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);
}
}
Related
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)
}
It is possible to pass a jQuery variable as a Id in Html. For example
$(document).on('click', '.addvideo', function () {
var dynamicID = $(this).attr('id');
});
Here I am getting the currently clicked id value "dynamicID". I want pass this value to another variable, like below
$('#'+dynamicID).change(function(){
alert('hi');
});
I tried like above. But i am getting error "ReferenceError: dynamicID is not defined". How to resolve this problem ?
Write change event inside addvideo click event, then only it will bind:
$(document).on('click', '.addvideo', function () {
var dynamicID = $(this).attr('id');
$('#'+dynamicID).change(function(){
alert('hi');
});
});
The error is caused by you trying to access the variable dynamicID from somewhere it is not available.
Variables in JS are only accessible within the function that defines them, in other words the part where you write var something = 'value'.
so in your example, the variable dynamicID is available anywhere within this function, but not outside of it.
$(document).on('click', '.addvideo', function () {
var dynamicID = $(this).attr('id');
});
console.log(dynamicID) //ReferenceError: dynamicID is not defined
When you try to access dynamicID outside the function you will get an error, because it basically doesn't exist there.
So you could move the function that is using the dynamicID inside the function that defines it:
$(document).on('click', '.addvideo', function () {
var dynamicID = $(this).attr('id');
$('#'+dynamicID).change(function(){
alert('hi');
});
});
Or to access the variable somewhere else you can define it outside the function, assign it a value in the function, and then access it from somewhere else.
var dynamicID;
$(document).on('click', '.addvideo', function () {
dynamicID = $(this).attr('id');
});
console.log(dynamicID) //this will log the ID value provided the element has been clicked
The reason you are getting that error, is that you are in a different scope, meaning that dynamicID won't be defined. Try adding it into the same scope like this:
$(document).on('click', '.addvideo', function () {
var dynamicID = $(this).attr('id');
$('#'+dynamicID).change(function(){
alert('hi');
});
});
Well I don't know how you intend to fetch the dynamic Id but imagine you're trying to get it from a textbox. Here's how I would do it.
$(document).ready(function() {
var dynamicID = '#' + $('#yada').val();
$(dynamicID).on('input', function(e) {
alert('hi');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="yada" value="yada">
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.
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
<globemedia id="1"></globemedia>
<script type="text/javascript">
$("globemedia").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
$.get("getmedia.jsp?mediaID="+globeIDxMedia,function(a){
$(this).html(a);
});
});
</script>
The above Script i use to load content to my customized tag say <getmedia id="1"></getmedia>
script works fine till getting data from the page getmedia.jsp but when i use $(this).html(a); its not loading the data.
Got Answer from jquery forum
It'll work with custom tag as well
<script type="text/javascript">
$(document).ready(function(){
$("div[data-globalmedia]").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
$(this).load("getmedia.jsp?mediaID="+globeIDxMedia);
});
});
</script>
jQuery expert gave me solution you have to use $(document).ready(function(){}); and it works like a charm
Keep a reference to $(this) outside the $.get() function.
<script type="text/javascript">
$("globemedia").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
var self = $(this);
$.get("getmedia.jsp?mediaID="+globeIDxMedia,function(a){
$(self).html(a);
});
});
</script>
The meaning of this is different within the callback of $.get than it is within the callback of the outer $().each. You can read more about the semantics of this here: http://www.sitepoint.com/javascript-this-gotchas/
As a rule, if you want to refer to the "outer" value of this within a callback function, you first have to bind it to a variable that is accessible within the callback (in this case, I've used the common convention of a variable named self).
You can't this ( which refers to globemedia ) within $.get() callback function scope. Within $.get() callback function this refers to something else but not globemedia.
So, get keep reference of this outside of $.get() which refers to globalmedia like following:
$("globemedia").each(function(index, value) {
var globeIDxMedia = $(this).attr("id");
// keep referece to this
// ie. globemedia
var media = $(this);
$.get("getmedia.jsp?mediaID="+globeIDxMedia,function(a){
// here self refers to
// globemedia element
media.html(a);
});
});
Note
I think $("globemedia") should be $(".globemedia"). That means you should use a class selector.
You can't make your own custom HTML tag. See HERE
As you can't create you own HTML tag (here, globalmedia), instead of that you can use data attribute to them. For example:
<div data-globalmedia="media1" id="id_1">Media 1</div>
<div data-globalmedia="media2" id="id_2">Media 2</div>
and so on. And for jQuery you can use:
$('[data-globalmedia]').each(function() {
var globeIDxMedia = $(this).attr("id");
// keep referece to this
// ie. globemedia
var self = $(this);
$.get("getmedia.jsp?mediaID=" + globeIDxMedia, function(a) {
// here self refers to
// globemedia element
self.html(a);
});
});
Working sample