0

I am new to stackoverflow, and I am also an amateur javascript programmer. I am trying to make a program in which, when I click one button, a prompt appears, asking for my name. Alongside that, I also want that button to disappear, and be replaced with another button with the value: Hello 'name'. How do I do this? My code that I currently have in javascript asks me for my name, but does not make the button disappear. My current js is as follows:

var button = document.getElementById("button");
function naming() {
    var getName = prompt("What is your name?");
    button.style.display = "none";
};

And my html for the button:

<button id="button" onclick="naming();"> Name Here</button>
Lukasz Koziara
  • 4,078
  • 4
  • 29
  • 40
VampireTooth
  • 25
  • 2
  • 7

2 Answers2

0

This would work, it does not remove the button but use it ones again for the name that the user inputs.

HTML

<button id="button">Name here</button>

JS

var button = document.getElementById('button');
button.addEventListener('click', function() {
    var name = prompt("What is your name?");
    this.innerHTML = name
}, false);

http://jsfiddle.net/rYU7Q/

Karl
  • 813
  • 6
  • 13
  • It works in the jsfiddle, but can't work in my html file, I am pretty sure that the syntax is right. What do you suggest? – VampireTooth Jul 20 '14 at 14:30
  • I will mark this answer as correct, because the code works perfectly in jsfiddle, but the problem lies somewhere in my actual computer. When I put the same js and html code in jsfiddle, it worked. – VampireTooth Jul 20 '14 at 14:43
  • I'm guessing it because the javascript runs before the DOM has loaded. Check this answer for the solution, so that the code is executed after the DOM has loaded :) http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the – Karl Jul 20 '14 at 14:47
  • I will try executing the code after loading the DOM, but in the js that you gave me, in the .addEventListener thing, there is a function named function(). I already have one with that name. So, if i change its name to like, naming(), will it work? – VampireTooth Jul 20 '14 at 14:58
0

another method

<button class="btn btn-primary" id = "del-btn">Old btn</button>
<div id = "sho-btn"></div>


 <script>
    var a = "<button class='btn btn-primary'>New Button</button>";
    document.getElementById("del-btn").style.visibility = 'hidden';
    document.getElementById("sho-btn").innerHTML = a;
    </script>
Hamza Qureshi
  • 330
  • 11