0

I am trying to get an elements id from another elements value and I just keeps returning null. Clicking on the first check box should show what the issue is that I am having.

<input id="test" type="checkbox" name="checkAddress" onclick="checkAddress(this)" value="66" /> <input id="rrrr66" type="checkbox" name="checkAddress" onclick="checkAddress(this)" value="33" /> <script> function checkAddress(checkbox) { if (checkbox.checked) { var testing = '"rrrr'+document.getElementById("test").value+'"'; alert(typeof testing); **<-- shows the correct type** alert(testing); **<-- shows the correct value** alert(document.getElementById(testing)); **<-- does not work** alert(document.getElementById("rrrr66")); **<--works** } } 

Demo Of issue

2 Answers 2

3

Remove the quotation marks from the string:

var testing = 'rrrr'+document.getElementById("test").value; 

Quotation marks are for the parser to indicate a string literal. The quotation marks are not actually part of the value. What you are currently doing is equivalent with

document.getElementById('"rrrr66"') 

Compare these two outputs:

console.log("foo bar"); // foo bar console.log('"foo' + ' bar"'); // "foo bar" 
Sign up to request clarification or add additional context in comments.

Comments

0

1

Get the value of test and add rrrr before:

var testing = "rrrr"+document.getElementById("test").value; 

2 Do the trick

document.getElementById(testing) 

This should work.

3 Comments

There a two elements, one has ID rrrr66.
Yes, but you're trying to document.getElementById(testing), when testing var is equal to '"rrrr'+document.getElementById("test").value+'"';, this is like document.getElementById('"rrrr'+document.getElementById("test").value+'"').
I'm not doing anything. But yes, that is the problem (I guess, not sure what exactly you are referring to), not that there is an element with ID test. Btw, your answer doesn't really include any information. What solution are you proposing?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.