简体   繁体   中英

I have 2 text Boxes and one button! When I click on button it should write 1 in the chosen text box but my code is not working

I have 2 text Boxes and one button! When I click on button it should write 1 in the chosen text box but my code is not working.

my code:

function one() {
var number = "1";


if (document.getElementById("txt1").focused) {
    document.getElementById("txt1").value = number;
}
else if (document.getElementById("txt2").focused) {
    document.getElementById("txt2").value = number;
}
else {

}

You can do some thing like this:

<input type="text" onfocus="onFocus(this)" id="itext1"></input>
<input type="text" onfocus="onFocus(this)" id="itext2"></input>
<button onclick="setValue()">ClickMe</button>
<script>
    var selectedDOM = undefined;

    function setValue() {
        if (selectedDOM) { //selecteddom is present set text to it
            selectedDOM.value = 1;
        }
    }

    function onFocus(e) {
        selectedDOM = e;//register the last dom selected inside the variable.
    }
</script>

Full working code here

You can use onfocus property to perform this instead.

HTML

<input type="text" onfocus="myFocusFunction(this)">
<input type="text" onfocus="myPlaceholderFunction(this)">

Javascript

function myFocusFunction(x) {
   x.value = "1";    
}

function myPlaceholderFunction(x) {
   x.placeholder = "1";    
}

Above are two approaches to set value in text box when focused. You can apply any of them prior will add a value and later will add a placeholder instead.

Working Demo : JSFiddle

You can do like this

<div>
    <input type="text" id="txt1">
    <input type="text" id="txt2">    
        <button type ="button" id='button'>Click Me </button>
</div>

JavaScript

(function(){
    var number ='1';
    var _thisId=null;   
     var _button = document.getElementById('button');
     _button.addEventListener('mouseover',function(){
     _thisId = document.activeElement.id;
    },false)

    _button.addEventListener('click',function(){
        if(_thisId =='txt1'){
                document.getElementById("txt2").value = "";
                document.getElementById("txt1").value = number;     
            }
            else if(_thisId =='txt2'){
                document.getElementById("txt1").value = "";
                document.getElementById("txt2").value = number;     
                }
        })
}())

jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM