Uncaught ReferenceError: addStu is not defined at HTMLButtonElement.onclick (index.php:196) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Uncaught ReferenceError: addStu is not defined at HTMLButtonElement.onclick (index.php:196)

I got this error what should i do <button type="button" class="btn btn-primary" onclick="addStu()">Sign up</button> function addStu(){ var stuname = $("#stuname").val(); var stuemail = $("#stuemail").val(); var stupass = $("stupass").val(); console.log(stuname); console.log(stuemail); console.log(stupass); }

17th Apr 2021, 10:00 AM
Gayatri Dunakhe
Gayatri Dunakhe - avatar
1 Answer
+ 2
Share more complete code. Your JavaScript should either be in a script element or an external .js document referenced by a script element's src attribute. You probably knew that but just being sure. Most likely, you're loading your addStu function definition after the HTML for your button is rendered and that's your problem. Try this instead: function addStu(){ var stuname = $("#stuname").val(); var stuemail = $("#stuemail").val(); var stupass = $("stupass").val(); console.log(stuname); console.log(stuemail); console.log(stupass); } // Set id="add-student-button" attribute in your button's HTML and then run this: document.getElementById('add-student-button').addEventListener('click', addStu); // Also, remove your onclick="addStu" from HTML. Remember to do like the comments there say. That change separates your HTML from JavaScript a little more. It is part of an approach called "unobtrusive javascript". Unobtrusive JavaScript also recommends making all features work with JavaScript disabled but that's not a concern here. Learn more about unobtrusive JavaScript here: https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
18th Apr 2021, 4:57 PM
Josh Greig
Josh Greig - avatar