strange variable scope in jQuery - javascript

I know scope in javascript in sometimes tough but this time I suspect the issue may be jQuery execution order. In the following code I try to define a simple HTML element (simulates a button) in javascript and pass different text to it when mounting it in HTML using jQuery:
var name;
var buttonsecondary = '<div class="buttonsecondary clicked"><p>'+name+'</p></div>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content-item" id="things4">
<a href="aFabrica.html">
<div class="itemHome">
<div class="bg" id="buttonsecondaryfabrica"></div>
<script>
$(document).ready(function() {
var name = "A Fábrica";
$("#buttonsecondaryfabrica").after(buttonsecondary)
})
</script>
</div>
</a>
</div>
<div class="content-item">
<a href="lojas.html">
<div class="itemHome">
<div class="bg" id="buttonsecondaryloja"></div>
<script>
$(document).ready(function() {
var name = "Loja";
$("#buttonsecondaryloja").after(buttonsecondary)
})
</script>
</div>
</a>
</div>
The problem is that I get the same text on both buttons: "Store" although in the first alert getting "Street" and in the second "Store"...
Does anyone know how to explain it?

The problem is that the buttonsecondary variable already contains the final HTML of the button because it's merely a concatenated string.
You need to generate the desired HTML each time:
function generateButton(name)
{
return '<div class="buttonsecondary clicked"><p>' + name + '</p></div>';
}
Then:
var name = "A Fábrica";
$("#buttonsecondaryfabrica").after(generateButton(name));
And
var name = "Loja";
$("#buttonsecondaryloja").after(generateButton(name));

In your original code, you are creating a string with variables that are changed later on. When you change the variables, the string does not get updated because the variables are not bound. You need to create a new string if you want to pass in a new value for the name.
Change this:
var buttonsecondary = '<div class="buttonsecondary clicked"><p>'+name+'</p></div>';
To this:
function createSecondaryButton(name) {
return '<div class="buttonsecondary clicked"><p>' + name + '</p></div>';
}
Or, since you are using jQuery:
function createSecondaryButton(name) {
return $('<div>').addClass('buttonsecondary clicked')
.append($('<p>').text(name));
}
Then simply call the function:
$("#buttonsecondaryfabrica").after(createSecondaryButton('A Fábrica'));
$("#buttonsecondaryloja").after(createSecondaryButton('Loja'));

Related

Retrieve name value from button in javascript

I have the following HTML:
<div class="dropdown" data-offers-filter-segments="">
<button class="toggle--dropdown" name="toggle-segment-cagetories-list">
<span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
</button>
<div class="dropdown__content" hidden="hidden">
Which renders a dropdown, when clicked a new class is appended which is called is-dropped so the parent div will look like this once its been clicked on class="dropdown is-dropped"
Now using Javascript I'm trying to retrieve name="toggle-segment-cagetories-list" which we will use within DTM (Adobe Tag Manager) as an eVar value but I'm uncertain how I go about retrieving that name value, so far I have the following javascript:
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
if(hasClass(document.getElementsByClassName('dropdown')[0], 'is-dropped')){
// Now get the name value ?
}
else {
alert("false");
}
Now I'm pretty new to javascript so if someone can shed some light in how I go about getting the name value and passing it to DTM I would highly appreciate it.
use document.querySelector:
<div class="dropdown is-dropped" data-offers-filter-segments="">
<button class="toggle--dropdown" name="toggle-segment-cagetories-list">
<span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
</button>
<div class="dropdown__content" hidden="hidden">
<script>
var button=document.querySelector('div.is-dropped button.toggle--dropdown');
var name=button&&button.name||'';
alert(name);
</script>
if you want to use your own data-attributes, you need start your attribute name with 'data':
<button class="toggle--dropdown" data-name="toggle-segment-cagetories-list">
In order to retrieve the value of the attribute, you can do as shown in the example below:
var article = document.getElementsByClassName('toggle--dropdown');
article[0].dataset.name // article[0] because getting elements by className returns an array

get textarea by class and set name dynamically

I don't really know why I can't do this apparently silly thing.
I have a template that parses dynamically a js file with an html textarea only with the class attribute.
What I want to do is to add name attribute to it so I can get it with $_POST in php.
So far I have tried:
var txt = $('.note-codable');
txt.prop('name','description');
$('.note-codable').attr('name','description');
and other options that doesn't seem to work.
This is html that is added dinamycally:
<div class="note-editor">
//other divs
<textarea class="note-codable"></textarea>
</div>
when I do (in order to TRY the code):
var txt = $('.note-codable');
alert(txt);
the result is [object] [object]
what am I missing? why is attr name not writing?
Try this, tell me if there is anything else I can do.
window.onload = function(){
//get the element
var txt = $('.note-codable');
//set the name attribute
txt.name = 'yourName';
//get the name and console.log it
console.log(txt.name);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="note-editor">
//other divs
<textarea class="note-codable"></textarea>
</div>
You seem to be doing it right... Here's an example for clarity.
$(function() {
var $el = $("#example");
var $out = $("#output");
$out.append("<p>Name is: " + $el.attr('name') + "</p>");
$el.attr('name', 'description');
$out.append("<p>Name is: " + $el.attr('name') + "</p>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="example"></textarea>
<div id="output"></div>
Your code is working on my end: the name is set dynamically. You are getting [object object] from the alert because you are returning the textbox itself, not its contents or the value of its name attribute.
Assuming you want the name put into the textbox instead of added as an attribute, you should set it with txt.val('your name here').
var txt = $('.note-codable');
txt.attr('name', 'description');
console.log(txt.get(0));
txt.val(
'html: ' + txt.parent().html().trim() + '\n' +
'name: ' + txt.attr('name')
);
textarea {
height: 100px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="note-editor">
<textarea class="note-codable"></textarea>
</div>
If you alert an object(like what the jQuery selector will return) it will not give display the information. It will always read [object Object]. Using console.log would be a better way to read through it. Alternatively, if just want to test if the name attribute is in fact applied, this should the trick.
var txt = $('.note-codable').attr('name');
alert(txt);
Assuming the jQuery was successful, it should read description

Pass Jquery variable to HTML so it can be picked up in multiple functions

I'm struggling to get this working but I may be going completely off track with this. I'm creating a jquery mobile webapp and I'm trying to use a variable that is declared when a popup is created, in a different on click function. The way that I thought to do this is:
click here to run function LoadCancelReservationPopup and pass some id's to the JQ
<a onclick= LoadCancelReservationPopup('" . $row ['sizecodeid'] ."','" . $row ['unitid'] ."') class='ui-btn ui-mini'>Cancel</a>
Run this function
function LoadCancelReservationPopup(sizecode,unit) {
var sizecode = (sizecode);
var unit = (unit);
$("#cancelReservationSizecode").html(sizecode);
$("#cancelReservationUnit").html(unit);
$("#reservationCancelPopup").popup("open");
$("#reservationCancelPopup").trigger('create');
};
That function opens this popup and the ids that were passed are now being displayed in the divs
<div data-role='popup' id='reservationCancelPopup' data-theme='a' style='min-width: 300px;'>
<div data-role='main' class='ui-content'>
<div data-role='header' data-theme='a'>
<h1>Cancel Reservation</h1>
</div>
<p>Are you sure you want to cancel this reservation?</p>
<div id='cancelReservationUnit' name='cancelReservationUnit' class="unit"></div>
<div id='cancelReservationSizecode' name='cancelReservationSizecode' class="sizecode"></div>
<a href='#' class='ui-btn ui-btn-c' data-transition='pop' id='loadCancelCustomerReservation' name='loadCancelCustomerReservation'>Yes Cancel Reservation</a>
<a href='#' class='ui-btn ui-btn-c' data-rel='back' data-transition='pop' id='CloseCancelCustomerReservationPopup'>No Return to Customer Details</a>
</div>
</div>
The problem I'm having is that when the loadCancelCustomerReservation function is called, the popups that I expected to contain the jquery variables are empty, these variables will eventually be passed to PHP via ajax but I can't figure out how I can use these variables in my 2 different functions. Is it not possible to pass jquery variables in this way?
$("#loadCancelCustomerReservation").click(function(){
var sizecode = $('#cancelReservationSizecode').val();
var unit = $('#cancelReservationUnit').val();
window.alert(sizecode);
window.alert(unit);
});
You're calling .val() on a <div> tag, when you're setting the value with .html().
Change your code to this:
$("#loadCancelCustomerReservation").click(function(){
var sizecode = $('#cancelReservationSizecode').html();
var unit = $('#cancelReservationUnit').html();
window.alert(sizecode);
window.alert(unit);
});

Create custom variable names

I have an orientational question that i'm not quite sure how to approach, so this is a request for advice.
For a project i'm working on i would like to assemble 'custom' variable names. For example, lets say i have this html page:
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Now i know i can get the id's in jQuery with $('div').attr('id'). This is where my problem comes in:
I would like to create something like this line:
var variable_name_custom = 'Hello world';
where the var-name is generated by getting the div id's. (string div 1 + string div 2 + string div 3).
If i were to put the 3 names together right now, i would get the string 'variable_name_custom', but it would be a string-value of a variable, rather than the name of one.
Is this possible?
I have no idea why you would want to do something like this but:
var varName = getName(); // will get you 'div1_div2_div3'.
window[varName] = 'Hello world';
alert(div1_div2_div3); // Hello World.
Now you can access the div1_div2_div3 global var you created.
Take a look at this Fiddle
Here you go: http://jsfiddle.net/lotusgodkk/wd99s/
window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')] = 'Sample';
console.log(window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')]);
<div id="variable"></div>
<span id="name"></span>
<p id="custom"></p>
I think your best bet is to change the var into a property of an object.
names = {};
names[id1+'_'+id2+'_'+id3] = 'Hello world';
Hi you can use map function of Jquery
HTML Code
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Javascript
$(document).ready(function () {
var varname = $("#content > div").map(function () {
return this.id || null;
}).get().join("_");
window[varname] = "Hello World";
console.log("varname = "+varname);
console.log("value = "+window[varname])
});
take a look at this fiddle
Hope this helps
Thanks,
Dhiraj

JQuery onclick attribute undefined in each() loop

Please forgive my awful coding style. I am learning to write a Chrome extension and can't figure out some JQuery stuff. I am trying to parse a document with some rows, each containing a (dynamically generated?) link, the HTML code looks like this:
<div class="row" id="rand">
<div class="display">
<div class="link">
<a name="actionLink" href="#" alt="action" onclick="listener.postAction('form', 'http://***/')" class="alink"><span>Confirm</span></a>
</div>
</div>
I am grabbing the info the following way:
$(".row").each(function(index)
{
var $itemArea = $(this).find(".display");
var id = $(this).attr("id");
var alink = $(this).find(".link").find("a");
var onclick = alink.attr("onclick");
console.log("id=" + id);
console.log("alink=" + alink);
console.log("onclick=" + onclick);
});
Here's the output from JSBin:
"id=rand"
"alink=[object Object]"
"onclick=listener.postAction('form', 'http://***/')"
However, when I debug this in Chrome, the value of "onclick" returned by my code is undefined. To make things more confusing, when I inspect the onclick attribute of alink, it shows the correct value? What am I doing wrong?
Try the following to get your var instead
var onclick = $('.link a:first',this).attr('onclick');

Categories

Resources