簡體   English   中英

選擇多選選項限制最多2

[英]select multiselect option limit up to 2

我正在使用multiselect用於不同的主題我想要將select最多限制為2,並且如果用戶取消選擇,則以相同的方式禁用其他選項。再次,該選項必須對用戶可用。

<select multiple="multiple" class="subjects" name="subjects[]" style="float:left;width:205px;" size="5">
  <option value='1'>subject1</option>
  <option value='2'>subject2</option>
  <option value='3'>subject3</option>
  <option value='3'>subject3</option>
</select>

到目前為止,我已經實現了取消選擇僅在2之后選擇的最后一個選項,代碼如下

    /**
     * Make sure the subject's limit is 2
     */
    $(".subjects option").click(function(e){

        if ($(this).parent().val().length > 2) {
            $(this).removeAttr("selected");
        }
    });

謝謝。

改進了jQuery示例,注意(else enable)選項,這修復了以前禁用select選項的示例的bug。 同時刪除了“請僅選擇兩個選項”。 可能時出現錯誤消息。 http://jsfiddle.net/c9CkG/25/

jQuery(document).ready(function () {

jQuery("select").on("change", function(){
  var msg = $("#msg");

  var count = 0;

  for (var i = 0; i < this.options.length; i++)
  {
    var option = this.options[i];

    option.selected ? count++ : null;

    if (count > 2)
    {
        option.selected = false;
        option.disabled = true;
        msg.html("Please select only two options.");
    }else{
        option.disabled = false;
        msg.html("");
    }
  }
});

});

作為RobG答案的改進,如果計數> 2,您可以取消選擇一個選項。

有關使用jQuery的工作示例,請參閱: http//jsfiddle.net/c9CkG/3/

function checkSelected(el) {
  var msgEl = document.getElementById('msg');
  var count = 0;

  for (var i=0, iLen=el.options.length; i<iLen; i++)

      el.options[i].selected? count++ : null;

      // Deselect the option.
      if (count > 2) {
          el.options[i].selected = false;
          el.options[i].disabled = true;

          msgEl.innerHTML = 'Please select only two options';
      }
}

像下面這樣的東西將完成這項工作:

function checkSelected(el) {
  var msgEl = document.getElementById('msg');
  var count = 0;

  for (var i=0, iLen=el.options.length; i<iLen; i++)
      el.options[i].selected? count++ : null;

  msgEl.innerHTML = count > 2? 'Please select only two options' : '';
}
</script>

<span>Please select a maximum of two options:</span>
<select multiple onchange="checkSelected(this);">
  <option>0
  <option>1
  <option>2
  <option>3
</select>
<br>
<span id="msg"></span>

我認為禁用選項不是一個好主意,您只關心在提交表單時只選擇了兩個選項。 在那之前,沒關系。

$(document).ready(function() {

  var last_valid_selection = null;

  $('#testbox').change(function(event) {
    if ($(this).val().length > 5) {
      alert('You can only choose 5!');
      $(this).val(last_valid_selection);
    } else {
      last_valid_selection = $(this).val();
    }
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM