简体   繁体   English

如果在选择中选择了特定选项,则如何进行输入

[英]How to make input required if specific options are selected in a select

I'm struggling with making a input field required only if specific options are selected in a <select> list. 仅当在<select>列表中选择了特定选项时,我才努力使输入字段为必填项。

For example: 例如:

<select id="model">
    <option value="model1">Model 1</option>
    <option value="model2">Model 2</option>
    <option value="model3">Model 3</option>
    <option value="model4">Model 4</option>
</select>

<input type="text" name="extra">

The input extra gets required if Model 2 or 3 is selected. 如果选择了模型2或3,则需要extra输入。

How do I do this? 我该怎么做呢?

Well you can only do so much with javascript client-side. 好吧,您只能在javascript客户端上做很多事情。 Ultimately you will have to enforce this on the server. 最终,您将不得不在服务器上强制执行此操作。 To do this client-side without relying on browser specific implementations or HTML5, you will need to manually check the values you want to be requires with an onsubmit() event handler. 要在不依赖浏览器特定实现或HTML5的情况下进行此客户端操作,您将需要使用onsubmit()事件处理程序手动检查所需的值。

<form onsubmit="return validateFormData(this)">

Also be sure to give your select element a name for ease of use: 另外,请确保为您的select元素起一个易于使用的名称:

<select id="model" name="model"></select>

Then in your javascript: 然后在您的JavaScript中:

function validateFormData(oForm) {
    //Let's say that a value of 'model3' makes 'extra' required
    if(oForm.model.value=='model3') {
        if(oForm.extra.value=='') {
            //returning false will prevent the form from submitting
            return false;
        }
    }
}

Here is a fully working example to demonstrate how to use jQuery to solve both cases. 这是一个完全有效的示例,以演示如何使用jQuery解决这两种情况。 Note that you must include the reference to the jQuery library as I have done in the head tags. 请注意,您必须像在head标签中一样包含对jQuery库的引用。 You also might move the javascript/jQuery into a separate file and simply include it by reference. 您还可以将javascript / jQuery移到一个单独的文件中,并仅通过引用将其包括在内。

Live example (jsFiddle) here 此处为实时示例(jsFiddle)


<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
//alert('Document is ready');
                $('#model').change(function() {
                    var sel = $(this).val();
                    if (sel == 'model2' || sel == 'model3') $('input[name=extra]').show();
                });

                $('input[name=btn_submit]').click(function() {
                    var sel = $('#model').val();
                    if (sel == 'model2' || sel == 'model3') {
                        if ($('input[name=extra]').val() == '') {
                            alert('Please complete all fields');
                            return false; //prevent submit from submitting
                        }else{
                            alert('Your entry was submitted');
                        }
                    }else{
                        //Model is NOT 2 or 3 so don't check
                        alert('Your entry was submitted without checking input field value.');
                    }
                });
            });
        </script>
    </head>
<body>

    <select id="model">
        <option value="model1">Model 1</option>
        <option value="model2">Model 2</option>
        <option value="model3">Model 3</option>
        <option value="model4">Model 4</option>
    </select>

    <input type="text" name="extra" style="display:none">
    <input type="submit" name="btn_submit" value="Submit It">

</body>
</html>

You can add a required class when a certain option is selected. 选择某个选项时,可以添加所需的类。 Then on submit check the required elements to make sure something it's not empty 然后在提交时检查所需的元素,以确保它不为空

$('#model').change(function () {
    // check if it's model2 or model3
    var isRequired = /model2|model3/i.test(this.value);
    $('input[name=extra]').toggleClass('required',isRequired);    
});

$('form').submit(function(){
    // get all empty required fields
    var reqEmpty = $('.required').filter(function(){
       return $.trim(this.value).length === 0;
    });
    // if any empty required fields are found - do something
    if(reqEmpty.length){
        alert('empty required field');
        return false;
    }
});

the red border in the fiddle is just to show you when the required class has been added. 小提琴中的红色边框仅是在添加所需的课程时向您显示。

FIDDLE 小提琴

Assuming you're trying to set the required property : 假设您要设置required 属性

$('#model').change(function(){
    var index = this.selectedIndex;
    $('input[name="extra"]').prop('required', function(){
        return index == 1 || index == 2;
    });
});

JS Fiddle demo . JS小提琴演示

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

相关问题 如何使特定选项出现在 select 菜单中? - How to make specific options to appear in select menu? 如果选中复选框,则需要输入 - If checkbox selected make input required 如何在使用JavaScript或jQuery选择父选项时进行选择必需的选择 - How to make select required upon parent option selected with JavaScript or jQuery 如何进行输入 - How to make input required 进行多个不包含任何先前输入的选定选项的选择输入 - Make multiple select inputs that don't contain any previous input's selected options 级联选择:选择特定选项时显示不同的选项 - Cascade Select: Show different options when specific options is selected HTML JAVASCRIPT或PHP如何使select中的选项依赖于另一个select中选择的选项 - HTML JAVASCRIPT or PHP how to make options in select dependent on option selected in another select 如何检查表格的每一行,选择 select 的值,而不是获取所有可用的选项和文本输入值 - How to check for each row of a table, the value of the selected select instead of getting all the available options and text input values 如何选择必填字段 - How to make a select required fields 当“选项”不是静态时,如何引用“选择”列表的选定值? - How do I make a reference to the selected value of a “select” list when the “options” are not static?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM