Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 339
emjay Avatar asked May 29 '13 08:05

emjay


People also ask

Are hidden form fields submitted?

A hidden field let web developers include data that cannot be seen or modified by users when a form is submitted. A hidden field often stores what database record that needs to be updated when the form is submitted.

How do you hide input fields?

The HTML <input type=”hidden”> is used to define a input Hidden field. A hidden field also includes those data that could not be seen or modified by the users when submitted the form.


1 Answers

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");
}
like image 129
CodingIntrigue Avatar answered Oct 20 '22 13:10

CodingIntrigue