1

I have this code and I want to show il in the elements which will be created by jquery , but il is undefined : this is code :

<script>
$(document).ready(function(){
    var il = 1 ;
    $("#btn1").click(function(){
        $("p").append(" <b>Appended text</b>.");
    });
    $("#btn2").click(function(){
        $("ol").append("<li>Appended item " + il + " </li>");
var il = il + 1;
    });
});
</script>


<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>

this is output :

List item 1
List item 2
List item 3
Appended item undefined
Appended item undefined
1
  • Live: jsfiddle.net/pf0y6z4q Commented Mar 2, 2015 at 19:33

2 Answers 2

1

Simply use il++.

 $(document).ready(function(){
    var il = 1 ;
    $("#btn1").click(function(){
        $("p").append(" <b>Appended text</b>.");
    });
    $("#btn2").click(function(){
        $("ol").append("<li>Appended item " + il + " </li>");
        il++;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Just remove var from var il = il + 1;.

Use var only for new variable declaration.

$(document).ready(function(){
    var il = 1 ;
    $("#btn1").click(function(){
        $("p").append(" <b>Appended text</b>.");
    });
    $("#btn2").click(function(){
        $("ol").append("<li>Appended item " + il + " </li>");
        il = il + 1;
    });
});

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.