1

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

7
  • Perhaps you can use onfocus event? Commented Jan 23, 2019 at 20:33
  • I am not very sure what you are trying to accomplish but you may want to add the eventhandler function to the textbox itself. Commented Jan 23, 2019 at 20:34
  • @Umair any code you can help me with would be really helpful. Hoping you understood what i want to achieve here Commented Jan 23, 2019 at 20:39
  • Can you use jQuery? Commented Jan 23, 2019 at 20:47
  • @MerakMarey i do have some understanding of jquery but im new so a snippet would be helpful. Commented Jan 23, 2019 at 20:50

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Aplogies for the late reply , it worked thanks Eric.

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.