我正在尝试制作一个选择按钮,当用户选择或取消选择该值时,单击它选择,再次单击时取消选择该值,并在用户选择div时更改文本框的值,它将显示此div是选中并更改文本框值,当用户再次单击时,div将变为非活动状态,文本框的值将再次更改,当选择所有div时,它将添加所有插件值,如果它选择1个文本框值将为2时选择第二个文本框的值将变为4,依此类推,当前值正在改变,而且div正在激活但是当我们点击所有同一个类的div时,激活和停用我无法找到错误我希望你知道我在说什么
$(document).ready(function() {
$('.js-mc-checkbox', this).on('click', function() {
$('.js-mc-checkbox').toggleClass('active');
var old_val = $('.price_addon').val();
var new_val = old_val + $(this).attr('data-addon');
$('.price_addon').val(new_val);
});
});
.active {
background:#333 !important;
color:#fff;
}
.js-mc-checkbox {
background:#f7f7f7;
width:150px;
height:40px;
float:left;
margin-right:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div data-addon="202" class=" js-mc-checkbox add-on-item">
<div class="meta">
<span class="price add-on-price-202">$35</span>
<span class="included">Included</span>
</div>
</div>
<div data-addon="203" class=" js-mc-checkbox add-on-item">
<div class="meta">
<span class="price add-on-price-202">$35</span>
<span class="included">Included</span>
</div>
</div>
<div data-addon="204" class=" js-mc-checkbox add-on-item">
<div class="meta">
<span class="price add-on-price-202">$35</span>
<span class="included">Included</span>
</div>
</div>
<input type="text" name="price_addon" class="price_addon" value="" />
答案 0 :(得分:3)
您的代码存在的问题是您忘记将data-addon
的值和输入值解析为数字而忘记在按钮停用时将其减去。
这将有效:
$(document).ready(function() {
var $boxes = $('.js-mc-checkbox');
var $input = $('.price_addon');
var activeClass = 'active';
var dataAttr = 'data-addon';
$boxes.on('click', function() {
var value = parseInt($input.val() || 0);
$(this).toggleClass(activeClass);
if($(this).hasClass(activeClass)) {
value += parseInt($(this).attr(dataAttr));
} else {
value -= parseInt($(this).attr(dataAttr));
};
$input.val(value);
});
});
.active {
background:#333 !important;
color:#fff;
}
.js-mc-checkbox {
background:#f7f7f7;
width:150px;
height:40px;
float:left;
margin-right:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div data-addon="202" class=" js-mc-checkbox add-on-item">
<div class="meta">
<span class="price add-on-price-202">$35</span>
<span class="included">Included</span>
</div>
</div>
<div data-addon="203" class=" js-mc-checkbox add-on-item">
<div class="meta">
<span class="price add-on-price-202">$35</span>
<span class="included">Included</span>
</div>
</div>
<div data-addon="204" class=" js-mc-checkbox add-on-item">
<div class="meta">
<span class="price add-on-price-202">$35</span>
<span class="included">Included</span>
</div>
</div>
<input type="text" name="price_addon" class="price_addon" value="" />