当两个数据属性都不为空时,我试图将按钮从禁用更改为启用。
我没有收到任何错误,但是每次填充数据属性时,它不会更改其Disabled / Enabled属性。
我已经尝试过这种方法,但是什么也没有发生,我的浏览器控制台无法打印任何内容。
<select class="form-control os" name="os">
<option disabled selected>Please choose...</option>
<option>Ubuntu Server 18.04</option>
<option>Ubuntu Server 16.04</option>
<option>Ubuntu Server 14.04</option>
</select>
<select class="form-control location" name="location">
<option value="" disabled selected>Please choose...</option>
<option value="Sydney">Sydney</option>
<option value="Tokyo">Tokyo</option>
<option value="Sao Paulo">São Paulo</option>
</select>
<button class="btn btn-primary btn-lg float-right btn-buynow" data-shoppy-product="ewAfime" data-shoppy-os="" data-shoppy-location="" disabled>Buy now</button>
$(document).ready(function(){
$("select.location").change(function(){
var selectedLocation = $(this).children("option:selected").val();
$('.btn-buynow').attr('data-shoppy-location', selectedLocation);
});
$('select.os').change(function() {
var selectedOS = $(this).children("option:selected").val();
$('.btn-buynow').attr('data-shoppy-os', selectedOS);
});
var $buynow = $('.btn-buynow');
if (typeof $buynow.data('shoppy-os') !== 'undefined' && typeof $buynow.data('shoppy-location') !== 'undefined') {
if($buynow.attr('disabled')) $buynow.removeAttr('disabled');
else $buynow.attr('disabled', 'disabled');
}
});
答案 0 :(得分:2)
尝试关注
data
访问.data()
属性时,请从参数中删除data-
disable
按钮,请使用.attr('disabled', 'disabled');
var $buynow = $('.btn-buynow');
if ($buynow.data('shoppy-os') && $buynow.data('shoppy-location')) {
if($buynow.attr('disabled')) $buynow.removeAttr('disabled');
else $buynow.attr('disabled', 'disabled');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn-buynow" data-shoppy-os="a" data-shoppy-location="b" disabled>Button</button>
答案 1 :(得分:0)
对于我的验证方法,我建议进行一些更改。它们如下:
HTML更改:为HTML选项添加值
<select class="form-control os" name="os">
<option value="Please choose..." selected>Please choose...</option>
<option value="Ubuntu Server 18.04">Ubuntu Server 18.04</option>
<option value="Ubuntu Server 16.04">Ubuntu Server 16.04</option>
<option value="Ubuntu Server 14.04">Ubuntu Server 14.04</option>
</select>
<select class="form-control location" name="location">
<option value="Please choose..." selected>Please choose...</option> <option value="Sydney">Sydney</option>
<option value="Tokyo">Tokyo</option>
<option value="Sao Paulo">São Paulo</option>
</select>
<button class="btn btn-primary btn-lg float-right btn-buynow" data-shoppy-product="ewAfime" data-shoppy-os="" data-shoppy-location="" disabled>Buy now</button>
JS验证如下:
$(".os,.location").change(function() {
if ($(".os").val() != "Please choose..." && $(".location").val() != "Please choose...") {
$('.btn-buynow').prop("disabled", false);
}
});
让我知道这是否对您有用。