Retrieve name value from button in javascript - 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

Related

Insert variable into file path string in javascript

Depending on the user selection the variable "team" contains different team names as string. I want then display the according team logos which are saved as .png files. Therefor I want to insert the variable's string into the file path. How to do that?
Thank you.
JS:
$('ul.subbar li a').on('click', function(e) { // User clicks on a team in the navbar
e.preventDefault(); // Stop loading new link
var team = $(this).html(); //assign clicked team name to variable
console.log(team);
$('.selectedClub').html(team);
$('.teamLogo').src("'images/Clubs/Germany/' + 'team' + '.png'").alt(team);
});
html:
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="images/man united.png" alt="Manchester United">
</div>
<div class="selectedClub">Manchester United</div>
</div>
</div>
You have a problem here:
$('.teamLogo').src("'images/Clubs/Germany/' + 'team' + '.png'").alt(team);
Should probably be something like:
$('.teamLogo').attr('src', 'images/Clubs/Germany/' + team + '.png').alt(team);
(without the extra quotes)
Better answer is to use string interpolation
$('.teamLogo').src(`images/Clubs/Germany/${team}.png`).alt(team);

how to add a unique id to a onclick event

I am having some code between pre tags and I want to catch al that code with an onclick event
My html structure is like below:
<div class="Message">
<div class="surroundpre">
<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span>
<pre class="CodeBlock id="id22015640">
<!-- code goes her -->
</pre>
</div>
</div>
The pre elements and the div with class surroundpre is created by javascript.
The unique id for the pre:
$('pre').each(function(){
if ($(this).attr('id') == undefined){
$(this).attr('id','id'+Math.floor((Math.random() * 99999999) + 1))
}
});
The div with surroundpre is created like below:
$('.Message .CodeBlock', this).wrap('<div class=surroundpre></div>');
The span is created with php variable:
$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span><br />';
in combination with:
$('.surroundpre').prepend('$SelectButton');
My question: the id1 in the php variable should be replaced with the same unique id as in the pre tag.
How can I achieve this?
Or is there an other method to achieve this?
This might work for you, make a few changes, first in PHP:
$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, this.getAttribute(\"data-block-id\"))">[Select and Copy]</span><br />';
Then in JS:
$('pre').each(function(){
var id;
if ($(this).attr('id') == undefined){
id = 'id'+Math.floor((Math.random() * 99999999) + 1);
$(this).attr('id',id);
$(this).prev('span').attr('data-block-id',id);
}
});
Now the id generated in js is attached to the span at the same time of creation, when it is available to you, and the pregenerated (in PHP) onclick event can access it when it needs it (as long as that is after the ID setting code has run).

strange variable scope in jQuery

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

clearing input text area with dynamic input id's on button click - jQuery

Although the question title gives an impression that I want to ask one question, but there are two problems I have facing at the moment.
I have gone through few similar questions on how to clear the input text area on button click, but most of them are for fixed input class or id's.
Problem 1: I am generating rows dynamically and and all the fields are being populated using JS thus the input ID's for all text boxes are different. Now if a user enter some number on "Apply to all" input field and click the button the same number should be set to all the rows which are added in the betslip.
Problem 2: After entering individual values in the betslip input boxes and if I click "clear all" button. It should clear all the inputs entered earlier in the bet slip.
Here is the HTML structure
<div id="bets">
<div id="idNo1" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_1" type="text">
</div>
</div>
<div id="idNo2" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_2" type="text">
</div>
</div>
<div id="idNo3" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_3" type="text">
</div>
</div>
</div>
JS for adding element in the individual bets
function createSingleBetDiv(betInfo) {
var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field - This is where I am creating the input fields
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text" class="betInput"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
HTML for Apply to all and Clear all button
APPLY TO ALL <input type="text">
CLEAR ALL
JS where I need to implement those 2 functions
function applyToAllBetInput() {
$('.apply').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
}
function clearAllBetInput() {
$('.clearall').click(function() {
$('div.bet').find('input').val('');
});
}
The best thing to do is remove the inline event handlers from the links, like this...
APPLY TO ALL <input type="text">
CLEAR ALL
Then, assign the event handlers in your script...
$("a.button.apply").on("click", function(e) {
e.preventDefault();
applyToAllBetInput($(this).find("input").val());
});
$("a.button.clearall").on("click", function(e) {
e.preventDefault();
applyToAllBetInput("");
});
And this would apply the value to all inputs...
function applyToAllBetInput(value) {
$("#bets div[name=singleBet] .supermid input:text").val(value);
}
If you pass a parameter into applyToAllBetInput and then set the inputs with that then you only need the one function, as they both do the same thing, but with different values. Best to only have 1 bit of code if it's only doing 1 thing, then you only have to fix it once if things change in the future :)
Please replace the id's i've given with your actual button/textarea ids (give ID's to your elements).
$('#txtApplyToAll').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
$('#btnClearAll').click(function() {
$('#txtApplyToAll').prevAll().find('input[type=text].val('');
});
There are several general suggestions I'd make before even starting to write the code. First, Why are you using longhand JavaScript when you have jQuery available? For example:
inputId = divId.document.getElementById('input');
should be simply:
inputId = $(inputId).find('input');
(or something along those lines--I'm not sure what you're after with that.)
Next, you're using inline click handlers. Instead, use event listeners:
<a href="javascript: applyToAllBetInput()" ...
Should be
$('a#my-id').click(function() { ... }
Finally, you can target all your inputs for clearing with a selector like this:
$('div.bet').find('input').val('');

Self written toc jQuery function: jump to link target and show corresponding element

I generate dynamically a toc for elements of class=faqQuestion.
The answer resides in a class=faqAnswer element which is hidden by default.
By clicking on class=faqQuestion entry it will show up with
$(this).next(".faqAnswer").slideToggle(300);
Everything works as expected.
What I want: by clicking on a toc link i will jump to the target faqQuestion element and show the corresponding faqAnweser element.
The way I generate the toc:
$(document).ready(function(){
var url = window.location.pathname;
$('<ol />').prependTo('#toc')
$(".faqQuestion").each(function(i) {
var current = $(this);
current.attr("id", "entry" + i);
$("#toc ol").append("<li class=\"faqToc\"><a id='link" + i + "' href='" + url + "#entry" +
i + "' entry='" + current.attr("tagName") + "'>" +
current.html() + "</a></li>");
});
This is what I tried, which will jump to the selected faqQuestion but the faqAnswer element is still hidden.
$(".faqToc").click(function(event){
$(this).next(".faqAnswer").slideToggle(300);
});
My problem is this - at least I think so - so I tried something like - which results in "undefined"
var url = $(this).prop("href");
alert(url);
Trying attr instead of prop returns also "undefined".
Can you point out my problem?
I'm trying to improve my Javascript and jQuery know how, so I don't want to use a toc-plugin.
Update: HTML looks like this:
<div id="toc">
<ol>
<li class="faqToc">
...
</li>
<li class="faqToc">
...
</li>
</div>
<p id="entry0" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
<p id="entry1" class="faqQuestion">...</p>
<div class="faqAnswer" style="display: none;">...</div>
A very simple way would be to use the index() method since relationship between the TOC elements and the question/answer elements is 1 to 1.
$(".faqToc").click(function(event){
var index=$(this).index(); /* zero based index position of element within it's siblings*/
/* toggle answer element with same index */
$(".faqAnswer").eq(index).slideToggle(300);
});
jQuery API Reference : index()

Categories

Resources