Javascript: How to use same button for different text input?
Suppose I have 2 input elements with only 1 button. I want the button to do a function 开发者_开发问答for one input element at a time according to which one is currently being focused but I don't know how to capture focusing status of each element.
Please consider this example:
<head>
<script type="text/javascript">
var id_box = document.createElement('input');
id_box.id = 'id_box';
id_box.type = 'text';
div.appendChild(id_box);
var weight_box = document.createElement('input');
weight_box.id = 'weight_box';
weight_box.type = 'text';
div.appendChild(weight_box);
function showLetter() {
if (id_box is being focused){
document.getElementById('id_box').value = 'ABC';
}
if (weight_box is being focused){
document.getElementById('weight_box').value = 'ABC';
}
}
</script>
</head>
<body>
<button onclick="showLetter()">ABC</button>
</body>
Any idea? Thank you very much.
The minute you click the button, the textfield loses focus anyway. Try trapping the OnFocus method for each text box and set a variable to the instance of the textfield. This way you have the latest text field and you don't need your if statement.
If an input has focus and if the user then clicks a button the input will lose focus instantly so you cannot detect which input has focus in the way you want.
You could create a variable that stores the "current" input by attaching an event handler to each input for the onFocus
event.
Demo on jsFiddle: http://jsfiddle.net/P58sx/1/
var current_input;
function showLetter() {
current_input.value = 'ABC';
}
function setCurrentInput() {
console.log(this);
current_input = this;
}
var id_box = document.createElement('input');
id_box.id = 'id_box';
id_box.type = 'text';
id_box.addEventListener("focus", setCurrentInput);
div.appendChild(id_box);
var weight_box = document.createElement('input');
weight_box.id = 'weight_box';
weight_box.type = 'text';
weight_box.addEventListener("focus", setCurrentInput);
div.appendChild(weight_box);
I would recommend trying the onFocus
event handler.
One trick would be to declare a variable and setting it in onFocus
event of each field. Then in the button code you can check what was the last field that was focused before the click on the button.
精彩评论