[英]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! 我有2个文本框和一个按钮! When I click on button it should write 1 in the chosen text box but my code is not working. 当我单击按钮时,它应该在所选文本框中写1,但是我的代码不起作用。
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>
You can use onfocus property to perform this instead. 您可以使用onfocus属性来执行此操作。
HTML 的HTML
<input type="text" onfocus="myFocusFunction(this)">
<input type="text" onfocus="myPlaceholderFunction(this)">
Javascript Java脚本
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. 您可以先应用任何一个,然后再添加一个值,然后再添加一个占位符。
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 的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;
}
})
}())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.