Reputation: 270
I am having 1 text field with number of buttons each having value of their own.
In the code below as i have a single input field i have used it to update the value based on button value to the input field id. How can i know the which input field i have selected before the button click to pass the button value to the input field when there are multiple input fields??
var x,y;
function first(){
var y=1;
document.getElementById("how").value=y;
}
function second(){
var x=2;
document.getElementById("how").value=x;
}
<input type="button" onclick="first()" value="1" id="01"/>
<input type="button" onclick="second()" value="2" id="02"/>
<input type="text" value="" id="how"/>
Let me know how this can be achieved in the easiest way
Upvotes: 1
Views: 670
Reputation: 842
You can create a single onfocus function for each of the inputs, and have it store a global reference of the last focused input. Then use the global reference in your button click functions.
Code example:
<input type="button" onclick="first()" value="1" id="01"/>
<input type="button" onclick="second()" value="2" id="02"/>
<input type="text" onfocus="inputFocus(this)" value="" id="input1"/>
<input type="text" onfocus="inputFocus(this)" value="" id="input2"/>
<input type="text" onfocus="inputFocus(this)" value="" id="input3"/>
<script>
var x,y;
var focusObj;
function first(){
var y=1;
if(focusObj) focusObj.value = y;
}
function second(){
var x=2;
if(focusObj) focusObj.value = x;
}
function inputFocus(obj) {
focusObj = obj;
}
</script>
Upvotes: 2