Glen Glen -4 years ago 92
HTML Question

Get the value of incremented input

I have two buttons which either increment or decrement an input value. I don't know how to retrieve the value later on submit of the result. My current attempts have either resulted in 'undefined' or '0'.

Thanks in advance for any advice

$('.plus').click(function(e){
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal)) {
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});


$(".minus").click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal) && currentVal > 0) {
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});


//attempting to get value
var value = document.getElementById( 'inputval' ).val();


$('#submitscore').click(function() {
alert(value);
});


My HTML

<span class="input-group-btn">
<button class="btn btn-secondary btn-success minus" field='minusfield' id ="minus" type="button">-</button>
</span>
<input type="text" name="inputval" id="inputval" value="0" class="gh form-control"/>
<span class="input-group-btn">
<button class="btn btn-secondary btn-success plus" id="plus" field='plusfield' type="button">+</button>
</span>
<button type="button" id ="submitscore" class="btn btn-md btn-orange">Submit</button>

Answer Source

You are attempting to get already assigned value.

Change your code to this

$('#submitscore').click(function() {
        alert($('#inputval').val());
    });

and it should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download