0

How to use a javascript variable when setting the innerHTML of an element? To see my problem first click CLICK 1. This will show delete and then click delete. Why does the alert not show 111-aaaa,1? How can I do that?

https://jsfiddle.net/brf75wvp/

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

<input id="test_id" value="1"/>
<div onclick="test_fn1()">CLICK 1</div>
<div id="demo"></div>

<script>
    function test_fn1() {
        var test_id_val = document.getElementById("test_id").value;
        document.getElementById("demo").innerHTML = "<span onclick= delete_fn('111-aaaa, test_id_val')>delete</span>";
    };
</script>

<script>
    function delete_fn(no_delete) {
        alert(no_delete);
    };
</script>
2
  • what do you mean Why not alert 111-aaaa,1 Commented Jan 27, 2016 at 11:44
  • Please tag your questions appropriately. This had nothing to do with jquery, css, html nor ajax Commented Jan 27, 2016 at 11:45

4 Answers 4

2

You should add the variable with string like following.

function test_fn1() {
    var test_id_val = document.getElementById("test_id").value;
    document.getElementById("demo").innerHTML = "<span onclick=delete_fn('111-aaaa,"+test_id_val+"')>delete</span>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to concatenate the variable to string:

document.getElementById("demo").innerHTML = "<span onclick=delete_fn('111-aaaa," + test_id_val + "')>delete</span>";

Updated fiddle

Comments

1

There is syntax error. Correct one is:

document.getElementById("demo").innerHTML = "<span onclick=delete_fn('111-aaaa," + test_id_val + "')>delete</span>";

Comments

0

Your code having some error try using bellow this will work

<script>
function test_fn1() {
var test_id_val = document.getElementById("test_id").value;
document.getElementById("demo").innerHTML = '<span onclick=delete_fn("111-aaaa,'+test_id_val+'")>delete</span>';
};
</script>

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.