user1159435
user1159435

Reputation: 125

Manipulating form values before submitting without displaying it to the user?

Sorry for the vague title, but I don't know how to describe the problem more precisely in a short sentence.

My problem is the following:

When I manipulate form values within an onsubmit callback function like in the following example, the browser sometimes show the changed input/textarea values to the user while submitting the form and before being forwarded to a result page.

<html>
<head>
  <script type="text/javascript">
    function manipulateForm() {
      document.forms["myForm"]["myField"].value = "new value";
      return true;
    }
  </script>
</head>
<body>
  <form name="myForm" action="submit.htm" onsubmit="manipulateForm()">
    <input type="text" name="myField">
    <input type="submit" value="Submit">
  </form>
</body>
</html>

Is there any way to circumvent this? What I want is to send manipulated form values but without users actually seeing that form data has been changed.

Upvotes: 2

Views: 5889

Answers (2)

jeffpkamp
jeffpkamp

Reputation: 2866

There is no reason to make a second form, the onsubmit function can alter the data before it is submitted.

in the example below, the data will be altered before it is sent on.

<html>
<form id=myform target=apage.html onsubmit=alter()>
<input type=text id=name name=name>
<input type=age id=age name=age>
<input type=submit>
</html>

<script>
function alter(){
    age.value=Number(age.value)+10;
    name.value="My your Is "+name.value;
}
</script>

Upvotes: 2

Psych Half
Psych Half

Reputation: 1411

how about creating two forms one fake and the other real... the user enters data in the fake form.. which when submitted calls the function manipulateForm... the default submit action of the fake form is prevented.. and the data from the fake from is extracted.. manipulated.. and set in the real form.. then the real's form submit is triggered...
something like that.. here's an example..

 <div>

   <form onsubmit="return manipulateForm()">
    <input type="text" id="myFieldFake">
    <input type="submit" value="Submit">
  </form>

     <form id="myForm"  action="javascript:alert('Replace with your form action')" style="display:none" >
    <input hidden="true" type="text" id="myFieldReal">
    <input  hidden="true" type="submit" value="Submit">
  </form>

  </div>   

and for the manipulate function...

 function manipulateForm() {

  var myFieldValue = document.getElementById("myFieldFake").value;

 // do something with myFieldValue... 

 document.getElementById("myFieldReal").value = myFieldValue ;

document.getElementById("myForm").submit() ;

      return false ;
    }

jsFiddle

Upvotes: 4

Related Questions