1

Quick question, is this code possible?

function respond (primary_id) {
var answer = $('id_of_' + primary_id).val();    
}

I've tested it out but the error produced does not directly point to this line of code, but another that is using this variable answer so I can't be sure if this is causing the problem or something else. If this can't work, then what is an alternative?

2
  • 2
    Don't forget the # on id selectors =) Commented Aug 15, 2012 at 6:51
  • Silly me. I forgot to add the #. Commented Aug 15, 2012 at 7:04

3 Answers 3

3
$('id_of_' + primary_id)

Would point to all elements:

<id_of_xxx>

Which don't exist in any version of HTML I've seen...

If you're looking for an element with that ID,

$('#id_of_' + primary_id)

Would be the way to go.

Also, don't forget to return the value:

function respond (primary_id) {
     var answer = $('id_of_' + primary_id).val();    
     return answer;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can find it very easily on http://api.jquery.com/id-selector/

Here, you should use '#' before the element Id like this.

function respond (primary_id) {
      var answer = $('#id_of_' + primary_id).val();    
}

Comments

1

Well if you are selecting an element based on an id it should be preceded by a # so your code should be

var answer = $('#id_of_' + primary_id).val();

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.