【问题标题】:jQuery hide button if textbox is empty and display if textbox have value如果文本框为空,则jQuery隐藏按钮并在文本框有值时显示
【发布时间】:2017-12-02 09:54:47
【问题描述】:

当复选框被选中并且文本框为空时,我想禁用添加到购物车按钮。如果用户单击复选框并在文本框中输入任何内容,则会出现按钮。否则它将被禁用。

我正在添加一个类“disableit”。我的代码几乎可以工作了:当用户在文本框中键入任何内容时出现按钮,但当文本框再次变为空时,类“disableit”不再添加。

我想要的是,如果用户单击复选框,添加到购物车按钮将不起作用,直到用户将信息填写到文本框中并且如果用户取消选中复选框,文本框将隐藏。

jQuery('.single-product .summary button.single_add_to_cart_button').addClass('disableit');
jQuery(".custom_enter-the-domain-name,.custom_hosting-username").on('propertychange change keyup paste input', function() {
  if ((jQuery("input[name='addon[domain]']")).is(':checked') && (jQuery('.custom_enter-the-domain-name').length > 0)) {
    jQuery('.single-product .summary button.single_add_to_cart_button').removeClass('disableit');
  } else if ((jQuery("input[name='addon[domain]']")).is(':checked') && (jQuery('.custom_enter-the-domain-name').val() == '')) {
    jQuery('.single-product .summary button.single_add_to_cart_button').addClass('disableit');
  }
});

【问题讨论】:

  • 欢迎来到 SO。我们想要的是您将相关的 HTML 添加到我制作的 sn-p 中,这样我们就有了 minimal reproducible example
  • 那么用户是否必须选中该框并添加文本,或者您是否会在用户键入时选中该框并在它为空时取消选中它?你想做一些像$("input").on("input",function() { $(this).closest("parentContainerIDOrClass").find(".single_add_to_cart_button").prop("disabled",this.value=="")}
  • 创建一个小提琴并分享链接,对每个人来说都更容易。
  • @Kumar_Vikas - 更容易留在 SO 并创建一个 sn-p
  • @mplungjan 哦,是的!

标签: javascript jquery wordpress wordpress-theming


【解决方案1】:

使用 2 个事件处理程序,input 用于文本字段,change 用于复选框。以下代码将完成您想要的行为。

var addToCart = jQuery('.single-product .summary button.single_add_to_cart_button')
var checkBox = jQuery("input[name='addon[domain]']")
var textField = jQuery('.custom_enter-the-domain-name')

function toggleButton() {
  if(checkBox.is(':checked')) {
    if (textField.val() === '') {
      addToCart.addClass('disableit')
    } else {
      addToCart.removeClass('disableit')
    } 
  } else {
    addToCart.addClass('disableit')      
  }
}

toggleButton()
textField.on('input', toggleButton)
checkBox.on('change', toggleButton)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
  • 2011-02-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多