Mia Legaspi Mia Legaspi - 7 months ago 16
Javascript Question

Clicking the button concurrently using replaceWith without refreshing the browser

I'm trying to figure it out how can I click my button concurrently without refresh my browser. I noticed that if I clicked one of the buttons it's working and replacing it's new value using

.replaceWith
but when I click another button it doesn't give me a another value.

Code:

<body>
<input type = "button" id = "bt1" value = "See my Full Name :)">
<input type = "button" id = "bt2" value = "See my Nickname :)">

<div>
<div class = "name">See my name</div>
</div>

<script>

$(document).ready(function ()
{
$("#bt1").click
(
function ()
{
$("div.name").replaceWith("<div>John Francis</div>");
alert("Your full name is John Francis");
}
);

$("#bt2").click
(
function ()
{
$("div.name").replaceWith("<div>Francis</div>");
alert("Your nickname is Francis");
}
);
});

</script>



Answer

You're not adding the classname .name to the newly inserted DIV that you replace, so the next time you click, there is no element with the class .name.

It would be a lot easier to just update the text

$(document).ready(function() {
    $("#bt1").click(function() {
        $(".name").text("John Francis");
        alert("Your full name is John Francis");
    });

    $("#bt2").click(function() {
        $(".name").text("Francis");
        alert("Your nickname is Francis");
    });
});

FIDDLE

If for some reason you have to use replaceWith (which you don't), just add the class

$(document).ready(function() {
    $("#bt1").click(function() {
        $(".name").replaceWith("<div class='name'>John Francis</div>");
        alert("Your full name is John Francis");
    });

    $("#bt2").click(function() {
        $(".name").replaceWith("<div class='name'>Francis</div>");
        alert("Your nickname is Francis");
    });
});

FIDDLE