redconservatory
redconservatory

Reputation: 21924

jQuery change input box by preceding label

I have the following bit of HTML:

<label>First Name</label><input name="Question62" type="text" value="" />

Unfortunately because I am creating several forms, the "name" of the input box will change however the "label" contents will stay the same ("First Name").

Is there a way to change the input value by the preceding label? (instead of an id tag in the input box)?

[Edit] Answer given below, code provided in case anyone needs it:

var firstName = $("label:contains('First Name')");
firstName.next('input').val(obj.first_name);

Upvotes: 0

Views: 317

Answers (2)

Engineer
Engineer

Reputation: 48793

Try like this:

var labelContent = "First Name";
$('label:contains('+labelContent+') ~ :text')​.val( 'Some value' )

Upvotes: 1

Jo&#227;o Gon&#231;alves
Jo&#227;o Gon&#231;alves

Reputation: 4002

You want jquery .next() method.

http://api.jquery.com/next/

Upvotes: 1

Related Questions