为了创建油漆制造商网站,产品页面需要为用户提供输入 RAL 颜色代码或使用颜色选择器选择颜色的选项。
为此,我使用了:
<p class="line-item-property__field">
<label for="ral-colour-code">RAL Colour Code</label>
<input required class="required" id="ral-colour-code" type="text" name="properties[RAL Colour Code]">
</p>
<p class="line-item-property__field">
<label for="choose-a-colour">OR Choose a colour</label>
<input id="choose-a-colour" type="color" name="properties[Choose a colour]">
</p>
这实现了主要目标,因为用户对颜色的选择包含在公司收到的确认订单中。然而,我担心的是,在某些情况下,用户可能会使用选择器选择一种颜色,然后输入准确的颜色代码——这两者都将包含在确认中。我想最好的做法是在将文本输入到另一个输入时禁用一个输入,但是用户需要清楚这两个选项中的哪一个将应用于他们的订单。
我尝试了什么: 在做了一些挖掘之后,我发现了一个类似的问题得到了回答 here .所以我尝试这样做:
jQuery(function ($) {
var $inputs = $('properties[RAL Colour Code],properties[Choose a colour]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', !$(this).val().length);
});
});
这返回了以下错误:
Error: Syntax error, unrecognized expression: properties[RAL Colour Code],properties[Choose a colour]
除了错误之外,我认为这可能不是我正在寻找的解决方案,因为它只是删除了 required
标记,但大概用户仍然可以选择填写两者.
最佳答案
试试这个:
<input type="text" id="choose" />
<input type="text" id="write" />
和 jQuery:
$("#choose, #write").keyup(function(){
if($("#choose").val() != "") {
$("#write").hide();
}else if($("#write").val() != "") {
$("#choose").hide();
}else{
$("#write").show();
$("#choose").show();
}
});
这里正在工作fiddle为你
新fiddle满足您的需求。添加了清除颜色按钮,使用了您的 ID,input type="color"
的事件已更改为 .change()
关于javascript - 用户可以选择两个输入,但只需要一个。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48204185/