我需要有关使用 jQuery 从复选框获取值的帮助。
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
var $this = $( this ),
value = $this.val();
value_array.push( value );
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
- 如果选中类别 1,则获得值(正确)。
- 如果选中类别 2,则获得值(正确)。
- 如果未选中类别 1,则再次获取值(错误,我不希望 它)。
- 如果类别 2 未选中,则再次获取值(错误,我不希望 它)。
我想要这样:
如果未选中类别 1,则从输出数组中删除该值。
如果未选中类别 2,则从输出数组中删除该值。
最佳答案
检查复选框是否被选中,如果是则将值添加到数组中,如果不是则删除。
$(document).ready(function() {
var value_array = [];
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
if ($this.prop('checked')) value_array.push(value);
else value_array.splice(value_array.indexOf(value), 1);
console.log($.unique(value_array));
$('#out').html($.unique(value_array).join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
关于javascript - 从 jQuery 复选框动态获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46831737/