Search code examples
jqueryattr

How can i change the value of data-rules-required using jQuery


I am using a validiation script on my website like this:

<input type="text" id="Abomonatspreis" name="Abomonatspreis" form="formular" data-rules-required="true">

In some case i have to change the data-rules-required value to "false" using jQuery.

I tried it this way, but it did not work:

$("#Abomonatspreis").attr({data-rules-required: "false"})

Does somebody has any idea?

Thank you Ingo


Solution

  • You don't need jQuery for this. This is a trivial task for the DOM API:

    document.getElementById('Abomonatspreis').dataset.rulesRequired = "false";
    
    console.log(document.getElementById('Abomonatspreis').outerHTML);
    <input type="text" id="Abomonatspreis" name="Abomonatspreis" form="formular" data-rules-required="true">

    Instead of working with the dataset object, you could as well work with the HTML attribute. Both are synced automatically, meaning if you change either, you also change the other implicitly.

    document.getElementById('Abomonatspreis').setAttribute('data-rules-required', 'false');
    

    The reason your attempt failed is that you need to quote the attribute name, otherwise the - between the parts is considered the minus operator.

    If you insist on using a third party library for trivial tasks, here's the jQuery version:

    $("#Abomonatspreis").attr({"data-rules-required": "false"})
    
    console.log($("#Abomonatspreis")[0].outerHTML);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="Abomonatspreis" name="Abomonatspreis" form="formular" data-rules-required="true">