문제

I have in my html page a list of checkboxes

 <input type="checkbox" id="example1" value="1">
 <input type="checkbox" id="example2" value="2">

generated via php, according to the content of a database table, containing the details of the elements to be displayed. I don't know how much checkboxes i will have at any moment in the page, for the number can change according to the database content.

Now, in order to reply to the hit of a checkbox i was thinking to use

 $('#example').mousedown(function() {   
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
 });

but this way means to know the name/id of the checkbox which i don't know, cause it is generated... So, how i can generate my checkbox and control which was hitten via jquery?

도움이 되었습니까?

해결책

Try giving a class to your checkboxes :

<input type="checkbox" class="cls1" id="example1" value="1">
<input type="checkbox" class="cls1" id="example2" value="2">

Then, when binding the mousedown event, instead of selecting them by their id, select them with that class :

 $('.cls1').mousedown(function() {   
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
 });

This is to stay as close as possible from your original code, which may not be the best. Without a broader view on it it's hard to tell. Note that in the case you're adding dynamically the checkboxes clientside (which is not the case I presume cause you talk about generating it with PhP) you would need a different selector in order to use what is called delegated events

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top