Felipe
Felipe

Reputation: 3149

Setting a button's value using JavaScript

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

Upvotes: 21

Views: 68500

Answers (4)

vol7ron
vol7ron

Reputation: 42179

Your code works, but isn't doing what you probably expect. Your followed by shows the text of the button and it's initial value, however your code will change the value before the form is submitted. That means, the receiving page (most often a php/perl/asp script) will see the changed value passed as a GET or POST parameter.

If you want to change the text w/o submitting the form you might want to try this:

function changeValue(id, newText) {
    var el       = document.getElementById(id);
    el.value     = newText;  // change the value passed to the next page
    el.innerHTML = newText;  // change the displayed text on the screen
    return false;
}
<form onsubmit="return false;">
    <button  id="submit-button" 
           name="submit-button" 
        onclick="changeValue(this.id,'Some New Text');" >Original<br>Text</button>
</form>

see JS Fiddle here

Upvotes: 2

Will
Will

Reputation: 20235

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

Upvotes: 33

thescientist
thescientist

Reputation: 2948

there's a much better way to do that. use document.getElementById and give the button an ID.

function myFunc() {
    document.getElementById('my_button').innerHTML = "New<br>Text";
    //"other stuff that actually works."
    return false;
}

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

I'm not sure you can put a tag into the value of a button, but who knows. Can't say I've tried it.

Upvotes: 0

Blender
Blender

Reputation: 298562

This might work:

form.elements["submit-button"][0].innerHTML = "New<br>Text";

form.elements["submit-button"] probably returns all of the elements with that name attribute, which is an array.

Upvotes: 0

Related Questions