On 21/12/06, Klaus Hartl <[EMAIL PROTECTED]> wrote: > jpl schrieb: > > Hello, > > > > I have a form with 5 checkboxes and 5 text inputs. Each checkbox is related > > to a > > text input. > > I want a checkbox to be checked when its related text input is clicked... > > easy > > with jquery: > > $("#text_input_id").click( function() { $("#checkbox_id").get(0).checked = > > true; > > } ); > > > > But I have a problem doing this in a loop. Here is a test case with > > jquery-1.0.4, FF 2.0: > > > > <html> <head> <script src="jquery.js"> </script> </head> <body> > > <form> > > <input type="checkbox" name="a" id="a" value="1" /> <input type="text" > > name="a_date" id="a_date" /> > > <input type="checkbox" name="b" id="b" value="1" /> <input type="text" > > name="b_date" id="b_date" /> > > </form> > > <script> > > $(document).ready(function() { > > for each (var name in ["a", "b"]) { > > $("#"+name+"_date").click( function () { > > $("#"+name).get(0).checked = true; > > //alert(name); > > }); > > } > > }); > > </script> > > </body> </html> > > > > It seems like the creation of the function to bind is defered: it is always > > the > > last checkbox that is checked, whatever the text input I clicked on. > > > > What is the problem? Should I do this in another way? > > How could I easily debug what is bound on document load? > > > First of all I have never seen a "for each in" loop in JavaScript. That > should give you an error on the console. Second if you meant a for in > loop: do not use these for Arrays. > > For debugging try the excellent FireBug extension. > > Here's how I would do it. You don't need that id overhead and let's say > you give the containing form an id of "my-form": > > $(function() { > $('#my-form [EMAIL PROTECTED]"text"]').each(function() { > $(this).focus(function() { > $(this).prev('input').eq(0).get(0).checked = true; > }); > }); > }); > > Note that I use focus here for people using the keyboard (tab) instead > of the mouse. > > > -- Klaus
Can't you cut the amount of code down even further (you don't need to use each, then focus)? $(function() { $('#my-form [EMAIL PROTECTED]"text"]').focus(function() { $(this).prev('input:eq(0)').attr('checked',true); }); }); _______________________________________________ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/