iJade
iJade

Reputation: 23811

JQuery script for one checkbox selection from group not working while adding a checkbox dynamically

i'm using the below jquery script to disable user from selecting more than 1 check box of same name at a time

 $("input:checkbox").click(function () {
    if ($(this).is(":checked")) {
        var group = "input:checkbox[name='" + $(this).attr("name") + "']";
        $(group).prop("checked", false);
        $(this).prop("checked", true);
    } else {
        $(this).prop("checked", false);
    }
});

And here is the check boxes

 <div class="ChekMarkWrap">
  <input id="chkFilm_4" type="checkbox" name="four" style="margin-left:2px;" /><br />film
 </div>

 <div class="ChekMarkWrap">
  <input id="chkTv_4" type="checkbox" name="four" /><br />tv
 </div>

 <div class="ChekMarkWrap">
  <input id="chkWeb_4" type="checkbox" name="four" /><br />web
 </div>

 <div class="ChekMarkWrap">
  <input id="chkStage_4" type="checkbox" name="four" /><br />stage
 </div>

It works well and good until i add a new check box dynamically.i'm binding the above jquery script on document.ready()

Upvotes: 0

Views: 515

Answers (4)

Sergio
Sergio

Reputation: 28845

Try like this:

$("body").on('click',input:checkbox,function () {
    if ($(this).is(":checked")) {
        var group = "input:checkbox[name='" + $(this).attr("name") + "']";
        $(group).prop("checked", false);
        $(this).prop("checked", true);
    } else {
        $(this).prop("checked", false);
    }
});

When you add new content you need to append it to the DOM.

But you can target a parent element that was not added after the DOM was loaded to be able to reference/attach-event to it using .on() and passing the selector as I wrote above on the first line of your code..

Upvotes: 2

Nicklas Nygren
Nicklas Nygren

Reputation: 2605

Fiddle: http://jsfiddle.net/3hcFp/2/

That method binds the click event only once, so elements added after that code has been run will not have the event bound. What you need to do is set up a listener instead, like so:

$('body').on('click', 'input:checkbox', function () {
    // Do some stuff
}

In the fiddle, i have wrapped the checkboxes in a form#exampleForm, and replaced body in the above example with that.

EDIT: Updated fiddle with live example of adding more checkboxes.

Upvotes: 3

Ali Shah Ahmed
Ali Shah Ahmed

Reputation: 3333

You can try using delegates. Something like this:

$(".ChekMarkWrap").delegate('click','input:checkbox',function () {
    //your functionality
});

For Reference: jQuery Documentation

Upvotes: 0

RRikesh
RRikesh

Reputation: 14411

You should use delegated events. Your code is running on document ready. Nothing is bound to new elements.

$("your-form-selector").on('click', ':checkbox', function(){
//your code here.
});

Upvotes: 0

Related Questions