23

I have some code which uses a selector in a loop.

This works:

document.getElementById("new_grouping_"+i).value

This does not: $("#new_grouping_"+i).value

Is there a way to do this using jQuery?

3 Answers 3

28

You should use the val() function:

var myValue = $("#new_grouping_"+i).val(); // to get the value

$("#new_grouping_"+i).val("something");    // to set the value 
Sign up to request clarification or add additional context in comments.

Comments

12

$("#new_grouping_"+i).val() gets you the value of a form.
$("#new_grouping_"+i).text() gets you the text of an html element.
$("#new_grouping_"+i).html() gets you the html of an html element.

$("#new_grouping_"+i).val('value') sets the value of a form.
$("#new_grouping_"+i).text('value') sets the text of an html element.
$("#new_grouping_"+i).html('value') sets the html of an html element.

$("#new_grouping_"+i).append('value') prepends something at the beginning of an element $("#new_grouping_"+i).append('value') appends something at end of an element

$("#new_grouping_"+i).before('value') places something before an element $("#new_grouping_"+i).after('value') places something after an element.

See More: jQuery Manipulation

2 Comments

Firefox gives me: "$("#new_grouping_desc_"+i).value is not a function" when I add the empty paren after value
Updated*. Was two letter off of the actual function.
2

# is important for selector. Here I am setting value to span.

var i="spanId";
$("#"+ i).html("hello").show();

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.