jQuery value passing as a id in html - javascript

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">

Related

Google Tag Manager - storing id of a clicked div/button

Looked for the answer all over, tried reading seperatly but couldn't find an answer..
I have a site, on which Google Tag Manager is implemented, and I need to extract the id of a clicked button (or its parent).
this is my code:
function(){
$(document).ready(function(){
var editid;
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
return editid;
});
}
Thanks!
The simplest approach is to create the following custom javascript variable:
function(){
return $({{Click Element}}).attr('data-id');
}
This will return the data-id attribute for all events (including clicks).
Attach this variable to the relevant event tag, and use click class contains uk-button as the trigger.
You can remove the outer function and code like below.
$(document).ready(function () {
$('div.uk-button').click(function () {
var editid;
editid = $(this).attr('data-id');
alert(editid);
});
});
Hey it looks like you may be not be catching the returned value of the document ready callback.
For example, this returns undefined since the return of $(document).ready() callback is not being returned by the containing function:
function testfunc() {
$(document).ready(function(){
var editid = 'this is the return value';
return editid;
});
}
testFunc()
"returns undefined"
I'm guessing that you might be trying to set up a custom javascript variable in GTM. You can still use document ready to ensure the elements are present but the returned value needs to be returned by the outer function for it to be passed into the variable.
So your example should work as follows:
function(){
var editid;
$(document).ready(function(){
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
});
return editid;
}

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);
}
}

how to get last clicked event data in entire javascript scope

function my_fun(){
var data = $(this).data();
// this is undefined
console.log(data.crm);
}
$(document).on('click', '#add_image', (function() {
var data = $(this).data();
// this works
console.log(data.crm);
my_fun();
}));
<a class="add_img" href="#" data-crm="1" id="add_image">Add Image</a>
Basically I want to access html link set data (i.e. value of dataset crm) in my_fun() without sending parameter to my_fun().
How to access click events html set data in the entire scope of javascript.
javascript.
Global variable in javascript
function my_fun() {
console.log(data.crm);
}
$(document).on('click', '#add_image', (function(e) {
e.preventDefault();
data = $(this).data();
console.log(data.crm);
my_fun();
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="add_img" href="#" data-crm="1" id="add_image">Add Image</a>
function my_fun(event){
var data = $(event.target).data();
console.log(data.crm);
}
$(document).on('click', '#add_image', my_fun);
or
function my_fun(event){
var data = $(event.target).data();
console.log(data.crm);
}
$(document).on('click', '#add_image', function(e){
my_fun(e);
});
You have to pass a context to your function by call method:
my_fun.call(this);
jsFiddle
There's a limited number of ways to do this. One is to pass arguments to the called function.
Another is to just reference the function, and you'll keep the this value
function my_fun(){
var data = $(this).data();
// this is undefined
console.log(data.crm);
}
$(document).on('click', '#add_image', my_fun);
Lastly, there's bind, apply or call
my_fun.bind(this)();
// or
my_fun.call(this);
// or
my_fun.apply(this, arguments);

$(this).html not working in jquery

<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

using jquery when passing arguments to function

I have a link which triggers js function. To the link I have attached data-attribute on html which I want to pass to the function.
$(".trigger").awesomeFunction({
oneArgument: "secretSauce",
secondArgument: $(this).data("address")
});
Now that second argument ends up null instead of the data-address attribute. Is it because $(this) is not in right scope inside the function arguments list and if so how could I refer to the originating link?
Not sure how your awesomeFunction is defined, but this seems to do the trick.
$.fn.awesomeFunction = function(obj){
console.log(obj.sauceType, this.data(obj.dataArg))
// returns 'secretSauce 123 Anystreet Dr.'
}
var div = $('#theDiv')
div.awesomeFunction({
sauceType : 'secretSauce',
dataArg : 'address'
})
JSFiddle
$(".trigger").each(function() {
var self = $(this);
self.awesomeFunction({
oneArgument: "secretSauce",
secondArgument: self.data("address")
});
});
Given your code sample, anything could happen, this is not defined in the scope of .trigger, you're "one layer out" so to speak.
See this fiddle for example
$(".trigger").click(function() {
var self = $(this);
self.awesomeFunction({
oneArgument: "secretSauce",
secondArgument: self.data("address")
});
});

Categories