Search code examples
javascriptjquerythymeleaf

Removing 'required' attribute with user action Thymeleaf


Currently creating a Spring application with Thymeleaf as the front-end component.

When a user selects a checkbox within a form, I want to immediately remove the required attribute from any subsequent tags in that form. This way, the user can submit the form immediately, rather than being forced to enter data for the required input fields.

Checkbox

This^ checkbox is checked. It should allow the user to save immediately, instead of this:

enter image description here

I believe that JQuery is needed for what I am trying to do. I found this possible solution:

Removing html5 required attribute with jQuery

but I have no experience with JQuery, and this solution only indicates how to remove a required field, rather than when an action happens. Is there a simpler way to handle this task?

My form markup for reference:

<!-- When the user clicks "save", this data routed here -->
        <form action="#" th:action="@{/ots/resolve/save}"
            th:object="${griefRecord}" method="POST">

            <div class="checkbox">
                <label data-toggle="popover" data-content="Checking this box will Exclude this record">
                <input type="checkbox" name="exclude"/>Exclude this Record?</label>
            </div>

            <div class="input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="inputGroup-sizing-default"
                    data-toggle="popover" data-content="Adjust the Platform">Platform</span>
                </div>
                <input type="text" th:field="*{platform}"
                    class="form-control" placeholder="platform" required>
            </div>

            <button type="submit" id="index-popover"
                class="btn btn-warning btn-sm" data-toggle="popover"
                data-content="Save the listed record to the Cross Reference Table">Save</button>

        </form>

Solution

  • Set an id, eg. reqfield on the inputs with required attribute, then you can use the following code:

    $(function(){
    
        $("input[name=exclude]").change(function(){
         if(this.checked){
            $("input#reqfield").removeAttr("required")
         } else {
            $("input#reqfield").attr("required", true)
         }
        })
    
    })