My problem is that I have a form in my HTML that I write to the database after filling it out.
The form consists of 7 labels with 7 input fields type=’number’
It all works so far, but it annoys me because it is designed for mobile phones that I have to keep clicking on the field and entering the number.
Now I have come up with a system that I can use between the input fields type=’text’,
I have one button each for increase and decrease. I intercept this with a JavaScript and let the will be manipulated to correspond.
This only worked to a limited extent. If I comment out the "Form Tag" it works. But as soon as I comment on the "form tag" again, nothing works anymore.
Now the question is. Where is the mistake or why it no longer works in this form?
HTML excerpt:
<form action="" method="post">
<label>Test1</label><br>
<input type="button" onclick="dec('number')" id="dec" value="-"/>
<input type="text" name="test1" id="number" value="0" min="0" size="3" />
<input type="button" onclick="inc('number')" id="inc" value="+" />
</form>
JS excerpt:
function inc(number) {
document.getElementById("number").value++;
}
function dec(number) {
if (document.getElementById("number").value != 0)
document.getElementById("number").value--;
}
3
Answers
[Related] There is a legacy scope chain issue originating from JavaScript 1.0 to 1.3 when there was no distinction between the programming language and what we now call a DOM API
For your case, the id idenfiers inside the form are causing troubles because they have the same names as the functions. Please remove the id identifiers from the buttons
So, (A) change
to
and (B) change
to
Alternatively, change the id names are also ok (e.g. change id="dec" to id="dec2", and change id="inc" to id="inc2"), [or as the comment made by Geshode, you can also change the names of the functions]
The main issue here seems to be because you’re setting
id
of each button to beinc
anddev
, which in Javascript, any ID will become a global variable.It seems like when the button element is wrapped in
<form>
, it overrides theinc
anddec
variables to refer to the button element, instead of the function.Removing or renaming the id attribute of the button should fix the issue if the
id
attribute is actually not being used. But if theid
attribute is important, then renaming the function is much better.in a form, any form child element must use a name attribute, even the buttons.
there is no needs to use id attributes.