How to change a text on button click in jquery

Viewed 31

i want to change a text when i click a button, this was what i have tried, but when i click in the buttons it does not work

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button id="one">one</button>
<button id="two">two</button>

<p id="p">paragraph</p>

<script>
    $(document).ready(function() {
        if(('#one').data('clicked')) {
            $("#p").text("hello");
        } 
        else if(('#two').data('clicked')) {
            $("#p").text("byby");
        } 
        else {
            $("#one").text("");
            $("#two").text("");
        } 
      })
</script>
2 Answers

You need to use click event. Try like this:

$(document).ready(function() {


        $('#one').click(function(){
            $("#p").text("hello");
        })
        $('#two').click(function(){
            $("#p").text("byby");
        })

      })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="one">one</button>
<button id="two">two</button>

<p id="p">paragraph</p>

$(document).ready(function() {


        $('#one').click(function(){
            $("#p").text("hello");
        })
        $('#two').click(function(){
            $("#p").text("byby");
        })

      })

You should listen to the click event of each button as follows:

$(document).ready(function() {
     $('#one').on('click', function(){
          $("#p").text("hello");
     });
     $('#two').on('click', function(){
           $("#p").text("byby");
     });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="one">one</button>
<button id="two">two</button>
<p id="p">paragraph</p>

Related