Uncaught ReferenceError is not defined - javascript

what Am I missing here?
I have this javascript in an html view:
sections.forEach(sec => {
const li = jQuery(`<li>${sec.categoryName}<button type="button" onclick="
if (confirm('Remove ${sec.categoryName}?')) removeSectionTapped(sec)"
>Remove</button></li>`);
jQuery('#Sections').append(li);
});
function removeSectionTapped(sec) {
console.log(sec)
}
after I press OK on the confirm I get this error : Uncaught ReferenceError sec is not defined
sec is defined in the confirm message but no inside the if statement..

You have two variables called sec, both of them are declared as the names of function arguments and so are local to those functions.
You are trying to use a variable inside an onclick attribute. This attribute is not inside either of those functions (even though the HTML source code from which the attribute is generated is) so the variable is out of scope by the time it is used.
Don't use onclick attributes, bind your event handlers with JavaScript instead.
sections.forEach(sec => {
const li = jQuery("<li />");
li.append(sec.categoryName);
const button = jQuery('<button type="button" />');
button.text("Remove")
button.on("click", () => {
if (confirm(`Remove ${sec.categoryName}?`)) {
removeSectionTapped(sec);
}
});
li.append(button);
jQuery('#Sections').append(li);
});
function removeSectionTapped(sec) {
console.log(sec)
}

Related

JS: ReferenceError: function is not defined

When my HTML file is loaded, it automatically shows a "login window" (see the function draw_login). When I click on the generated button I get the following error:
ReferenceError: emit_login is not defined
window.onload = function() {
var socket = io();
draw_login ();
function emit_login() {
var login_name = document.getElementById("login_name").value;
var login_password = document.getElementById("login_password").value;
socket.emit('login', {
name:"",
pw:""
});
}
function draw_login() {
document.getElementById("status_bar").innerHTML =
'Name:<input type="text" id="login_name"></input><br>'+
'Password:<input type="password" id="login_password"></input><br>'+
'<button type="button" onclick="emit_login();">login</button>';
}
}
Has anyone an idea or some suggestions?
Thanks in advance!
As Daniel A. White said;
Move it outside of the onload function.
And as Amit said, if you want to learn about why you need to do this, you should read about scopes in JavaScript as this is what causes your error. The function emit_login is created inside of the anonymous function window.onload, which means that anything outside of window.onload will not have access to anything outside of this.
Please correct me if I said anything wrong here. Haven't used JS for quite some time.
It looks like you are receiving this error because you have the emit_login function being called from your click handler which does not share the same scope as the function being called in your onload.
https://jsfiddle.net/sL7e5cut/
function emit_login() {
var login_name = document.getElementById("login_name").value;
var login_password = document.getElementById("login_password").value;
alert('login', {
name:"",
pw:""
});
}
(function() {
draw_login ();
function draw_login() {
document.body.innerHTML =
'Name:<input type="text" id="login_name"></input><br>'+
'Password:<input type="password" id="login_password"></input><br>'+
'<button type="button" onclick="emit_login();">login</button>';
}
}())
try defining the emit_login function outside the onload handler, and everything should work fine.
Keeping things out of the global scope is a good thing, but when you combine it with inline eventlisteners, e.g onclick="emit_login()" it just doesn't work.
Instead of having an inline eventlistener, you can do something like this in draw_login:
function draw_login() {
document.getElementById("status_bar").innerHTML =
'Name:<input type="text" id="login_name"></input><br>'+
'Password:<input type="password" id="login_password"></input><br>'+
'<button type="button">login</button>';
document
.querySelector('#status_bar button')
.addEventListener('click', emit_login, false);
}
Update: The whole point being that using the onclick attribute is discouraged, and definitely not one of the good parts of javascript.

Input's value as variable is not defined

Got an input type text. Whatever entered is supposed to become a value for variable, and further on from there. Yet, i get error "Uncaught ReferenceError: emailvar is not defined" and the whole script breaks from there.
html
<input type="text" class="signfield emfield" />
<div class="submt sbmtfrm" href="#" style="cursor:pointer;">Step 2</div>
and js
$(".sbmtfrm").click(function(){
var emailvar = $(".emfield").val();
});
In your code, emailvar is being defined in a function closure, and only that function has access to it.
$(".sbmtfrm").click(function(){
var emailvar = $(".emfield").val();
});
If you want to use emailvar outside of your jQuery event handler, you will need to first define it (not assign it, yet) outside the scope of the function.
(function(window, $) { // closure
var emailvar;
$(".sbmtfrm").click(function() {
emailvar = $(".emfield").val();
});
// you now have access to `emailvar` in any function in this closure
}(window, jQuery));
You need to declare emailvar as a global variable to use it outside of that click event handler:
$(function()
{
var emailvar;
$(".sbmtfrm").click(function()
{
emailvar = $(".emfield").val();
});
function foo()
{
console.log(emailvar);
}
}

Defined function is not found

I have this function which is called in a for loop.
function printResult(name, i) {
$('#list').append("<a href='#' onClick='goto(" + i + ");' class='item'><H1>" + name + "</H1> </a>");
}
The a href-tags are appended as they should, but when I call the goto function firebug says: 'goto is not defined'
But it is!!
This is the function:
function goto(myPoint){
map.setCenter(new google.maps.LatLng(marker[myPoint-1].position.lat(), marker[myPoint-
1].position.lng()));
markerArr[myPoint-1]['infowindow'].open(map, markerArr[myPoint-1]);
}
I'm clueless as to why the function is not found. Does it have something to do with it being called in the appended a href-tag?
goto() is a terrible name for a function, because it's commonly used as a keyword in a lot of programming languages.
In Javascript, it is not a keyword. However, it is a reserved word, on the grounds that it may be used in future versions of the language. This alone may be causing JS to reject your function or fail to call it.
But even if it weren't a reserved, is could be seen as a potential ambiguity, and so would not be recommended for use.
Therefore, my suggestion would be to change the function name. With luck, it might magically start working.
Using jQuery click events like this:
Html:
function printResult(name, i) {
$('#list').append("<a href='#' rel='" + i + "' class='item'><H1>" + name + "</H1></a>");
}
Js:
$(document).on('click', 'a.item', function (e) {
goto($(this).attr("rel"));
});
But I recommend to rename the function goto to something else or do:
$(document).on('click', 'a.item', function (e) {
var myPoint = $(this).attr("rel");
map.setCenter(new google.maps.LatLng(marker[myPoint-1].position.lat(), marker[myPoint-
1].position.lng()));
markerArr[myPoint-1]['infowindow'].open(map, markerArr[myPoint-1]);
});
When you define event handlers by using onclick attributes, the definition of goto() must be global, i.e. window.goto must exist.
More importantly, this is not the jQuery way; event handlers should be defined in JavaScript code rather than HTML.
function printResult(name, i)
{
var $title = $('<h1 />', { text: name }),
$anchor = $('<a href="#" class="item" />')
.append($title)
.on('click', {
index: i
}, moveToIndex)
.appendTo('#list');
}
// this is the click handler
function moveToIndex(evt)
{
// evt.data.index = the value of i
}
I have renamed your goto() function into moveToIndex() which is somewhat more descriptive. This should not have the same scope issues as your current code.
You are using onClick='goto(" + i + ");'. Use onclick ='goto("+i+")' instead, don't use a semicolon

Calling a function from an html document will not generate an alert

Hi all thanks for taking a look.
I am trying to call a javascript function when I click on the update button.
Here is the javascript
var text2Array = function() {
// takes the value from the text area and loads it to the array variable.
alert("test");
}
and the html
<button id="update" onclick="text2Array()">Update</button>
if you would like to see all the code check out this jsfiddle
http://jsfiddle.net/runningman24/wAPNU/24/
I have tried to make the function global, no luck, I can get the alert to work from the html, but for some reason it won't call the function???
You have an error in the declaration of the pswdBld function in your JavaScript.
...
var pswdBld() = function() {
---^^---
...
This is causing a syntax error and avoiding the load of your JavaScript file.
See the corrected version.
Also, you may consider binding the event and not inlining it.
<button id="update">Update</button>
var on = function(e, types, fn) {
if (e.addEventListener) {
e.addEventListener(types, fn, false);
} else {
e.attachEvent('on' + types, fn);
}
};
on(document.getElementById("update"), "click", text2Array);​
See it live.
In your fiddle, in the drop-down in the top left, change "onLoad" to "no wrap (head)"
Then change
var text2Array = function()
var pswdBld() = function()
to
function text2Array()
function pswdBld()
and it will alert as expected.
You have a syntax error in the line below..
var pswdBld() = function
^--- Remove this
supposed to be
var pswdBld = function
Also make sure you are calling this script just at the end of the body tag..
Because you are using Function Expressions and not Function Declaration
var pwsdBld = function() // Function Expression
function pwsdBld() // Function Declaration
Check Fiddle

Assigning Anchor tag's to call Javascript function dynamically

I am creating list of <span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service">'+servicename+'</a><br/></span> tags dynamically and appending it to a div
Then using the below map to map a tags attribute to some function
var idMap = {
//it can be a lot more
"javaInfo":javaInfo,
/*infa9 product map*/
"infa9PMServer":infa9PMServer,
"infa9Service":infa9Service
};
This is the click Handler
$('#ds-accordion a').click(function(event) {
var elementId=$(this).attr("id");
treeItemClickHandler(elementId);
});
function treeItemClickHandler(id)
{
(idMap[id])(id); //Is this usage called 1st class functions?
}
function infa9Service(id)
{
alert("i got this "+id);
}
Note: I am using Jquery v1.6.3
But when I click on any of the a tags, it calls the function an does all the operation inside the function, but gives an error Object dosen't support this porperty or method in the treeItemClickHandler function.
I would like to know,
How to avoid getting this error?
Is there a more better approach for something like this?
And Is it 1st class functions that I am using (if so where can i learn more about it)?
Thanks.
Update
How can I pass 2nd parameter?
'<span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service" title='+servicename+'>'+servicename+'</a><br/></span>'
$('#ds-accordion a').click(function(event) {
var elementId=$(this).attr("id");
var elementName=$(this).attr("title");
treeItemClickHandler(elementId,elementName);
});
function treeItemClickHandler(id,name)
{
idMap[id](id,name);
}
function infa9Service(id,name)
{
alert(id+", "+name);
}
It gives me infa9Service, undefined
check this out http://jsfiddle.net/ywQMV/4
1)define your functions.
2)define your id map.
html part :
<div id ="ds-accordion">
<span class="infa9span">
<img src="/csm/view/include/images/foldericon.png"/>
<a id="infa9Service" title='+servicename+'>'+servicename+'</a>
<br/>
</span>
js part:
function infa9Service(id, serviceName)
{
alert("i got this "+id +" serviceName : " + serviceName);
}
var idMap = {
"infa9Service":infa9Service
};
$('#ds-accordion a').click(function(event) {
var elementId=$(this).attr("id");
var serviceName = this.title;
treeItemClickHandler(elementId, serviceName);
});
function treeItemClickHandler(id,serviceName)
{
// alert(idMap[id])
(idMap[id])(id,serviceName); //Is this usage called 1st class functions?
}

Categories