Reputation: 75
How can I focus an input when one of them is not filled. Right now I have this: http://jsfiddle.net/jalxob/ahQLC
$('#form').submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
$( ".email1" ).addClass( "focusred" );
$( ".name1" ).addClass( "focusred" );
return false;
} });
It shows the red focus but in both inputs although one of them is filled.
Thank you guys
Upvotes: 0
Views: 77
Reputation: 1931
Try this:
$('#form').submit(function() {
if ($.trim($("#email").val()) === "")
{
$( ".email1" ).addClass( "focusred" ).focus();
}
if ($.trim($("#user_name").val()) === "")
{
$( ".name1" ).addClass( "focusred" ).focus();
}
return false;
});
Demo: Fiddle
Upvotes: 0
Reputation: 575
$('#form').submit(function () {
var result = true,
focus_class = "focusred",
elements = $("input#user_name,input#email");
elements.each(function (index, element) {
var element = $(element);
if ($.trim(element.val()) === "") {
element.addClass(focus_class);
result = false;
} else {
element.removeClass(focus_class);
}
})
return result;
});
Update, better answer:
http://jsfiddle.net/SobiborTreblinka/6UgxJ/3/
Upvotes: 0
Reputation: 388436
Try
$('#form').submit(function() {
if ($.trim($("#email").val()) === "") {
$( "#email" ).focus();
return false;
}
if ($.trim($("#user_name").val()) === "") {
$( "#user_name" ).focus();
return false;
}
});
Demo: Fiddle
Upvotes: 2