Abishek Fernando
Abishek Fernando

Reputation: 99

get value of input box by id stored in a variable?

I am wondering how to get the value of a input box by storing the id in a variable then fetching the value by that id variable. Here is what I have tried.

<script>
    var c=$("#inp").val();
    var temp = "i"+c;
    var obj = document.getElementById(temp).value;
    alert(obj);
</script>

<input type='text' class='form-control' value='$q6[$t2]' id='inp'>/php is used/

Upvotes: 0

Views: 9775

Answers (3)

ThisClark
ThisClark

Reputation: 14823

Your code works, but maybe you're doing something in the wrong order like putting the script before the element on the page. If your elements are in the following order, then it will work.

<input type="text" id="i" value="asdf" />
<script>
    var temp = "i";
    var obj = document.getElementById(temp).value;
    alert(obj);
</script>

edit

Based on your question's edits, given this input:

<input type='text' class='form-control' value='$q6[$t2]' id='inp'>

The value of c may not be what you think it is.

var c = $("#inp").val(); //equals $q6[$t2] exactly

By adding an i to the front of it, you get exactly that - i$q6[$t2] now the only way your script is going to work is if you have another element on the page with that ID.

<input type='text' id='i$q6[$t2]' value='output' />

I wonder is it really what you want to accomplish? If so, this snippet demonstrates it.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' class='form-control' value='$q6[$t2]' id='inp'>
<input type='text' id='i$q6[$t2]' value='output' />
<script>
    var c=$("#inp").val();
    var temp = "i"+c;
    var obj = document.getElementById(temp).value;
    alert(obj);
</script>

Upvotes: 5

alessandrio
alessandrio

Reputation: 4370

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-control' value='test' id='inp'>
<br>
<input type='text' class='form-control' value='$q6[$t2]' id='itest'>
<script>
var inp = $("#inp");
function chng(){
    var c=$("#inp").val();
    var temp = "#"+"i"+c;
    var obj = $(temp).val();
    alert(obj);
}
chng();
inp.on("change", chng);
</script>

Upvotes: 2

Domino
Domino

Reputation: 6778

When you call getElementById, you get a live node. That means its properties will update dynamically as the element in the page is modified (resized, typed into, selected). However, if you copy the value in a variable, this stored value won't update when you type in the input. That might be the cause of your problem here.

You need to update that variable when the "change" event is triggered for the input.

var myVal = null;

document.getElementById(temp).addEventListener("change", function(e) {
    myVal = e.target.value;
    alert(e.target.value);
});

Upvotes: 1

Related Questions