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