0
$("input[type='checkbox']").change(function(){
  if(this.checked){
    if($(':checkbox:checked').length>1 && $('#qT').val()==1){
        $(this).prop( "checked", false );
    }
  }
});

this is the script to run And html looks like below

<div class=row>....
<div class="isCorrect">
    <span>correct</span>
    <input type="checkbox" class="form-check-input mx-1"value="1">
</div>...</div>
<div class=row>....
<div class="isCorrect">
     <span>correct</span>
     <input type="checkbox" class="form-check-input mx-1"value="1">
</div>...</div> 
etc etc

This code only checks the first check box. not any other.. I also tried

$("input[type='checkbox']").change(function(){
  if(this.checked){
    if($(':checkbox:checked').length>1 && $('#qT').val()==1){
        $(this).prop( "checked", false );
    }
  }
}).triger(change);

and many other ways

2
  • What are you trying to achieve? Commented Mar 1, 2022 at 2:36
  • i want to prevent checking the check box if already any one is selected. depend on some other conditions also.. Commented Mar 1, 2022 at 2:45

2 Answers 2

1

Your code is not working because your event handler is created before the dynamic checkboxes are. To bypass this, you can bind an event handler to the whole document or, for better performance, to the parent that contains all your checkboxes :

$(document).on('change',"input[type='checkbox']",function () {

    // your code here...

});
Sign up to request clarification or add additional context in comments.

Comments

0

This should work.

When dealing with dynamic elements you have to start your selector with an element that is not dynamic and is already on the page. I like using the on method when dealing with events because it gives you more control. As you see I then define the event and then select the dynamic element that I am targeting.

Here is another reference.

$("document").on("change", "input", function(){
  if($(this).checked && $('#qT').val()==1){
     $(this).prop( "checked", false );
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.