Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of input and submit form in JavaScript

I'm currently working on a basic form. When you hit the submit button, it should first change the value of a field, and then submit the form as usual. It all looks a bit like this:

<form name="myform" id="myform" action="action.php">     <input type="hidden" name="myinput" value="0" />     <input type="text" name="message" value="" />     <input type="submit" name="submit" onclick="DoSubmit()" /> </form> 

And this is how far I've come with the JavaScript code. It changes "myinput"'s value to 1, but it does not submit the form.

function DoSubmit(){   document.myform.myinput.value = '1';   document.getElementById("myform").submit(); } 
like image 268
Paparappa Avatar asked Aug 02 '11 12:08

Paparappa


People also ask

How do I change input type submit value?

you want to change value after submit? The default behaviour of a form is to submit data, you need to tell it not to submit if you don't want it to. If you use event. preventDefault(); in the function triggered on submit this will remove the default behaviour of posting.

Can change value in input JavaScript?

We can set the value of an input field with JavaScript by selecting the element. Then we can set the value attribute by setting the value property or calling setAttribute .

How do you change a value in JavaScript?

In order to change an element, you use its argument name for the value you wish to change. For example, let's say we have a button, and we wish to change its value. <input type="button" id="myButton" value="I'm a button!">

How do you change the input type on a submit text?

Input value attribute The value attribute can be used to change the text of the form submit button. Use value attribute within <input> of type="submit" to rename the button.


1 Answers

You could do something like this instead:

<form name="myform" action="action.php" onsubmit="DoSubmit();">     <input type="hidden" name="myinput" value="0" />     <input type="text" name="message" value="" />     <input type="submit" name="submit" /> </form> 

And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:

function DoSubmit(){   document.myform.myinput.value = '1';   return true; } 

I'd also be wary of using onclick events on a submit button; the order of events isn't immediately obvious, and your callback won't get called if the user submits by, for example, hitting return in a textbox.

like image 80
valderman Avatar answered Oct 09 '22 08:10

valderman