Get text in containing DIV of clicked link - javascript

I have the following JS:
$(document).on("click", '.like', function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
return false;
});
$(document).on("click", '.unlike', function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
return false;
});
I also have the below html:
<div>
45
<a href = "#" class = 'unlike'>
<div class = "heart"></div>
</a>
</div>
I am trying to get the integer 45 returned to the console using JS but am unable to do so. The 45 is in the div. I am trying to get it returned on click using parent/child or next in relation to the existing html.Any advice on how to do this?
I tried doing
id = $(this).parent().text;
console.log(id);
But it doesn't work.

if you're using chrome dev tools or firebug:
console.log(value);
In internet explorer you will need to start the Dev Tools and refresh the page or console.log won't work.
to return a value in the <div> without an id tag on the div:
$(document).on("click", '.like', function (e) {
$(e.target).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
console.log($(e.target).text());
return false;
});

text is a method, not a property, you have to call it as a function.
var value = $(this).parent().text();
console.log(value);

Try this
var value = $(this).parent().text();
alert($(this).parent().text()); //Alert 45
console.log(value);//print 45 in Console

Use
console.log( $(this).parent().text().trim());

What about this approach with single event handler using toggleClass method:
$(document).on("click", '.like, .unlike', function (e) {
$(this).toggleClass('like unlike');
alert(this.previousSibling.nodeValue);
return false;
});
And we can use plain old javascript to get previous text node value as this.previousSibling.nodeValue.
Demo http://jsfiddle.net/Q69Bb/

Related

EventListener's e.preventDefault(); not working for inner-page href="#hash" links

I am currently building a WordPress site and trying to prevent inner page links for firing. The part of code I use is:
var numberLinks = Array.from( document.querySelectorAll('.benefits-links .inner-nav-link > .number-link '));
numberLinks.forEach( function (link) {
link.addEventListener('click' , numberClick)
})
function numberClick(e) {
e.preventDefault();
console.log(e);
}
When a <a></a> tag is clicked the event is logged but the window still jumps to the href anchor.
Am I missing something? How to stop the execution of the link and add my own functions?
Page of reference is https://dev.cognitivplus.com/grey-box/
Thank you
Just to make a contribution, what made the trick was to add:
e.preventDefault();
e.stopPropagation();
apparently, some relative element was triggering the link
Try bellow codes, it will work :
numberLinks.forEach( function (link) {
link.addEventListener('mouseenter',function(e){
var myLink = e.currentTarget;
myLink.khref = myLink.href;
myLink.href = "#";
});
link.addEventListener('mouseout',function(e){
var myLink = e.currentTarget;
myLink.href = myLink.khref
});
});
Hi I do it this way,
I use a specific class for all the elements i dont want to trigger.
var numberLinks = document.querySelectorAll('.benefits-links');
console.log(numberLinks);
numberLinks.forEach( function (link) {
link.addEventListener('click' , (e)=>{
e.preventDefault();
console.log("anything will trigger except pokemon");
return false
})
})
.benefits-links{
color:red;
}
Google
<br>
Pokemon
<br>
Stack Overflow
Hope it helps

How to fix clicking functionality with javascript?

I have the javascript/html below. When the user clicks on 'heart' or 'coal' it switches to the opposite. However, it only works for 1 click. If I click on 'heart' once, it turns into 'coal'...but if I click on 'coal' now, it doesn't turn into 'heart' again. Any idea on how to fix this?
<script>
$(document).ready(function(){
$('.like').click(function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
console.log('liked');
return false;
})
$('.unlike').click(function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
console.log('unliked');
return false;
})
})
</script>
<div>
<a href = "#" class = 'unlike'>
<div class = "heart"></div>
</a>
</div>
Use
$('body').on('click', '.like', function () {
});
The problem you are facing is because you are adding dynamically an element (by destroying and recreating it), and the new element have no event click handler bound to it.
The solution is the use of event delegation, you can use jQuery on.
Another solution is instead of create again and again the clicked element, add a generic class, and in its click change the inner HTML and switch the like/unlike classes.
Code:
<div> <a href="#" class='handler unlike'>
<div class = "heart">aa</div>
</a></div>
JS:
$(document).ready(function () {
$('.handler').click(function (e) {
if ($(this).hasClass('like')) {
$(this).html("<div class = 'heart'>aa</div>");
} else {
$(this).html("<div class = 'coal'>bb</div>");
}
$(this).toggleClass('unlike');
$(this).toggleClass('like');
return false;
})
})
Demo: http://jsfiddle.net/At3D9/
#meavo is correct.
Here is a sample jsfiddle with a code sample similar to what you posted.
http://jsfiddle.net/Q2pDG/
$(document).on("click", '.like', function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
return false;
});
$(document).on("click", '.unlike', function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
return false;
});

How to get the content inside the link that is clicked jQuery

So I have a couple of links that run the same function when they are clicked. But I need the text they contain as a variable in jQuery.
var myVariable = content inside link
I'm actually using this function that the link activates
function updateStatus() {
var link_text = linktext_here;
jQuery.post("/to/my/php/file/mylist.php", {firstParam : link_text}, function(data) {
//this is your response data from serv
console.log(data);
});
return false;
}
My links:
<a href="javascript:void(0);"
onclick="updateStatus(); class="statusWatching">Watching</a>
<a href="javascript:void(0);"
onclick="updateStatus(); class="statusWatching">On hold</a>
As you can see, I have multiple links that run the same function, now I just want to make sure that whichever link they click, that's the value of the text that goes to the var link_text
I am not using a click function so I am not sure if the current answers would work.
It's quite quick to do using jquery's text() function, and their class selector*
HTML:
Watching
<br>
On hold
** include this JS at the end of your page in <script> tags before the </body>**
$('.statusWatching').on('click', function(event)
{
event.preventDefault();
var link_text = $(this).text();
jQuery.post("/to/my/php/file/mylist.php", {firstParam : anime_id}, function(data)
{
console.log(data);
}
});
*you want to have more than one on the page, so use the class attribute on the links to bind the function to the links, rather than id which should be only be set on one element on the page.
In example
<a href="http://www.link.com" class="mylink" >click here</a>
If you wanna get a hyperlink of a tag you can use
var link = $(".mylink").attr("href"); //to http://www.link.com
But if you wanna get the text of a tag you can do
var linkText = $(".mylink").text(); //to click here
Edited...
with your example
function updateStatus() {
var element = event.target || event.srcElement || event.toElement;
var link_text = element.innerText;
jQuery.post("/to/my/php/file/mylist.php", {firstParam : link_text}, function(data) {
//this is your response data from serv
console.log(data);
});
return false;
}
That's an easy one
var txt = $(this).text(); //assuming your are handling this within a click event
You can assign text using .text(), for example:
$("a:first").text('your text here');
or
$("#a_id").text('your text here');

Append to a.href id from input field

I am trying to append to a link with id a value that is entered from the input text field. I came this far searching stackoverflow but id doesn't work!
<script type="text/javascript">
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
});
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code='.text(value);
});
});
</script>
and this is how the html looks like
<form>
<fieldset>
<input id="txt_name" type="text" value="discount" />
</fieldset>
</form>
<a id="coupon_link" href="https://www.e-junkie.com/ecom/gb.php?c=cart&i=XXXXXX&cl=YYYYYY&ejc=2" target="ej_ejc" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this);"><img src="http://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" alt="Add to Cart"/></a>
You probably meant this:
$(function() {
$("#coupon_link").on('click', function(e) {
e.preventDefault(); // apparently not needed
location.href = $(this).attr('href') + '&discount_code=' + encodeURIComponent($('#txt_name').val());
});
});
You don't have to update the value of #txt_name on keypress; you only have to use the value when the link is pressed.
Fix your code like this :
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
var link = $("#coupon_link");
var originalHref = link.attr('originalHref');
if (!originalHref) {
originalHref = link.attr("href");
link.attr("originalHref", originalHref)
}
link.attr("href", originalHref + '&discount_code='+value);
});
});
A few things to note :
never add anything to a selector when you're targeting an element by ID
your value variable wasn't in the same scope
the return of val can be directly concatenated, you don't need to try to change it to text
you don't need to pass a function to attr in your case
you're trying to make the href grow with every key stroke. This is a bad idea. The solution I propose is to keep the original href
if you're not sure the original href has yet some parameters (i.e. has '?') you should test it (I let you do that)
Overall a much cleaner solution wouldn't be to change the link but to build the href on click on the link :
$("#coupon_link").click(function(e) {
location = this.href + '&discount_code=' + $('#txt_name').val();
});
Not sure to understand, but it looks like a scope issue try this javascript :
<script type="text/javascript">
jQuery(function(){
var value = 0;
$("#txt_name").keypress(function() {
value = $("#txt_name").val();
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code=' + encodeURIComponent(value);
});
});
});
</script>
Try this:
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href", '&discount_code=' + String(value));
});
});
This isnt working because the href isnt being changed as the function is called before a keypress event is triggered. Look into replacing keypress with blur and update the href when blur() is called
i think you need this:
<script type="text/javascript">
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href",href+'&discount_code='+value.toString);
});
});
</script>
look at href don't know where you have that var, if it is needed ok else remove that
You probably need to change the href when a key has been pressed, not only on page load. To do so you will have to do the replacing of the href inside the keyup function, like so:
$(function(){
var link = $("a#coupon_link");
link.data('href', link.attr("href"));
$("#txt_name").on('keyup', function() {
link.attr("href", link.data('href') + '&discount_code='+ this.value);
});
});
So as to not append the &discount_code=*** several times, you need to store the original href somewhere, like in a data attribute.
this one worked for me getting value from input field and append it to the existing link using jquery.
$('#qty').on('keyup', function() {
var theQty = 0;
theQty = $("#qty").val();
var oldHref=$("a#buybtn").attr("href");
$("a#buybtn").attr("href",oldHref+ '&qty=' + String(theQty));
});

jQuery how to get the class or id of last clicked element?

I am trying to get the class or an id of the last clicked element. This is what I have based off of what I found here...
HTML
Button
JQUERY
$('.button').click(function () {
myFuntion();
});
function myFunction (e) {
e = e || event;
$.lastClicked = e.target || e.srcElement;
var lastClickedElement = $.lastClicked;
console.log(lastClickedElement);
}
This sort of does what I want, but I am not sure how to go about modifying it so I can get just the class.
I have also tried using this solution but couldn't get it to work with my code.
$('.button').click(function () {
myFuntion();
});
function myFunction(){
var lastID;
lastID = $(this).attr("id");
console.log(lastID);
}
When I do this my console log comes back as undefined. I am probably missing something obvious. Any help is much appreciated. Thanks.
You can pass clicked element as parameter to your function:
$('.button').click(function () {
myFunction(this);
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
UPDATE added jsfiddle
A couple of ways come to mind:
$(".button").click(myFunction);
Should work with the above myFunction.
$(".button").click(function () { myFunction($(this)); });
function myFunction($elem) {
var lastID;
lastID = $elem.attr('id');
$.data('lastID', lastID);
}
In order to get the class-name of the element, assuming you have an accurate reference to the element from which you want to retrieve the data:
var lastClickedElement = $.lastClicked,
lastClickedElementClassNames = lastClickedElement.className;
This does return the full list of all the classes of the element though.
$('.button').click(function () {
myFuntion(this);
});
function myFunction(ele){
var lastID;
lastID = $(ele).attr("id");
console.log(lastID);
}
First Select all possible DOM Elements
var lastSelectedElement = null
$(document).ready(function(){
$("*").live("click",function(){
lastSelectedElement = $(this);
myFunction($(this));
});
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
than you could play with lastSelectedElement by grabbing it's ID or Class with jQuery .attr("ID OR CLASS");

Categories

Resources