droidus
droidus

Reputation: 641

javascript change value of button

How do I change the value of this button? I am looking at a tutorial, but only the url seems to change, and not the button.

<form name="form" id="form">
<button name="button" id="button">Click Me!</button>
</form>

<script type="text/javascript">
document.form.button.value=new Date();
</script>

Upvotes: 5

Views: 107150

Answers (4)

user1687619
user1687619

Reputation:

This works for sure...

onclick="changeValue(this);"

function changeValue(button)
{
    // Changes the value of the button
    button.value = new Date();
}

Upvotes: 5

Jonathan Payne
Jonathan Payne

Reputation: 2223

I added an onclick to your button to change the value with the function.

If you add onsubmit="return false" to the form tag, it won't refresh the page.

<form name="form" id="form" onsubmit="return false">
    <button name="button" id="button" onclick="changeValue();" value="before" >Click Me!</button>
</form>

<script type="text/javascript">
    function changeValue()
    {
        // Changes the value of the button
        document.form.button.value = new Date();

        // Changes the text on the button
        document.form.button.innerHTML = new Date();
    }
</script>

Upvotes: 10

Travesty3
Travesty3

Reputation: 14469

document.form.button.innerHTML = new Date();


EDIT:

If what you're trying to is to make the text on the button change to the current date when you click it, this is what you want to do:

<script type="text/Javascript">
    function changeLabel()
    {
        document.getElementById('button').innerHTML = new Date();
    }
</script>

<button id="button" onclick="changeLabel()">Click Me!</button>

Upvotes: 9

Engineer
Engineer

Reputation: 48793

Use innerHTML:

document.form1.button1.innerHTML=new Date();

UPDATE: Alternative you could define your button like:

<input name="button" id="button" type="button" value="Click Me!" />

In that case

document.form.button.value=new Date();

should work as you had expected .

Upvotes: 0

Related Questions