I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.
HTML
<form id="myform" action="" method="post">
<input name="destination" class="form-control" type="text" >
<input name="thingstodo" class="form-control" type="text">
<input name="gsearch" class="form-control" type="text">
<button type="submit" name="search">Search</button>
</form>
JavaScript
$(function(){
$("#myform").submit(function(){
var valid=0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") valid+=1;
});
if(valid){
return true;
}
else {
alert("error: you must fill in at least one field");
return false;
}
});
});
Thanks
Modify the code like so
$(function(){
$("#myform").submit(function(){
var valid=0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") valid+=1;
else
$(this).style.border = "solid 1px red"
});
if(valid){
return true;
}
else {
return false;
}
});
});
You can do it by setting the CSS style. This is done most easily with jQuery syntax.
$(function(){
$("#myform").submit(function(){
var valid = 0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") {
valid++;
$(this).css("border-color", "initial");
}
else {
$(this).css("border-color", "red");
}
});
if (valid > 0) { return true; }
else { return false; }
});
});
How about this ?
$(function(){ $("#myform").submit(function(){ var dirty = false; $('input[type=text]').each(function(){ if($(this).val().length){ dirty = true; } }); if(!dirty){ $('input[type=text]').each(function(){ $(this).css('border','1px solid red'); }); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="myform" action="" method="post"> <input name="destination" class="form-control" type="text" > <input name="thingstodo" class="form-control" type="text"> <input name="gsearch" class="form-control" type="text"> <button type="submit" name="search">Search</button> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.