Exclude hidden form fields from submit

后端 未结 2 2229
太阳男子
太阳男子 2021-02-19 05:50

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



        
相关标签:
2条回答
  • 2021-02-19 06:26

    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");
    }
    
    0 讨论(0)
  • 2021-02-19 06:27

    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".

    0 讨论(0)
提交回复
热议问题