我想禁用按钮或更改字段的属性,以便如果输入字段中少于12个字符,它将禁用按钮我试过了我所知道的一切。(可能重复- Can't change html attribute with external script)
Html代码
<button name="button" type="submit" id="continue_button" class="step__footer__continue-btn btn" aria-busy="false">
<span class="btn__content" data-continue-button-content="true">Continue to shipping</span>
<svg class="icon-svg icon-svg--size-18 btn__spinner icon-svg--spinner-button" aria-hidden="true" focusable="false"> <use xlink:href="#spinner-button"></use> </svg>
</button>
JS代码-
$("#checkout_shipping_address_address1").attr('maxlength','15');
var valueLength = $('#checkout_shipping_address_address1').val();
if(valueLength.length < 12){
// console.log(valueLength.length);
// $("#checkout_shipping_address_address1").aria-invalid="true";
// var attrChange = $("#error-for-address1");
// $("#checkout_shipping_address_address1").innerHTML("aria-describedby" = attrChange);
// $("#checkout_shipping_address_address1").innerHTML("aria-descibedby = attrChange");
// $("#checkout_shipping_address_address1").setAttribute("aria-invalid", "true");
// $('#continue_btn').attr("disabled", true);
// $('#continue_btn').disabled = true;
// $('#continue_btn').prop('disabled', true);
}
else
{
// $('#continue_btn').disabled=false;
}
网页上的属性没有改变,我也不能禁用按钮。
注意-我不能改变HTML/CSS代码,因为我没有访问它
p。S -我是JS/JQuery新手。
你必须在文本输入上放置一个事件监听器,我向你提出一个香草JS解决方案:
- 默认禁用按钮
- 检查输入 的值长度
- 根据结果更改禁用值
const input = document.querySelector("#continue_input");
const button = document.querySelector("#continue_button");
input.addEventListener("input", (event) => {
if(event.target.value.length > 11) {
button.removeAttribute("disabled");
} else {
button.setAttribute("disabled", "true");
}
});
.step__footer__continue-input {
margin-bottom: 1rem;
}
<input id="continue_input" class="step__footer__continue-input" type="text" placeholder="Enter 12 characters here">
<button id="continue_button" class="step__footer__continue-btn btn" type="submit" name="button" aria-busy="false" disabled="true">
<span class="btn__content" data-continue-button-content="true">Continue to shipping</span>
<svg class="icon-svg icon-svg--size-18 btn__spinner icon-svg--spinner-button" aria-hidden="true" focusable="false"><use xlink:href="#spinner-button"></use></svg>
</button>
输入需要一个事件处理函数(与on()
一起添加),以便在用户更改输入值时发生一些事情:
$("#checkout_shipping_address_address1").attr('maxlength', '15').on('input', function() {
$('#continue_button').prop('disabled', $(this).val().length < 12);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="checkout_shipping_address_address1" />
<button name="button" disabled type="submit" id="continue_button" class="step__footer__continue-btn btn" aria-busy="false">
<span class="btn__content" data-continue-button-content="true">Continue to shipping</span>
<svg class="icon-svg icon-svg--size-18 btn__spinner icon-svg--spinner-button" aria-hidden="true" focusable="false"> <use xlink:href="#spinner-button"></use> </svg>
</button>