Ad
Get Value Multiple Button Created By Checked Checkbox
I want to get value from button. This button appear when checkbox checked.
if only one button, it's ok, but when there is so many button it will fetch last button data-attr which is not good
$('#other-products').on('change', function() {
var selectedProducts = [];
var listProductsCtrl = $('.list-products');
listProductsCtrl.html('');
$('#other-products input[type="checkbox"]:checked').each(function() {
selectedProducts.push($(this).attr('name'));
var showtimesAsString = '<button class="number" data-label="'+$(this).attr('name')+'">'+selectedProducts.join('</button> <button class="test">')+'</button>';
listProductsCtrl.html(showtimesAsString);
});
$('.number').click(function(){
alert($(this).attr('data-label'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="other-products">
<input type="checkbox" name="First" value="1">
<input type="checkbox" name="Second" value="2">
<input type="checkbox" name="Third" value="3">
</div>
<span class="list-products"></span>
Ad
Answer
for 2nd and 3rd you are appending class test
not number, and that does not having data-label
attribute
SO here i just display text()
here.
$('#other-products').on('change', function() {
var selectedProducts = [];
var listProductsCtrl = $('.list-products');
listProductsCtrl.html('');
$('#other-products input[type="checkbox"]:checked').each(function() {
selectedProducts.push($(this).attr('name'));
var showtimesAsString = '<button class="number" data-label="'+$(this).attr('name')+'">'+selectedProducts.join('</button> <button class="test">')+'</button>';
listProductsCtrl.html(showtimesAsString);
});
$('.number, .test').click(function(){
alert($(this).text());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="other-products">
<input type="checkbox" name="First" value="1">
<input type="checkbox" name="Second" value="2">
<input type="checkbox" name="Third" value="3">
</div>
<span class="list-products"></span>
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad