如何使用JavaScript选择输入值为空而不是空?

时间:2018-01-25 20:38:34

标签: javascript jquery

点击提交按钮并添加以下条件后,如何选择输入:空输入:不(:空)值:

  1. 如果值为空,请在点击更改背景颜色后。

    (它在输入Text3 中看不到)

  2. 如果值不为空,请在点击后添加以下三个条件:

    (它在我的示例代码中无效)

  3. •{cursor:not-allowed;} • 只读 •更改背景颜色

    以下是我的示例代码:

    		$(".signupbtn").on('click', function() {
    		    $("input").filter(function() {
    		        return this.value.length !== 0;
    		    }).val("Successfully Received!");
    		    $("input:empty")
    		        .css("background", "rgb(255,220,200)");
    
    		    $("input:not(:empty)").style.cursor = "not-allowed";
    		    $("input:not(:empty)")
    		        .css("background", "rgb(220,20,60)");
    		})
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    	<form action="" method="POST" onsubmit="return false;">
    	<input class="form-control" type="text" placeholder="" name="firstname" value="">
    	<input class="form-control" type="text" placeholder="" name="firstname" value="">
    	<input class="form-control" type="text" placeholder="" name="firstname" value="sss">
    	<button type="submit" class="signupbtn">Sign Up</button>
    	</form>

2 个答案:

答案 0 :(得分:1)

以下是您的代码的略微修改版本。首先使用input选择所有type of text代码,然后查看他们的length is 0 or not是否适用您想要的内容。

$(".signupbtn").on('click', function() {
   $('input:text').each(function(){
   
      if($(this).val().length == 0 ){
        $(this).css("background", "red");
      }else{
        $(this).val("Successfully Received!");
        $(this).css("background", "green");
        $(this).css("cursor","not-allowed");
      }
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="POST" onsubmit="return false;">
	<input class="form-control" type="text" placeholder="" name="firstname" value="">
	<input class="form-control" type="text" placeholder="" name="firstname" value="">
	<input class="form-control" type="text" placeholder="" name="firstname" value="sss">
	<button type="submit" class="signupbtn">Sign Up</button>
</form>

答案 1 :(得分:0)

&#13;
&#13;
		$(".signupbtn").on('click', function() {
		    $("input").filter(function() {
		        return this.value.length !== 0;
		    }).val("Successfully Received!");
		    $("input:empty")
		        .css("background", "rgb(255,220,200)");

		    $("input:not(:empty)").css("cursor","not-allowed");
		    $("input:not(:empty)")
		        .css("background", "rgb(220,20,60)");
		})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	<form action="" method="POST" onsubmit="return false;">
	<input class="form-control" type="text" placeholder="" name="firstname" value="">
	<input class="form-control" type="text" placeholder="" name="firstname" value="">
	<input class="form-control" type="text" placeholder="" name="firstname" value="sss">
	<button type="submit" class="signupbtn">Sign Up</button>
	</form>
&#13;
&#13;
&#13;