我有一个正常提交的表单,现在我有 2 个要求需要在点击提交按钮时完成,如果这些要求完成,那么数据需要保存在数据库中
1) Border of the input boxes get highlighted if input boxes are left empty
2) If the image upload is left empty, a written message below the upload button should appear saying that the image is missing
3) The form should not get submitted till all input boxes and image upload are filled
4) Would also appreciate if someone could tell how I can use this code for all input boxes together instead of using separately for each one
目前,当我点击提交按钮时,如果框为空,它会突出显示输入,但之后也会提交表单,图像消息也不会出现
表单代码
<form action="<?php echo base_url(); ?>profile/add_profile" method="post" >
<input id="user" type="text" />
<input id="pwd" type="text" />
<input type="file" class="form-control modalcontrol" name="profile_img" id="profile_img" required>
<span class="fileuploadlabl">Upload</span>
<div class="login-btn">
<button type="submit" class="btn btn-primary" name="submit" >SUBMIT</button>
</div>
</form>
脚本代码
<script>
$( document ).ready(function() {
$(".login-btn").click(function(){
var user = $("#user").val();
var pwd = $("#pwd").val();
if(!user){
$("#user").addClass("makeRed");
}
else
{
$("#user").removeClass("makeRed");
}
if(!pwd){
$("#pwd").addClass("makeRed");
}
else
{
$("#pwd").removeClass("makeRed");
}
});
$("#user").click(function(){
$("#user").removeClass("makeRed");
});
$("#pwd").click(function(){
$("#pwd").removeClass("makeRed");
});
});
</script>
CSS 代码
.makeRed{
border: 2px solid red !important;
}
最佳答案
您需要简单地迭代所有的输入
来验证它们(行内注释)
$( document ).ready(function() {
$(".login-btn").click(function(){
$( "input, select" ).each( function(){ //iterate all inputs
var $this = $( this );
var value = $this.val();
$this.removeClass( "makeRed" ); //reset the class first
if ( value.length == 0 )
{
$this.addClass( "makeRed" ); //add if input is empty
}
});
});
$( "input,select" ).focus( function(){
$( this ).removeClass( "makeRed" ); //on focus of the input remove the markRed class
})
});
$(document).ready(function() {
$(".login-btn").click(function() {
$("input, select").each(function() { //iterate all inputs
var $this = $(this);
var value = $this.val();
$this.removeClass("makeRed"); //reset the class first
if (value.length == 0) {
$this.addClass("makeRed"); //add if input is empty
}
});
if ( $(".makeRed").length > 0 )
{
alert( "Some validation errors" );
}
});
$("input,select").focus(function() {
$(this).removeClass("makeRed"); //on focus of the input remove the markRed class
})
});
.makeRed
{
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="user" type="text" />
<input id="pwd" type="text" />
<input type="file" class="form-control modalcontrol" name="profile_img" id="profile_img" required>
<span class="fileuploadlabl">Upload</span>
<div class="login-btn">
<button type="submit" class="btn btn-primary" name="submit">SUBMIT</button>
</div>
</form>
关于javascript - 如果留空,则无法突出显示输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47530753/