skip to Main Content

I took this code sample from w3schools https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_html_callback

I want to increase the index number of I how do I do this without showing zero on both the .text and .html code blocks

    <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("#test1").text(function(i, origText){
      return "Old text: " + origText + " New text: Hello world! (index: " + i + ")"; 
    });
  });

  $("#btn2").click(function(){
    $("#test2").html(function(i, origText){
      return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")"; 
    });
  });
});
</script>
</head>
<body>

<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>

<button id="btn1">Show Old/New Text</button>
<button id="btn2">Show Old/New HTML</button>

</body>
</html>

2

Answers


  1. return "Old text: " + origText + " New text: Hello world! (index: " + (i + 1) + ")"; 
    
    return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + (i + 1) + ")"; 
    

    use (i + 1) in the string.

    Login or Signup to reply.
  2. I am not sure if I understood it correctly, but if you are looking to display the number of clicks in HTML without showing the initial text, then this is the working code for it.

    $(document).ready(function(){
    
      var para1 = 0, para2 = 0;
      $("#btn1").click(function(){
      
        para1++;
        $("#test1").text("New text for para1 : "+para1);
      });
    
      $("#btn2").click(function(){
      
        para2++;
        $("#test2").text("New text for para2 : "+para2);
      });
    });
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    <body>
    
    <p id="test1">This is a <b>bold</b> paragraph.</p>
    <p id="test2">This is another <b>bold</b> paragraph.</p>
    
    <button id="btn1">increase i in para 1</button>
    <button id="btn2">increase i in para 2</button>
    
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search