Why my disable/enable checkbox is not working in JQuery?

jquery

61 观看

1回复

309 作者的声誉

I do not understan why this code is not working. Please, try to be specific in your anwer because it must be something really silly.

$("#cagree").on("change", function(e){
		  if($("#chbx").attr("checked")){
		    $("#submitbtn").button("enable");
		  } else {
		    $("#submitbtn").button("disable");
		  }
		  
		});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html> 
<html> 
<head> 
	<title>My Page</title> 
	<meta name="viewport" content="width=device-width, initial-scale=1"> 

</head> 
<body> 
<div data-role="page">

	<div data-role="content">	
		<label><input type="checkbox" name="checkbox-0" id="chbx" class="cagree"> I agree </input></label>
      <input type="button" value="Submit" id="submitbtn" class="submit" disabled/>
	</div><!-- /content -->

</div><!-- /page -->

</body>
</html>

作者: Jorge M. Nures 的来源 发布者: 2017 年 12 月 27 日

回应 1


1

60648 作者的声誉

决定

1.$("#cagree") need to be $(".cagree")

2.Use .is(":checked") to check that checkbox is checked or not

3.Instead of $("#submitbtn").button("enable") do $("#submitbtn").prop('disabled', false); and vice-versa

Working snippet:-

$(".cagree").on("change", function(e){ // it's class so use .
  if($(this).is(":checked")){ // use $(this) for current-object
    $("#submitbtn").prop('disabled', false); // it's property so use .prop
  }else{
    $("#submitbtn").prop('disabled', true);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html> 
<html> 
  <head> 
    <title>My Page</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 

  </head> 
  <body> 
    <div data-role="page">

      <div data-role="content">	
        <label><input type="checkbox" name="checkbox-0" id="chbx" class="cagree"> I agree </label>
        <input type="button" value="Submit" id="submitbtn" class="submit" disabled/>
      </div><!-- /content -->

    </div><!-- /page -->

  </body>
</html>

Note:-

enable and disable are properties so use .prop() to set them.

</input> is invalid so remove that.

作者: Anant Singh---Alive to Die 发布者: 2017 年 12 月 27 日
32x32