[英]making all input fields borders red when no one at least was filled in
I am not good enough with javascript. 我对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 的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 的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. 您可以通过设置CSS样式来实现。 This is done most easily with jQuery syntax. 使用jQuery语法最容易做到这一点。
$(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.