I am making an html form that will allow the user to submit numbers. Instead of having the user enter numbers, I simply want them to be able to click a button to increase or decrease the number in the text input. The following important pieces of code does this exactly how I want:
Javascript:
<script type="text/javascript">
function increase (form) {
var val = form.h1.value;
val++;
form.h1.value = val;
}
function decrease (form) {
var val = form.h1.value;
val--;
form.h1.value = val;
}
</script>
HTML
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(this.form)" value="+">
<input type="button" onclick="decrease(this.form)" val开发者_运维技巧ue="-">
My problem is that I want to be able to use the 'increase' and 'decrease' functions for any of the other textboxes (such as h2, h3, etc.). I tried to change the code by adding a second parameter, id, and using it to determine which form element to update. It will not work though. Any help figuring out where I went wrong would be appreciated!
Javascript
<script type="text/javascript">
function increase (form, id) {
var val = form.id.value;
val++;
form.id.value = val;
}
function decrease (form, id) {
var val = form.id.value;
val--;
form.id.value = val;
}
</script>
HTML
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(this.form, h1)" value="+">
<input type="button" onclick="decrease(this.form, h1)" value="-">
Try
function increase (form, id) {
var val = form[id].value;
val++;
form[id].value = val;
}
and
<input type="button" onclick="increase(this.form, 'h1')" value="+">
<input type="button" onclick="decrease(this.form, 'h1')" value="-">
A form works as a dictionary where you can address its fields by name. You do this by using square brackets. The name of the field is a string, so that's why you have to pass 'h1'
instead of of just h1
.
Try making these changes:
In your form pass a string of the ID instead of a variable.
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(this.form, 'h1')" value="+">
<input type="button" onclick="decrease(this.form, 'h1')" value="-">
And in your JavaScript, change the way you are referencing the field int he form.
<script type="text/javascript">
function increase (form, id) {
var val = form[id].value;
val++;
form.id.value = val;
}
function decrease (form, id) {
var val = form[id].value;
val--;
form.id.value = val;
}
</script>
Instead of passing two parameters, you can directly pass the textbox element whose value needs to be changed. Try below changes.
<input type="textbox" name="h1" size="3">
<input type="button" onclick="increase(document.h1)" value="+">
<input type="button" onclick="decrease(document.h1)" value="-">
And your javascript functions will be like below.
<script type="text/javascript">
function increase (element) {
element.value = element.value++;
}
function decrease (element) {
element.value = element.value--;
}
</script>
精彩评论