I have a data-value in my php code that is used in several places, for example:
<a class="dropdown-item" data-value="<?= $i ?>"></a>
<a class="dropdown-item" data-value="<?= $k ?>"></a>
And now I need to use one of these values in the script
getAttribute('data-value')
But I can’t just use data-value, since it will be relevant to everything that I have, I only need to use this data-value="<?= $k ?>"
How can I specify a value with this variable in the script?
since you want to get the data-value of a specific element with the $k variable, your best bet is giving an id to that specific element and selecting it by id:
HTML
<a id="element_with_k" class="dropdown-item" data-value="<?= $k ?>"></a>
JS
const elementWithK = document.getElementById('element_with_k');
elementWithK.dataset.value // "the content of $k"
In case thete are multiple elements that you want to select then you add an extra class to those elements, query all the elements that have the extra class , loop through them and get each element's value.
Hope this helps, cheers!
Related
I'm trying to echo a dynamic a tag which calls a javascript function, but the parameters are not being echoed correctly. They should retain their capitalization and not add spacing. Why is it doing this?
I've tried removing variables and just echoing a straight string with what I want, but it still displays incorrectly.
What I need:
echo '<img src="'.$info[1].'"/>'
Pure String Version:
echo '<img src="/images/calc-eng-desktop.png">'
Outputs:
<a href="/calc" onclick="redirTrackCalcBtn(" test_button_1",="" "="" calc")"="">
<img src="/images/calc-eng-desktop.png">
</a>
Should Output:
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
I also tried:
echo "<img src=\"".$info[1]."\"/>";
But that still outputs:
<img src="/images/calc.png">
as per Dharman's response I also Tried:
echo '<a href="'.$info[0].'"
onClick=\"redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\"
><img src="'.$info[1].'"/></a>'
This outputs:
<a href="/calc" onclick="\"redirTrackCalcBtn("Test_Banner_1"," "="" calc")\"="">
<img src="/images/preguntanos-h-es.png">
</a>
Edit for context:
It's for a dynamic banner within the content of a blog powered by WordPress.
You can simplify your expressions using the following technique ...
HTML accepts single quote or double quotes for attributes.
PHP can evaluate variables inside of double quote delimited strings. This can make your expressions much more easier to understand.
So based on this, the answer would be:
<?php
echo "<a href='{$info[0]}' onClick='redirTrackCalcBtn(\"{$bname}\", \"{$info[0]}\")'><img src='{$info[1]}'/></a>";
This will give the following result ...
<a href='/calc' onClick='redirTrackCalcBtn("test_button_1", "/calc")'><img src='/images/calc-eng-desktop.png'/></a>
In your question, you have shown an Pure String Version and what you thought was a normal output. Both of those outputs are wrong. You cannot use something like onclick="redirTrackCalcBtn("Test_Button_1", "/calc")" because the double quote right after the opening parenthesis finishes the onclick attribute which become onclick="redirTrackCalcBtn(". After that, the browser will try its best to find the following attributes and their values. So the spaces that you are seeing are just the natural space between attributes.
In conclusion, there is nothing wrong with echo.
You need to escape one set of the double-quotes, otherwise they are mixed together. Since you went for single-quotes in PHP, you need to use double in HTML/JavaScript and then use single-quotes again, but this time escaped from PHP.
echo '<a href="'.$info[0].'" onClick="redirTrackCalcBtn(\''.$bname.'\', \''.$info[0].'\')" ><img src="'.$info[1].'"/></a>';
The JavaScript variables are enclosed within \'
or
echo '<a href="'.$info[0].'" onClick=\'redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\' ><img src="'.$info[1].'"/></a>';
The onlick part is now enclosed with escaped quotes, everything else stayed the same.
You have 3 languages mixed together, 3 layers:
PHP will use '
-->HTML will use "
---->JavaScript will use \'
Each one uses double or single quotes and you only have two to choose from. Therefore you need to escape one of them.
A simpler example:
echo '<a onclick="alert(\'hi\')">Hello</a>';
Perhaps a simpler way to overcome quote escaping confusion is to assign the string in a different way. You can remove one layer of quotation by using heredoc notation.
as an aside, your "correct" output is not correct:
onclick="redirTrackCalBtn("Test_Button_1, "/calc")">
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
Your HTML should look like this:
<a href="/calc" onclick="redirTrackCalcBtn('Test_Button_1', '/calc')">
<img src="/images/calc-eng-desktop.png">
</a>
Using Heredoc notation, you don't have to concatenate and escape, just write it out the way the HTML should be:
$link =<<<LINKINFORMATION
<a href="{$info[0]}" onclick="redirTrackCalcBtn('{$bname}', '{$info[0]}')">
<img src="/images/calc-eng-desktop.png">
</a>
LINKINFORMATION;
echo $link;
Say I have: <a class="helloh" id="helloh">return this value</a>
Basically I want to get the innerText of <a> tag based on class name.
The problem is when I try: alert(document.getElementsByClassName("helloh").innerText); it return undefined but when I try: alert(document.getElementById("helloh").innerText); it return me they actual value that I want.
use document.getElementsByClassName("helloh")[0].innerText instead of document.getElementsByClassName("helloh").innerText.
When using getElementsByClassName, you will get array of elements instead of single array unlike getElementById.
A new syntax version is document.querySelector() which will return the first matching element. It saves you having to do getElementsByClassName('name')[0]
From the following:
<a class="helloh" id="helloh">get by ID</a>
<a class="helloh2" id="helloh2">get by Class</a>
You can use:
// by ID
console.log(document.querySelector('#helloh').innerText)
// by Class
console.log(document.querySelector('.helloh2').innerText)
If you want multiple elements, you can use document.querySelectorAll():
<a class="helloh" id="helloh">get by ID</a>
<a class="helloh" id="helloh2">get by Class</a>
// get both by Class
console.log(document.querySelectorAll('.helloh'))
Notice the # and .
You specify classes with ., IDs by #, and omit both to search by block elements .
For example, document.querySelectorAll('div') will return all divs on the page.
You can also use multiple at the same time:
document.querySelectorAll('div .helloh #helloh2')
var a = document.getElementsByClassName("helloh")[0].textContent;
alert(a);
<a class="helloh" id="helloh">return this value</a>
This question already has answers here:
Get value of a custom attribute
(3 answers)
Closed 6 years ago.
I have this <a> href attribute
<a id="cancel" value="<?php echo $subID;?>" href="#">Cancel</a>
and I need to get its value ($subID) and assign it to a JavaScript variable. How can I do that?
Instead of using value, you should use data-value="<?php echo $subID;?>"
then you can get the value like this
var myVal = $('#cancel').data("value");
You could add the value as a custom data-attribute
HTML:
<a id="cancel" data-value="<?php echo $subID;?>" href="#">Cancel</a>
And then retrieve the value like this
JS:
$('#cancel').data('value');
You don't need jQuery. Plain JavaScript is easy enough:
Traditional:
var value = document.getElementById('cancel').getAttribute('value');
console.log(value);
<a id="cancel" value="Hello world!" href="#">Cancel</a>
Using a CSS selector:
var value = document.querySelector('#cancel').getAttribute('value');
Using jQuery
var value = $('#cancel').attr('value');
Although this works (at least in Chrome), a link doesn't have a value attribute so this HTML is invalid. If you use HTML5 (which you probably will), you can make it valid by naming the attribute 'data-value'. Attributes with the 'data-' prefix are allowed for this purpose.
There are other solutions too, but since they are out of scope here, please check Can I add custom attributes to HTML tags.
You have two ways (and more) to solve this
With jQuery:
var x= $('#cancel').val();
with JavaScript:
var x= document.getElementById("cancel").value;
I need to generate a unique ID via js or PHP. Obviously this is pretty easy, but the part I can't figure out is that I need to generate a unique id for a <p> element, and then reference that unique id in some inline js below.
Here's the code to make this more clear:
<p id="UNIQUE-ID" class="toolbox"><a class="tooltip" onmouseover="tooltip.pop(this, '##UNIQUE-ID');"></a>
Basically, in both places where it says "UNIQUE-ID", I need an identical unique id generated. There will be an unknown number of these kind of <p> and <a> pairs generated dynamically.
Any help is greatly appreciated.
You've said that the <p> and <a> pairs are generated dynamically, and also asked for a unique ID "...via js or PHP..." So I'm going to assume the dynamic generation is via PHP, in some kind of loop.
If so, just remember the value in a variable in your loop and output it in the two required locations, e.g.:
<?php
while (someCondition) {
$id = /* ...generate the ID...*/;
?>
<p id="<?=$id?>" class="toolbox"><a class="tooltip" onmouseover="tooltip.pop(this, '##<?=$id?>');"></a>
<?php
}
?>
(Obviously that's using shorttags, which many people recommend against. But it gets the idea across. If you don't use shorttags, you can easily change that to use echo instead.)
I am just giving the structure.Just change it according to your requirement
<?php
for($i=0;condition;$i++)
{
?>
<p id="par_<?php echo $i;?>" <a id="id_<?php echo $i;?>" href=""></a>
<?php
}
?>
I want to create dynamic html which needs to render as code given below:
<a rel="{gallery: 'gal', smallimage: 'a',largeimage: 'b'}" href="javascript:void(0);"><img src="x1.jpg"></a>
What I wrote following code in jQuery to achive above:
for(i=1; i<=4; i++){
var rela="{gallery:'gal', smallimage:'a', largeimage: 'b'}";
html += "<a href='javascript:void(0);' rel='"+rela+"' ><img src='x"+i+".jpg' /></a>";
}
But when it's executed it renders as below:
<a 'b'}'="" largeimage:="" smallimage:'a',="" gal',="" rel="{gallery:" href="javascript:void(0);"><img src="x1" class="img1"></a>
Using attributes to store data on objects isn't exactly a smart idea as you found out yourself, it doesn't work as you might want it to work. Especially json.
In your case you're trying to store json? Or an object with qoutes in it in the html, the browser however will treat the first qoute it encounters as a closure of the rel attribute.. messing stuff up bigtime.
Store the different properties in a seperate data attribute, or considder storing the items in a js variable and the anchor an id. When you need the data again you use the id on the anchor to recapture the data from the js variable. (read more here on data attributes).
html += "<a href='javascript:void(0);' rel=\""+rela+"\" ><img src='x"+i+".jpg' /></a>";
or
var rela='{gallery:"gal", smallimage:"a", largeimage: "b"}';