Get Data-values From Selected Bootstrap Button Group (checkboxes) And Assign To Input
I'm trying to get the data-value from buttons similar to this, however, only when they are selected:
<
Solution 1:
I'm assuming you want all the values to that input. For the sake of simplicity, I am using a simple join with comma.
Here is the code you should use:
$('#genreButtons').find('input').on('change', function() {
var val = [];
$('#genreButtons').find('input:checked').each(function() {
val.push($(this).data('value'));
});
$('input[name="valueGenre"]').val(val.join(','));
});
Full snippet below or on jsfiddle.
$('#genreButtons').find('input').on('change', function() {
var val = [];
$('#genreButtons').find('input:checked').each(function() {
val.push($(this).data('value'));
});
$('input[name="valueGenre"]').val(val.join(','));
$('#debug').html(val.join(','));
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="btn-group"data-toggle="buttons"id="genreButtons"><labelfor="genre2"class="btn btn-default">Button 1
<inputdata-value="2"name="genre2"id="genre2"type="checkbox"></label><labelfor="genre4"class="btn btn-default">Button 2
<inputdata-value="4"name="genre4"id="genre4"type="checkbox"></label><labelfor="genre5"class="btn btn-default">Button 3
<inputdata-value="5"name="genre5"id="genre5"type="checkbox"></label><labelfor="genre7"class="btn btn-default">Button 4
<inputdata-value="7"name="genre7"id="genre7"type="checkbox"></label></div><inputtype="hidden"name="valueGenre"value=""><divid="debug"></div>
Solution 2:
first of all I think you are missing the name as id in
<inputtype="hidden" name="valueGenre" value="">
and using
$("#valueGenre").val($(this).val());
you should add the id in the input hidden
<inputtype="hidden" name="valueGenre"id="valueGenre" value="">
I just updated the input to a label and changed the val to append to explain better what was wrong: please see the snippet below:
$.each($("#genreButtons input:checked"), function()
{
$("#valueGenre").append($(this).attr('data-value'));
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="btn-group"data-toggle="buttons"id="genreButtons"><labelfor="genre2"class="btn btn-default">Button 1<inputchecked=""data-value="2"name="genre2"id="genre2"type="checkbox"></label><labelfor="genre4"class="btn btn-default">Button 2<inputdata-value="4"name="genre4"id="genre4"type="checkbox"></label><labelfor="genre5"class="btn btn-default">Button 3<inputdata-value="5"name="genre5"id="genre5"type="checkbox"></label><labelfor="genre7"class="btn btn-default">Button 4<inputchecked=""data-value="7"name="genre7"id="genre7"type="checkbox"></label></div><labelname="valueGenre"id="valueGenre" ></label>
Post a Comment for "Get Data-values From Selected Bootstrap Button Group (checkboxes) And Assign To Input"