Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a button's value using javascript

Tags:

I'm sure I'm going to feel stupid after seeing the answer, but I keep running into prehistoric code around the web, which I'm not sure still applies. My question is "How do I change the value of a button (inside a form) using javascript?" Here's what I have right now:

function myFunc(form) {
    form.elements["submit-button"].value = "New<br>Text";
    "other stuff that actually works."
    return false;
}

followed by

<form onSubmit="return myFunc(this);">
    <button name="submit-button">Original<br>Text</button>
</form>

The "other stuff that actually works." actually works, so I'm sure the function is getting called and the button is getting found. I just can't seem to stick "New
Text" into the button!

Help much appreciated.

like image 706
Felipe Avatar asked Dec 17 '11 01:12

Felipe


People also ask

How do I change the value of a button in HTML?

To change the button text, first we need to access the button element inside the JavaScript by using the document. getElementById() method and add a click event handler to the button, then set it's value property to blue . Now, when we click on our button , it changes the value from Red to Blue or vice versa.

Can we assign value to button?

The value attribute specifies the initial value for a <button> in an HTML form. Note: In a form, the button and its value is only submitted if the button itself was used to submit the form.

Can I get value from Button JavaScript?

Use the value property to get the value of a button in JavaScript.


1 Answers

Use innerHTML instead of value.

form.elements["submit-button"].innerHTML = ...

Because you are using a <button> instead of <input type="button">, you need to set the innerHTML. <button>s do not base their text on the value attribute.

<button> innerHTML </button>
<input type="button" value="value" />
like image 72
Will Avatar answered Sep 24 '22 00:09

Will