2
var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello" + testStr)');

This is probably a dumb question, but I'm trying to add a variable to .setAttribute onclick event, but I'm not quite sure what the correct syntax is to add the variable into the quote? The above alert doesn't show.

1
  • DO NOT USE SET ATTRIBUTE TO ADD A CLICK HANDLER! BAD BAD BAD. You should be using addEventListener Commented Sep 28, 2013 at 12:33

4 Answers 4

4
var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello '+testStr+'")');

However this is a poor way of binding click events to elements. Instead, look into the element.addEventListener method - that is the preferred way of binding. There's various reasons for this - one is that you are not limited to just one event of each type (as you are with your current approach). Another is that it keeps code out of your mark-up.

Sign up to request clarification or add additional context in comments.

Comments

1

This is the right way of binding events (no need to use setAttribute):

var testStr='World';
tUserBlock.onclick = function() { alert("Hello" + testStr) };

If you still insist on your original way, this is the way of doing it:

var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello ' + testStr + '")');

Comments

0

try this.

var testStr='World';
tUserBlock.setAttribute('onclick', 'javascript:alert("Hello '+testStr+'")');

I hope this will help you.

Comments

0

This works for me, and I haven't changed anything:

<button class="tUserBlock">click me</button>

<script>
  var tUserBlock = document.querySelector('.tUserBlock');
  var testStr='World';
  tUserBlock.setAttribute('onclick', 'javascript:alert("Hello" + testStr)');  
</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.