我有2个文本框和一个按钮!当我点击按钮,它应该写1在选定的文本框,但我的代码不工作
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
我有2个文本框和一个按钮!当我点击按钮时,它应该在选择的文本框中写1,但我的代码不工作。
我代码:
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 {
}
你可以这样做:
<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>
完整的工作代码在这里
您可以使用onfocus属性来执行此操作。