简体   繁体   English

如何强迫用户选择 <select>引导程序选项

[英]How to force a user to choose a <select> option with bootstrap

I've been trying to work the answer out to this for hours and it's driving me insane! 数小时以来,我一直在努力寻找答案,这让我发疯了!

I'm using Twitter Bootstrap and bootstrap-min.js. 我正在使用Twitter Bootstrap和bootstrap-min.js。

Here is my code: 这是我的代码:

<select id="assettype" name="assettype" class="input-medium required">
   <option>-- Please select --</option>
   <option value="1">Printer</option>
   <option value="2">Scanner</option>
</select>

If a user leaves the form as the '-- Please select --' option then I want an error to prevent the user from submitting the form ie forcing them to make a selection. 如果用户将表单保留为“-请选择-”选项,那么我希望出现一个错误,以防止用户提交表单,即强迫他们进行选择。

Any help would be massively appreciated! 任何帮助将不胜感激! Thanks in advance. 提前致谢。

Use event.preventDefault() 使用event.preventDefault()

$('#formId').submit(function (e) {
    if ($('#assettype').val() == '') {
    e.preventDefault(); //stop form submission
}
});


or 要么

Using jQuery Validator 使用jQuery验证器

 $.validator.addMethod('notNone', function (value, element) { return (value != ''); }, 'Please select an option'); $("form").validate({ rules: { assettype: { required: true, notNone: true } } }); 

This seems you need a simple validation before submitting like 看来您需要先进行简单的验证,然后才能提交

$('#formId').submit(function () {
 if ($('#assettype').val() != '')) {  //Check the value of select
    return true; //allow to submit the form
 }
 else {       
    alert("Please select an option");
    return false;  //Prevent form being submitted
 }
}); 
<form id="my_form" method="POST" action="" >
<select id="assettype" name="assettype" class="input-medium required">
  <option value="0" >-- Please select --</option>
  <option value="1">Printer</option>
  <option value="2">Scanner</option>
</select>
</form>
<script type="text/javascript">
  $("#my_form").submit(
    var check_value = $("#assettype").val();
    if (check_value == 0)
    {
      e.preventDefault();
      // prevent the user he has to choose something
      // by an alert for example, or background change of the element
      $("#assettype").css("background-color", "red");
      return false;
    }
    else
    {
      // and restore it if it's ok
      $("#assettype").css("background-color", "inherit");
    }
    return true;
  });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM