用户可以选择两个输入,但只需要一个输入。

问题描述 投票:1回答:1

要创建涂料制造商网站,产品页面必须为用户提供输入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标签,但可能用户stil可以选择填写两者。

javascript jquery html forms shopify
1个回答
3
投票

试试这个:

<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()

© www.soinside.com 2019 - 2024. All rights reserved.