Introduction: I'm creating a form using bootstrap and I have different input groups with the same structure and functionality.
All of them have a '-' button on the left and a '+' button on the right of the input field and, when one of them is pressed, the input value has to change.
Problem: As the buttons are inside a div with class="input-group-btn" and they are not siblings of the input field, I don't know which is the best way to select it.
I have managed to make it work but I'm not sure if it's the best way to do it.
JavaScript and HTML
$(".increase").click(function() {
var amount = parseInt($(this).parents('.input-group').children('input').val());
if (amount < 20) {
$(this).parents('.input-group').children('input').val(amount + 1);
}
});
$(".decrease").click(function() {
var amount = parseInt($(this).parents('.input-group').children('input').val());
if (amount > 0) {
$(this).parents('.input-group').children('input').val(amount - 1);
}
});
<form class="form-inline">
<div class="form-group">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default decrease"><span class="glyphicon glyphicon-minus"></span>
</button>
</div>
<input type="text" class="form-control" id="capacity" value="0" disabled="">
<div class="input-group-btn">
<button type="button" class="btn btn-default increase"><span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default decrease"><span class="glyphicon glyphicon-minus"></span>
</button>
</div>
<input type="text" class="form-control" id="rooms" value="0" disabled="">
<div class="input-group-btn">
<button type="button" class="btn btn-default increase"><span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</div>
</form>
Bootply: http://www.bootply.com/EA5a48SCdg
1 Answer 1
If the input group perhaps contains additional input elements this won't work. I think that you should bind the button to the input field by declaring a new attribute to the button which is connected to the input's id
. Like so:
<button type="button" class="btn btn-default increase" data-bind="rooms"><span class="glyphicon glyphicon-plus"></span></button>
It now contains the input ID which this button is connected to. Now in your JavaScript try something like this:
$(".increase").click(function() {
var input = $('#' + $(this).data('bind'));
input.val(input.val++);
});
It will use the data-bind attribute to connect to the specific input element and increase this value by 1 (++).
Explore related questions
See similar questions with these tags.