By default, I have a value for an input field that tells the user what to put there (e.g. Enter your account number). I have a script on it that hides the value when you click on it and it reappears when you click away.
The field is not required though. If a user doesn't enter information into the field, the default value gets sent and causes an error because it allows numerical digits only. How can this default value be changed to nothing if the user doesn't fill in his account number?
You can validate your input before form post like this:
Markup:
<input type="text" id="txtAcc" name="txtAcc" value="Enter your account number..." />
<input type="button" id="btnSubmit" name="btnSubmit" onclick="validate();" value="Submit" />
Javascript:
// Validate input before form post
function validate(){
var txtAcc = document.getElementById("txtAcc");
var accNum = parseInt(txtAcc.value);
if (!accNum || txtAcc.value == "Enter your account number..."){
// Set default Account number
txtAcc.value = 0;
}
}
Don't use default values. Use placeholders.
<input type="text" placeholder="Real Name">
Alternatively, just ignore these values on the server side:
if ($_POST["realname"] == "Real Name") { real_name_not_provided(); }
If you still insist on using JavaScript (for better browser support), you can use something like the following:
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
Taken from this article (which was first on Google by the way). Please read the article before using this code. It might require more code from the article.
You should be using the HTML5 placeholder attribute on browsers that support it.
The real answer is why is the validation code not smart enough to ignore the default text?