views:

167

answers:

5

If I have a bunch of numbered fields in a web form, like an invoice:

< input type="text" name="Item1" /><input type="text" name="Desc1" /><br />
< input type="text" name="Item2" /><input type="text" name="Desc2" /><br />
< input type="text" name="Item3" /><input type="text" name="Desc3" /><br />

Using JQuery, how would I select the first, then reference the second from the first?

I have something like $("input[id^='Item']"), which selects each Item pretty well, but from each of these I need to reference the corresponding Desc and fill it with a result.

Say for instance the user types something in Item1 and onBlur I want to copy the content to the corresponding Desc.

Thanks

+5  A: 

This could be a possible solution:

$("input[name^=Item]").blur(function() { 
   var n = $(this).attr("name").match(/\d+/);

   $("input[name=Desc" + n + "]").val($(this).val());
});
Philippe Leybaert
Now that is a great use of RegEx. Good stuff!
Dr. Zim
Ended up using var n = $(this).attr("id").match(/\d+/); $("span[id='Desc"+n+"']").html( and the content goes here ); Thanks a bunch.
Dr. Zim
+4  A: 

next?

http://docs.jquery.com/Selectors/next#prevnext

easement
Wow, could it be that simple? LOL
Dr. Zim
+2  A: 
$("input[name^=Item]").blur(function() {
    var reg = new RegExp("/[0-9]+$/")
    var number = reg.exec($(this).attr("id"));
    $("input[name=Desc"+number+"]").val($(this).val());
}
A: 

If I understand your question correctly. The easiest way I can think of to do that is to put a blur listener on each item.

$("input[id^='Item']").blur(function(event){
    $(event.target).attr('the attribute you want to change', $(event.target).val()) 
})

this will grab all the inputs and adds a blur listener that changes an attribute based on the value input.

SethZanderJensen
A: 

A variation:

$("input[name^=Item]").blur(function(){
    $($(this).replace(/^[^0-9]+/, 'Desc')).val($(this).val());
});
Dmitri Farkov