user677811
user677811

Reputation:

Making on onClick to change text in javascript

I want to make a format like the following:

Phrase
[Button]

When the button is clicked, the 'phrase' changes and the button remains. I am able to make it so text appears, however I can not make it so the button stays. Does anyone have an idea of how this may be done? Thanks.

Upvotes: 4

Views: 47580

Answers (4)

Bal mukund kumar
Bal mukund kumar

Reputation: 363

Use this code:

HTML:

<h1> Welcome to the </h2><span id="future-clicked"></span>

<button onclick="clicked_on()">Click for future</button>

JS:

<script>
    function clicked_on(){
        document.getElementById('future-clicked').innerHTML = 'Future World';
    }
</script>

Upvotes: 1

Jono
Jono

Reputation: 81

Final script

Javascript (replacement)

function displayPhrase()
{
    document.getElementById("demo").innerHTML = 'New Phrase';
}

HTML (Old phrase)

<span id="demo">Old Phrase</span>

HTML (The button)

<button type="button" onclick="displayPhrase()"></button>

Credit to above answers ^_^

Upvotes: 8

alex
alex

Reputation: 490153

I am able to make it so text appears, however I can not make it so the button stays.

My guess is you are updating the element that also contained the button element, and this update is clearing the button.

HTML

<span id="phrase"></span>
<button id="change-phrase" type="button">Change Phrase</button>

JavaScript

var button = document.getElementById('change-phrase'),
    content = document.getElementById('phrase');

button.onclick = function() {
    content.innerHTML = 'Your new phrase';
};

jsFiddle.

Upvotes: 1

Can&#39;t Tell
Can&#39;t Tell

Reputation: 13416

Take a look at this.

Upvotes: 3

Related Questions