1

I added onclick event to below query, but it doesn't work. I used ruby on rails . Help me out to get a solution. Thank you...

for (var j = 0; j < 3; j++){
   $('#sub').append("<div class='col-md-12' '><img src='picture.jpg' class='subPic' style='cursor:pointer;' onclick='sayhello()'></div>");
}
function sayhello(){
  alert("hello");
}
13
  • 2
    function name() and onclick = name() Commented Oct 10, 2017 at 6:39
  • your updated code is working.. what is the error you are encountering? Commented Oct 10, 2017 at 6:42
  • where you able to append the img? if not then maybe result["prd_image"].length; is the problem.. Commented Oct 10, 2017 at 6:46
  • I changed it. but error is still the same . I coded this on ruby on rails . is it the problem? Commented Oct 10, 2017 at 7:01
  • what is the error? Commented Oct 10, 2017 at 7:04

2 Answers 2

1

Your function needs a name. I chose the name "callAlert" here.

for (var j = 0; j < result["prd_image"].length; j++){
   $('#sub').append("<div class='col-md-12' '><img src='picture.jpg' class='subPic' style='cursor:pointer;' onclick='callAlert()'></div>");
}
function callAlert(){
  alert("hello");
}
Sign up to request clarification or add additional context in comments.

3 Comments

Do you have any output on browser console?
Yeah " Uncaught ReferenceError: sayhello is not defined at HTMLImageElement.onclick (VM23994 89:1)"
error is i defined that sayhello function inside of wrong function thanks for your cooperation
1

You need to assign a name to the function, like function sayhello() and then call it like onclick='sayhello()'

for (var j = 0; j < 2; j++) {
  $('#sub').append("<div class='col-md-12' '><img src='picture.jpg' class='subPic' style='cursor:pointer;' onclick='sayhello()' alt='awda'></div>");
}

function sayhello() {
  alert("hello");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sub"></div>

3 Comments

these changes are worked in here. but i in my code errors are still the same. I'm working my project on ruby on rails .
VM23994 89:1 Uncaught ReferenceError: sayhello is not defined at HTMLImageElement.onclick (VM23994 89:1) error is appeared in browser console
error is i defined that sayhello function inside of wrong function thanks for your cooperation

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.