Reputation: 9787
I'm trying to validate a form but with no labels, all the messages in the same input.
I have the html that works as I want but with the jQuery I have problems with the elseif and else.
I am trying to say:
- if the input name is still name give the message name is missing (this seems to work)
- if the input address is still address give the message address is missing (it does not work)
- if the input address and the input name are not address or name submit the form (it does not work)
I have the example here: http://jsfiddle.net/4ervc/20/
HTML:
<form id="form" action="#">
<input type="text" name="name" id="name" value="name"
onfocus="if (this.value=='name'||'name is missing') this.value = '';"
onblur="if (this.value=='') this.value = 'name';" />
<br />
<input type="text" name="address" id="address" value="address"
onfocus="if (this.value=='address'||'address is missing') this.value = '';"
onblur="if (this.value=='') this.value = 'address';" />
<br />
<input type="submit" name="submit" id="submit">
</form>
JQUERY:
$(function(){
$("#form").submit(function (e) {
if ($('#name').val("name")) {
e.preventDefault();
$('#name').val("name is missing");
}else if ($('#address').val("address")) {
e.preventDefault();
$('#address').val("address is missing");
}else{
$("#form").submit;
}
});
})
Upvotes: 0
Views: 165
Reputation: 13730
A few issues with your original code:
$("#form").submit;
was incorrect, should be $("#form").submit();
$('#name').val() === 'name'
, not $('#name').val('name')
The below fixes these things by using a simple flag, and checking each field separately. The submit call is also fixed.
Try this: http://jsfiddle.net/4ervc/21/
$(function() {
$("#form").submit(function(e) {
//assume valid form
var valid = true;
if ($('#name').val() === 'name') {
e.preventDefault();
$('#name').val('name is missing');
valid = false;
}
if ($('#address').val() === 'address') {
e.preventDefault();
$('#address').val('address is missing');
valid = false;
}
if (valid) {
$('#form').submit();
}
});
});
Also - just a note on code smell - you should try to use either single or double quotes consistently through your script. You've used a bit of both which isn't ideal (but will work).
Upvotes: 0
Reputation: 546
you are setting a value "name"
try to use this:
$('#name').val() == "name"
inside you if statement
Upvotes: 1