jquery property disabled and input value form submit

canpoint picture canpoint · Jul 22, 2013 · Viewed 13.4k times · Source

What I wanna ask is, I have a check box called full screen and when I checked it the two input fields which are width and height should be disabled and the values of it set to null. I do it well with j query but when I submit the form with full screen checked even the two input fields values are 0, it is saving with previous values of that two input fields.

Any help?

$("#fullscreenCheckBox").on("change", function() {
        if($(this).prop("checked")) {
            $("#height").prop("disabled", true);
            $("#height").val("");
            $("#width").prop("disabled", true); 
            $("#width").val("");

        } else {
            $("#height").prop("disabled", false);
            $("#height").prop("disabled", false);
        }
    });

The values are set to null as its but when the form is submitted it doesnt keep it

Answer

Kamil T picture Kamil T · Jul 22, 2013

If an input has the disabled='true' property at the moment of form submit, it's value isn't submited with the form. You can either try to re-enable it at the moment of form submit in jQuery, like:

$("#yourFormId").submit(function(){
    $("#YourInputId").prop('disabled', 'false');
});

Another approach is to use many extra hidden fields for each "visible" input, like <input id='hiddenInputId' type='hidden' > and to set thier values in jQuery. They will not be seen by the user, but their values will still be sent with form submit. Example:

$("#yourInputId").change(function(){
    $("#hiddenInputId").val($(this).val()));
});

After that, when you process the submit, you just ignore regular input values and only work with hiddens.

Personally, I think that the second option (with hidden inputs) is much better. You can even extend it, and instead of hard-typing your DOM element id in change(), you can add a data-attribute to each element and then kill all birds with one stone :)