开发者

Javascript prop('required', true) works but prop('required', false) doesn't?

Why does the $('#select_embed') propert开发者_开发问答y get set to true, but not to false? Instead, I tried removeAttribute('required'), but that didn't work either.

<script>

    function showBundles(){
        if (document.getElementById("embed").checked){
            $('#div_embed_bundles').show('fast')
            $('#select_embed').prop('required',true);
        }
        else {
            $('#div_embed_bundles').hide('fast')
            $('#select_embed').prop('required',false);
        }
    }

</script>


Ideally if prop('required',true) is working then prop('required',false) should also work. But you can try with removeAttr, hope this helps.

function showBundles(){
        if (document.getElementById("embed").checked){
            $('#div_embed_bundles').show('fast')
            $('#select_embed').prop('required',true);
        }
        else {
            $('#div_embed_bundles').hide('fast')
            $('#select_embed').removeAttr('required');
        }
    }


Use attr() instead of prop(). I used attr('required', true) and attr('required',false) and both worked perfectly. Read the documentation at https://api.jquery.com/attr/ to know when to use attr() and when to use prop()

Or read the essential parts of the documentation on .attr() below:

.attr(): Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

Attributes vs. Properties The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜