If a checkbox is checked, other checkboxs will be disabled


#1

I have the following code. I now want to check the box if the checkbox is checked and disabled other checkboxes until the check box is cleared.

 <div id="gallery">
                        <span>
                        <input type="checkbox" name="ChekboxDefault" value="" />

                        </span>
                    </div>
                    <br />
                    <button type="button" onclick="Addchecked()">add checked</button>
                    <br />
<script>
    function Addchecked() {
     
        $('#gallery').append("<br/><span>     <input type='checkbox' name='ChekboxDefault' value='' /> </span>")
    }

</script>

#2

Hi @shabzadeh97, what have you tried so far to make this happen?


#3

Give all the checkboxes the same classname, and use the .not($(this)) selector to disable all the other checkboxes.

HTH,

^ _ ^


#4

Sounds like you’re looking for radio buttons?


#5

I create a number of dynamic checkboxes and I ask the user to select one, but the number of these check boxes is unknown.


#6

I think your method is responsive. But the problem is how can I create dynamic data for value.

<script>
    function Add() {
 
          $('#gallery').append("<br/><span>    <input type='radio'  name='contact' value="+t+"> </span>")
        
    }

</script>

#7

I used the following solution

I add this code to html code

  <span id="counter" hidden="hidden"></span>

and then

<script>
    $('#counter').html(0);

    function Add() {
        var count = Number($('#counter').html());
        count = count + 1;
        $('#counter').html(count + 1);
 
        $('#gallery').append("<br/><span>    <input type='radio'  name='contact' value="+count+"> </span>")
        
    }

</script>

#8

You are increasing the value of count twice in your function. Did you intend to do that?

V/r,

^ _ ^


#9

Adding one is done so much in programming there is a shorthand for it. Instead of count = count + 1 you can use count++ :slight_smile:


#10

I corrected both mistakes . Thanks ScallioXTX ,WolfShade


#11

Hi @shabzadeh97, there is no reason to store that value in the markup though – you can just use a regular variable for the counter:

var $gallery = $('#gallery')
var count = 0

$('.my-button').click(function addChecked () {
  count++
  $gallery.append('<input type="radio" name="contact" value="' + count + '" />')
})