简体   繁体   中英

Javascript - Remove hidden fields or set to empty before form submission


I want to either remove 2 hidden fields or set them to null in a form before a POST action is performed using onclick event on a checkbox.

This is what I have -

<input type="hidden" id="ci" name="ci" value="2"/>
<input type="hidden" id="pg" name="pg" value="prev"/>

<form:checkboxes path="choices" items="${lookups}" itemValue="id" itemLabel="label" element="li" **onclick="this.form.submit();"**/>

How do I modify my onclick event JS to support this ?

Thanks!

Simply change the onclick to this:

onclick="document.getElementById('ci').value = ''; document.getElementById('pg').value = ''; this.form.submit();"

You just have to use the ID of the elements then assign their value to empty string - this will still send value though. To disable any value, disable those elements:

onclick="document.getElementById('ci').disabled = true; document.getElementById('pg').disabled = true; this.form.submit();"

$("input[type='hidden']").each(function(){

  $(this).reset();

});

.......................................................or......................................................

The below code is made up of javascript. This may work

oForm = getElementById('form_id');

var frm_elements = oForm.elements;

for (i = 0; i < frm_elements.length; i++)

{

field_type = frm_elements[i].type.toLowerCase();
switch (field_type)
{
case "text":
case "password":
case "textarea":
case "hidden":
    frm_elements[i].value = "";
    break;
case "radio":
case "checkbox":
case "select-one":
case "select-multi":
default:
}

}

Make onclick call a function which calls submit. Using jQuery is easy to do this

function doform(){
    $.each($('input[type=hidden]'), function(input){
        $(input).val('');
    });
 }

Modify your onclick to call that. You can also do it through normal DOM access using getElementsByTagName and filtering on type or even a straight set of calls to getElementById

function doform(){
  var i1 = document.getElementById('pg');
  i1.value = '';
  var i2 = document.getElementById('ci');
  i2.value = '';
 }

Change your onclick part like below.

onclick="javascript:Clicked();"

Then define your onclick function in clientside javascript under head tags.

<Head>
<script language=javascript>
function Clicked()
{
 //1. Write code to hide fields
 document.forms[0].submit(); 
}
</script>
</Head>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM