Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10541

Dynamic Checkbox selector in jquery

I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)

ModellingTagID_1201 ModellingTagID_1202 ModellingTagID_1203 ModellingTagID_1204

I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?

 $jqLib("#ModellingTagID_*").change(function(){
        var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
        $jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
    });

Upvotes: 0

Views: 262

Answers (3)

Sandip Ghosh
Sandip Ghosh

Reputation: 719

From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.

   cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
   cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
   cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">

And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.

$(document).ready(function(){
    $('.someclass').on('change', function() { 
        alert($(this).attr("id"));
    });
});

Upvotes: 0

Saurabh Solanki
Saurabh Solanki

Reputation: 2204

you can apply same class to all those checkboxes

<li><input type="checkbox" id="yourcbid1" name="x" value="1" class="yourcbclass" /> cb1</li>
  <li><input type="checkbox" id="yourcbid2" name="x" value="1" class="yourcbclass" /> cb2</li>

and then you can make function for it's change event like this.

$(function(){
$('.yourcbclass').on('change', function() { 
    if($(this).is(':checked')) 
    {
       //do your stuff here
    }
});
});

see if this helps..

Upvotes: 1

Harveer Singh Aulakh
Harveer Singh Aulakh

Reputation: 356

Very simple using this way:--

$("#envoyer").click(function(e) {
    var myArray = [];
    $(":checkbox:checked").each(function() {
        myArray.push(this.value);
    });
    
    if(myArray == ''){
    alert('Please check');
    }else{
    alert("Checked: " + myArray.join(","));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

    <body>
    one<input type="checkbox" name='checkbox0' value="one_name" checked>
   two<input type="checkbox" name='checkbox1' value="one_name1">
   three<input type="checkbox" name='checkbox2' value="one_name2">
        <input type="button" id="envoyer" value="Envoyer Reponse"  />

    </body>
</html>

Upvotes: 0

Related Questions