emjay
emjay

Reputation: 1511

Exclude hidden form fields from submit

I'm hiding/showing a div based on the state of a checkbox.

<input type="checkbox" id="other" name="os[other]" value="6" onclick="toggle_form_element('os[other]')">

Here is my Javascript Function:

function toggle_form_element(id) {
    if ((document.getElementsByName(id)[0].checked)) {
        document.getElementById('sometimesHidden').style.display = 'block';
    } else {
        document.getElementById('sometimesHidden').style.display = 'none';
    }
}

This is the "sometimesHidden" div:

<div id="sometimesHidden">
    <input type="text" size="20" id="other_os" name="other_os">
</div>

Now I would like to use my toggle_form_element function also for excluding all the input fields in the "hidden" div from the $_POST['array'].

But how can I do this?

Upvotes: 17

Views: 16473

Answers (2)

Alnitak
Alnitak

Reputation: 339816

You can directly set the .disabled property on the element:

function toggle_form_element(name) {
    var state = document.getElementsByName(name)[0].checked;
    document.getElementById('sometimesHidden').disabled = state;
}

It's almost always better to modify the properties of an element rather than the attributes, and the semantics are clearer for boolean properties, too.

Note that while MDN suggests that this property is ignored on hidden fields:

disabled

This Boolean attribute indicates that the form control is not available for interaction. In particular, the click event will not be dispatched on disabled controls. Also, a disabled control's value isn't submitted with the form.

This attribute is ignored if the value of the type attribute is hidden.

testing in Chrome 27 shows that Chrome does honour the disabled attribute and prevent submission of form values for hidden fields.

Furthermore, the W3C spec makes no such distinction. It simply says that "Controls that are disabled cannot be successful".

Upvotes: 5

CodingIntrigue
CodingIntrigue

Reputation: 78525

You can add a disabled attribute to any fields you don't want to submit.

function toggle_form_element(id) {
    if ((document.getElementsByName(id)[0].checked)) {
        document.getElementById('sometimesHidden').setAttribute("disabled", "disabled");
    } else {
        document.getElementById('sometimesHidden').removeAttribute("disabled");
    }
}

For a jQuery solution:

// Disables all input, select & textarea tags within the .sometimesHidden div
if(checked) {
  $("input, select, textarea", $(".sometimesHidden")).attr("disabled", "disabled");
}
else {
  $("input, select, textarea", $(".sometimesHidden")).removeAttr("disabled");
}

Upvotes: 22

Related Questions