Reputation: 1
I want my HTML button will add one each time it is clicked but for some reason which I can't find, both the Yes and No button will add to the No box.... why?
<h3>Did this Help?</h3>
<br>
<form>
<input type="text" id="Yes" value="0"/>
<input type="button" onclick="incrementValue()" value="Yes" />
</form>
<br>
<br>
<form>
<input type="text" id="No" value="0"/>
<input type="button" onclick="incrementValue()" value="No" />
</form>
<script>
function incrementValue(yes)
{
var value = parseInt(document.getElementById('Yes').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('Yes').value = value;
}
function incrementValue(No)
{
var value = parseInt(document.getElementById('No').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('No').value = value;
}
Upvotes: 0
Views: 38
Reputation: 68923
both the Yes and No button will add to the No box.... why?
This is because the function names are same, your second function is overriding the first function.
You do not need to write same function twice. Just pass id
to the function in the button
like the following way:
function incrementValue(id){
var value = parseInt(document.getElementById(id).value);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById(id).value = value;
}
<h3>Did this Help?</h3>
<br>
<form>
<input type="text" id="Yes" value="0"/>
<input type="button" onclick="incrementValue('Yes')" value="Yes" />
</form>
<br>
<br>
<form>
<input type="text" id="No" value="0"/>
<input type="button" onclick="incrementValue('No')" value="No" />
</form>
Upvotes: 1
Reputation: 310
The fact is that you are using two times the same function incrementValue
, so it will use the last one defined : the one updating the 'No' field.
I updated your function so that it receives a parameter : the id of the button. So you can just use it to increment the right value.
function incrementValue(buttonId)
{
var value = parseInt(document.getElementById(buttonId).value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById(buttonId).value = value;
}
<h3>Did this Help?</h3>
<br>
<form>
<input type="text" id="Yes" value="0"/>
<input type="button" onclick="incrementValue('Yes')" value="Yes" />
</form>
<br>
<br>
<form>
<input type="text" id="No" value="0"/>
<input type="button" onclick="incrementValue('No')" value="No" />
</form>
Upvotes: 1