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

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

Related

How to decide which element is being clicked in jQuery?

I have more similar elements in HTML which are being added continously with PHP. my question is the following:
With jQuery, I would like to add a click event to each of these <div> elements. When any of them is being clicked it should display it's content. The problem is that I guess I need to use classes to specify which elements can be clickable. But in this case the application will not be able to decide which specific element is being clicked, right?
HTML:
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
jQuery try:
$("test").on("click", function()
{
var data = ???
alert(data);
});
UPDATE - QUESTION 2:
What happens if I'm placing <a> tags between those divs, and I want to get their href value when the DIV is being clicked?
I always get an error when I try that with this.
this refers to the element triggering the event. Note that it is a regular js element, so you'll need to convert it to a jQuery object before you can use jQuery functions: $(this)
$(".test").on("click", function()
{
var data = $(this).text();
alert(data);
});
Like this:
$(".test").on("click", function(event)
{
var data = $(event.target);
alert(data.text());
});
this variable contains the reference of current item
$(document).ready(function() {
$(".test").click(function(event) {
var data = $(this).text();
alert(data);
});
})
;
The class selector in jquery is $(".ClassName") and to access the value, use $(this) as such:
$(".test").on("click", function(){
var data = $(this).text();
alert(data);
});
You can use this inside the function which mean clicked div
DEMO
$(".test").on("click", function () {
alert($(this).html());
});

Get text in containing DIV of clicked link

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/

How to call function on hyperlink text click

How can I call this on_search function by clicking on the text (item.name)?
$.each(docs, function(i, item) {
$('#body').append($('<div>' + item.name </div><br/>'));
});
// call this function whenever user clicks the text
function on_search() {
var url ='http:myhomepage/select/?wt=json&json.wrf=?&q='+item.name;
$.getJSON(url, on_text);
}
Give a class set at event handler to it.
$.each(docs, function(i, item) {
$('#body').append($('<div>' + item.name </div><br/>'));
$(".my-anchor").click(on_search);
});
// call this function whenever user clicks the text
function on_search() {
var url ='http:myhomepage/select/?wt=json&json.wrf=?&q='+item.name;
$.getJSON(url, on_text);
}
Not sure if each link needs to be wrapped inside its own div. In fact, to make this work well, you may want to put all of these links inside a particular div.
From there, here's what you do:
$('#divName').find('a').click(function (event) {
var url=...
event.preventDefault(); // Stops the browser from actually following the link
[...]
});
if you add an id or a class you can the just add
$('.yourClass').click(function()
{
var x = $(this).attr('href');
on_search();
// you would probably want to pass the item name as a parameter: on_search(x);
});

Jquery syntax and variables

I'm trying to make a FadeOut effect after clicking a link. But my syntax seems to be wrong. When i click, it fadeout, and go to a "~~nothing~~.html" page, it just dont get the value to compose the variable.
the id boo is attached to the tag (body id="boo") and in the css stylesheet the id #boo is set to display:none;
I'm using jquery-1.7.2.min
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').val() + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" value="374" href="#">Go to page 374</a>
the 374.html page is in the same folder. If possible, please explain what have i done wrong, and make it step by step. I'm new to jquery.
Thank you!
the .val() method only applies to fields, just putting a value attribute on any element will not be read with the val() method.
Instead use .attr('value').
Or, its better practice to use data-* attributes and use the data() method:
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').data('value') + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" data-value="374" href="#">Go to page 374</a>
The val() function won't give you that value from an anchor tag, use attr("value") to get the valuue of the a tag
$(document).ready(function(){
$('#go').click(function(e) {
e.preventDefault();
var url = $('#go').attr("value") + ".html";
alert(url)
$('#boo').fadeOut(600, function() {
window.location.href = url;
});
});
});​
Alternatively, you can use HTML 5 data attribute to store such kind of value
<a id="go" data-someValue="374" href="#">Go to page 374</a>
And you can access it in javascript like
var someVal=$("#go").data("someValue");
sample http://jsfiddle.net/LyPZB/1/
The a tag doesn't support the attribute value, you should do like this:
set the anchor like this
<a id="go" data-page="374" href="#">...
(data-xxx are custom attributes)
and get its value with
$('#go').data('page')
In this way it will work and you will respect the HTML standard (since the anchor shouldn't have the value attribute)
Try:
var url = $('#go').attr("value") + ".html";
instead of
var url = $('#go').val() + ".html";
From the jQuery docs -
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the .val() method returns an array
containing each selected option; if no option is selected, it returns
null.
There's an example here - http://jsfiddle.net/A8ArH/

capture link text and append to the URL as query string

I want to capture the text that is in between anchor link tag and pass it to the href value as query string so it looks like http://mysite.com/events/Pages/default.aspx?cat=cancer
The reason I can't add that manually is because the value in between and is dynamic. How do I capture that and append to the url using jquery or javascript??
or i can maybe, at the event of Cancer link being clicked, direct it to http://mysite.com/events/Pages/default.aspx?cat=cancer
 Cancer
$("a").on("click", function (e) {
e.preventDefault();
window.location = this.href + $.trim($(this).text());
});
Or you could replace the href attribute for each link:
$("a").prop("href", function () {
return this.href += $.trim($(this).text());
});
Then clicking each link will automatically direct the user correctly. Your selector ($("a") should be more specific, depending on your markup)
Example: http://jsfiddle.net/6U749/
Edit: If you have to do it inline, here's one way:
Cancer
You could do something like this:
$('.someClassImStickingOnLinksThatNeedThisBehavior').each(function()
{
this.href = $.trim(this.href) + $.trim(this.innerHTML);
});
Then, for any link, it would automatically update the HREF to the current HREF plus the value of the node.
You can do:
var yourlink = $("#youlink");
var href = yourlink.attr("href");
var text = yourlink.html();
yourlink.attr("href", href + "?cat=" + text);

Categories

Resources