简体   繁体   English

添加“必填”以选择框

[英]Add “required” to select box

I have a Country select box that display a State select box if the USA is selected. 我有一个国家选择框,如果选择了美国,则会显示一个国家选择框。 I am using the following jQuery to achieve this: 我正在使用以下jQuery实现此目的:

$(function() {
    $('#country').change(function(){
        $('.state').hide();
        $('#' + $(this).val()).show();
    }).trigger('change');
});

Is there a way that I can amend the above to also add the required attribute to the State select box if the USA is selected? 如果选择了美国,是否可以修改上述内容以将所需属性也添加到“州”选择框中?

The State select box is within the following DIV 状态选择框在以下DIV中

<div id="USA" class="state" style="display:none">

</div>

Many thanks, 非常感谢,

John 约翰

Use the prop() method for that: 为此使用prop()方法:

 $("#country").on("change", function() { let $state = $("#state"); if ($(this).val() == "EUA") { $state.prop("required", "required"); } else { $state.prop("required", null); } }).change(); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <select id="country"> <option>EUA</option> <option>Other</option> </select> <select id="state"> <option></option> <option>A</option> <option>B</option> </select> <button>Save</button> </form> 

  • prop("required", "required") to add the property; prop("required", "required")添加属性;
  • prop("required", null) to remove it. prop("required", null)删除它。

You may need to check for the selected value first, then you could use prop()/removeProp() : 您可能需要先检查选定的值,然后才能使用prop()/removeProp()

$(function() {
    $('#country').change(function(){
        var selected_value = $(this).val();
        var state   = $(".state");
        var related_elem = $('#' + selected_value);

        if( selected_value === 'USA' ){
            state.prop('required', true).show();
            related_elem.show();
        }else{
            state.removeProp('required').hide();
            related_elem.hide();
        }
    }).trigger('change');
});

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

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