jQuery - 如何评估if / else语句的两个选择选项值?

时间:2016-01-16 09:05:35

标签: javascript jquery

我有一个继续按钮,上面有" options-btn"在页面上(它是一个多步骤预订过程),页面上有两个选择字段。其中一个下拉选择字段需要具有用户选择的值才能单击页面上的提交按钮,同时还禁用单击事件?

每个下拉字段都有默认的选择选项0,另一个选择为" 1"。如何编写一个函数来基本上说"如果这些选项中没有一个选择值为1 - 警告消息"请选择一个选项"并禁用该按钮。

与这些选择字段关联的两个ID是:

#extra_units_7& #extra_units_4

这是我到目前为止所写的内容,但它不起作用:

jQuery(document).ready(function($) {
$(".options-btn").click(function() {
  if ( $('#extra_units_7').val() === 0  ||  $('#extra_units_4').val() === 0 )
    alert("Please select an option");
    return false;    
  } else {
      $('.options-btn').trigger('click');
  }
});

5 个答案:

答案 0 :(得分:0)

jQuery(document).ready(function($) {
    $(".options-btn").click(function(){
        if ( $('#extra_units_7').val() === 0  &&  $('#extra_units_4').val() === 0 )
            alert("Please select an option");
            return false;    
        }
        return true;
    });
)}

你应该使用&&而不是||。您不需要再次触发点击事件。

答案 1 :(得分:0)

你想检查id,每次更改选择时都会遵守条件,基本上禁用/启用按钮,代码非常好,但你必须在更改事件中执行检查。我已经在外部提取了检查功能只是为了帮助实现可更新性(你错过了{缩进代码太多了)而我已经在select上引入了一个类来更好地执行检查,你可以使用ID,如果你愿意的话。

<select class="input-select" id="extra_units_4">
  <option value="0">Volvo</option>
  <option value="1">Saab</option>
</select>

<select class="input-select" id="extra_units_7">
  <option value="0">Volvo</option>
  <option value="1">Saab</option>
</select>

<button class="options-btn" disabled="disabled">Submit</button>

<script>
jQuery(document).ready(function() {
    $(".input-select").on( "change", checkSelect);
});

function checkSelect() {
    if ( $('#extra_units_7').val() == '0'  &&  $('#extra_units_4').val() == '0' ) {
    $(".options-btn").attr("disabled","disabled");
        alert("Please select an option");
    }

    else {        
        $(".options-btn").removeAttr('disabled');        }
}
</script>

if contition是AND,因为您检查两个值都是0并且必须对string执行检查,因为select值不是整数。

答案 2 :(得分:0)

第一名:代码末尾的});出现错误

第二名:使用==代替===

第3名:无需使用$('.options-btn').trigger('click');

试试这个..如果你有没有表格的提交按钮

jQuery(document).ready(function($) {
  $(".options-btn").on('click',function() {
    if( $('#extra_units_4').val() == 0 ){
      alert("Please select an option in extra_units_4");
      //return false;  
    }else if($('#extra_units_7').val() == 0 ){
      alert("Please select an option in extra_units_7");
        //$('.options-btn').trigger('click');
    }else{
      alert('extra_units_4 value = '+$('#extra_units_4').val());
      alert('extra_units_7 value = '+$('#extra_units_7').val());
    }
  });
});

Working Demo

或者这..如果你有一个表单的提交按钮(你需要使用e.preventDefault();window.location.href

jQuery(document).ready(function($) {
  $(".options-btn").on('click',function(e) {
    e.preventDefault();
    if( $('#extra_units_4').val() == 0 ){
      alert("Please select an option in extra_units_4");
      //return false;  
    }else if($('#extra_units_7').val() == 0 ){
      alert("Please select an option in extra_units_7");
        //$('.options-btn').trigger('click');
    }else{
      alert('extra_units_4 value = '+$('#extra_units_4').val());
      alert('extra_units_7 value = '+$('#extra_units_7').val());

      // window.location.href = "type_url_here" // change type_url_here with url you need or with the form action attribute 
    }
  });
});

Working Demo

答案 3 :(得分:0)

这是一种替代方法,如果您计划继续添加相互排斥但需要的选择(您需要将required-select添加到所有选项中):     });

&#13;
&#13;
jQuery(document).ready(function($) {

  var hasSelected = function() {
    return $('.required-select option:not([value="0"]):selected').length;
  };

  $('.required-select').change(function() {
    $('.options-btn').prop('disabled', !hasSelected());
  });

  $('form').submit(function(e) {
    if (!hasSelected()) {
      alert("Please select an option");
      e.preventDefault();
    } else {
      alert('submitted');
    }
  });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" onsubmit="return false;">
  <select id="extra_units_7" class="required-select">
    <option value="0">Select an option</option>
    <option value="1">One</option>
    <option value="2">Two</option>
  </select>
  <select id="extra_units_4" class="required-select">
    <option value="0">Select an option</option>
    <option value="1">One</option>
    <option value="2">Two</option>
  </select>
  <hr>
  <button type="submit" class="options-btn" disabled="disabled">Submit</button>
</form>
&#13;
&#13;
&#13;

我认为在按钮被禁用时验证提交是否过度,并且允许提交,警报错误以及然后禁用按钮并不直观。我在上面的代码中选择了两种方法中的一种(我更喜欢在书面中指出选择是必需的,并且在选择之前不启用提交。)

答案 4 :(得分:0)

我重新考虑了您的HTML,以便您能够反馈给最终用户而不会突然出现alert()框。

<!-- Use ID to attach to in JS -->
<form id="form_units" action="#" method="post">
    <div>
      <!-- Labels, because... well, labels. -->
      <label for="extra_units_4">extra_units_4</label>
      <!-- Use data-attr to identify which elements should be validated and how. This future proofs your code, and it's a good pattern to follow. -->
      <select id="extra_units_4" data-validate="notempty">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    <!-- Hidden element to provide feedback as it's better UX -->
    <div class="fielderror">Please make a selection</div>
  </div>
  <div>
    <label for="extra_units_7">extra_units_7</label>
      <select id="extra_units_7" data-validate="notempty">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
      <div class="fielderror">Please make a selection</div>
  </div>
  <!-- Included an input[type="text"] for fun, and because future proofing is good -->
  <div>
    <label for="extra_units_8">extra_units_8</label>
    <input type="text" id="extra_units_8" data-validate="notempty" />
    <div class="fielderror">Please make a selection</div>
  </div>
  <!-- There appeared to be no reason not to use an input[type="submit"] in your code. Not doing so adds a tiny amount of complexity - so I slimmed the example down. Re-factor yourself for if <button> is a requirement. -->
  <input type="submit" class="options-btn" value="Submit" />
</form>

现在我们有了一个简单的JS,它将使用<input>捕获所有data-validate="notempty"

// Make sure you're specific with your selector for your form
$('#form_units').on('submit',function(e) {
  // Hide all .fielderror elements within the context of 'this' form.
  // This means that the next time we submit error messages are reset
  $('.fielderror', this).hide();
  // Select for all 'not empty' validations
  $('[data-validate="notempty"]').each(function (index, item) {

    // Check if it's an input[type="text"] - future proofing your "not empty" requirements. Expand on this idea for "radio" and "checkbox" inputs if and when required.
    if ($(item).attr('type') === 'text') {

      // Text is empty if the length is less than one char
      if ($(item).val().length < 1) {
        // We've found one that is invalid so stop the from from sending
        e.preventDefault();
        // Show the .fielderror text that is associated with the input being validated
        $(item).siblings('.fielderror').show();
      }
    } else {
        // Selects are empty if val() is less than 1. Be warned, this is dependant on having numerical values - and assumes that zero means no answer.
        if ($(item).val() < 1) {
          // We've found one that is invalid so stop the from from sending
          e.preventDefault();
          // Show the .fielderror text that is associated with the input being validated
          $(item).siblings('.fielderror').show();
        }
      }
  })
});

最后,添加一些CSS来隐藏错误消息,并在显示时对其进行样式化。

.fielderror { display: none; color: red;}

js更新HTML结构和文本输入的工作示例 - https://jsfiddle.net/likestothink/xLLvzps2/9/