2

I have a table of values and need to get the value of a row's checkbox. What is happening is: If I have a table with 4 rows of data and select the top row, the binding event is being fired for each corresponding row in the table with the same class name. I only want it to fire once and return the value of the row's checkbox that was changed (need both checked and unchecked trigger). Any help is appreciated.

See my fiddle at http://jsfiddle.net/radi8/MgFuu/5/.

I am using the following class (fixed using suggestions by Rob W and Richard D, thanks guys!):

 var RequiredField = {
     init: function() {
         // bind a control structure around the PSN selection table
         var psn = $(".psnselect");
         //for (var i = 0, ii = psn.length; i < ii; i++) {
         //    $(psn).change(RequiredField.psnSelect);
         //}
         psn.change(RequiredField.psnSelect);

     },
     psnSelect: function(event) {
         var evtName = event.currentTarget.name;
         var checked = event.currentTarget.checked;
         var val = event.currentTarget.value;
         alert('PSN Selection: ' + evtName);
     }
 };
 RequiredField.init();

2 Answers 2

1

Remove the for loop. jQuery automatically attaches events to all elements which match the selector. psn is already a jQuery object, so the $ wrapper can also be omitted:

psn.change(RequiredField.psnSelect);

Fixed demo: http://jsfiddle.net/MgFuu/6/


If you want to select the nth element of a jQuery collection, either of these methods can be used:

var n = 0;    // The first element (index 0)
psn.eq(n);    // = jQuery wrapped first element
psn.get(0);   // = DOM element
psn[0];       // = psn.get(0) = DOM element
Sign up to request clarification or add additional context in comments.

Comments

0

No need to have the for loop.

init: function() {
    $(".psnselect").change(RequiredField.psnSelect);       
},

The event will automatically be bound to all elements that match the selector

http://jsfiddle.net/infernalbadger/MgFuu/7/

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.