我想改变填充文本时填充的文本的颜色并失去焦点。我创建的表单要求填写至少一个字段。
我尝试了:required
,:valid
,但改变了所有领域的颜色
<form action="h.php" method="post" onsubmit="return formcheck()">
<div class="least1">
<label for="cb1">MAKAUT Development Fees:</label>
<input type="text" name="cb1" value="" placeholder="0"><br>
</div>
<div class="least1">
<label for="cb2">MAKAUT Registration Fees:</label>
<input type="text" name="cb2" value="" placeholder="0"><br>
</div>
<button>Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function formcheck(){
var total=0;
var fields = $(".least1")
.find("input").serializeArray();
$.each(fields, function(i, field) {
if (field.value!="")
total=total+parseInt(field.value);
});
// console.log(fields);
if(total==0){
alert("Fill at least one field.");
return false;
}
else{
if(confirm("Total amount to be paid= "+total))
return true;
else
return false;
}
}
jQuery(function ($) {
var $inputs = $('input[name=cb1],input[name=cb2]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', !$(this).val().length);
$inputs.css({
"border-color": "red",
"font-weight": "bold"
}) ;
});
});
</script>
所有字段都改变颜色而不是一个。
$(document).on("focusout","input",function(){
if($(this).prop('required'))
if(!$(this).val())
{
$(this).css({
"border-color": "red",
"font-weight": "bold"
}) ;
}
});
我只是用focusout方法更新你的方法。试试这个我希望它会帮助你。谢谢
$("input[name=cb1],input[name=cb2]").focusout(function(){
$(this).css({"border-color": "red", "font-weight": "bold"});
});
聚焦方法示例 - Link
<form action="h.php" method="post" onsubmit="return formcheck()">
<div class="least1">
<label for="cb1">MAKAUT Development Fees:</label>
<input type="text" name="cb1" value="" placeholder="0"><br>
</div>
<div class="least1">
<label for="cb2">MAKAUT Registration Fees:</label>
<input type="text" name="cb2" value="" placeholder="0"><br>
</div>
<button>Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function formcheck(){
var total=0;
var fields = $(".least1")
.find("input").serializeArray();
$.each(fields, function(i, field) {
if (field.value!="")
total=total+parseInt(field.value);
});
// console.log(fields);
if(total==0){
alert("Fill at least one field.");
return false;
}
else{
if(confirm("Total amount to be paid= "+total))
return true;
else
return false;
}
}
$("input[name=cb1],input[name=cb2]").focusout(function(){
$(this).css({"border-color": "red", "font-weight": "bold"});
});
</script>
当你有一个占位符存在时,你可以使用这个:
.myInput:not(:placeholder-shown):not(:focus) { /* change stuff */ }
如果表单没有值,则会显示占位符。因此,如果它有一个值/用户输入了一些数据(也就是:占位符 - 显示不是真的)并且它失去焦点(又名:焦点不是真的) - 将应用样式。