How to call function on hyperlink text click - javascript

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

Related

How to pass a HTML control to another javascript function

I want to pass HTML control to another function inside JavaScript. I am calling a modal popup which has a input control and a save button.
The function in which i am calling the modal popup has entire GridView row as a parameter. I want to pass this to another javascript function which will be called on the button click inside of modal dialog.
I tried as below but it passes a string variable.
function ShowDialogPeoplePicker(id, requestType, cntrl) {
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Approvers = row.cells[1].getElementsByTagName("span")[0];
if (requestType == "AddApprovers") {
$('#btnAddApprover').removeAttr('onclick');
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
}
}
The below function will be called on a button click and will set the values inside GridView row.
function setApprovers(cntrl)
{
var usernames= $("#hdnApproversName_CTO").val();
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
row.cells[1].getElementsByTagName("span")[0].innerHTML = usernames;
$("#overlayTasks").hide();
$("#dialogTasks").hide();
return false;
}
Instead of attaching your click handler like this:
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
Try this instead:
$('#btnAddApprover').on('click', function() {
setApprovers(cntrl);
});
If you need to remove previously added event listeners, you can do that with:
$('#btnAddApprover').off('click');
Or if you want to attach the listener to listen just one time in the first place, you can use:
$('#btnAddApprover').one('click', function() {
setApprovers(cntrl);
});
(with one instead of on). Hope this helps!
Instead of
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
use
$('#btnAddApprover').click(function() {
return setApprovers(cntrl);
}

Incorrect selector is called on click event

There is the following JS:
for (var catId in this.data.categories) {
(function (catId) {
$("li#tsCat-" + catId).click(function (event) {
$(this).addClass("tax-active");
event.stopPropagation();
})
}(catId))
for (var floor in this.data.floors) {
(function (floor, catId) {
var selector = "#tsCatFloor_" + catId + "_" + floor;
$(selector).on("click", function (event) {
$(this).addClass("active-filt");
event.stopPropagation();
});
}(floor, catId));
}
}
This code forms two level list.
On clicking links on 1st level, it executes correct click handler $("li#tsCat-" + catId).
But on clicking 2nd level it again executes 1st handler $("li#tsCat-" + catId).
It needs to execute 2nd handler $(selector).
Where is the problem?
Sorry, I didn't provided the full view, but what is good I found a solution what could be useful for everyone:
If You're adding .click() event be sure, that You put the data (against which .click is called) already to DOM. Otherwise .click will never be called.

I want to make a parameterized function in javascript in which on button

I want to make a parameterized function in javascript
in which on button click an HTML <label> tag should be append with unique id every time I click on button with a parameter value.
If I understood your question, you are trying to bind a click event to a <label> tag. So just find it on the dom
var myLabel = document.getElementById('--your label id--');
And then call
myLabel.addEventListener('click', function() {
// your code goes here
console.log('hey there!');
});
If you happen to be using jQuery, you can use a cleanner syntax:
$('#label').on('click', function () {
// you can even fetch data from the label:
var title = $(this).attr('title');
var customData = $(this).data('customData');
/* ... */
});

How to get ID of listview item Clicked. [javascript / jquery / jquery mobile]

I need advice on how to detect which <li> is tap/click by the user, then write the 'ID' of the tap/clicked <li> into Localstorage, then use the saved Localstorage to retrieve data for Detail Page.
I'm new to javascript/jquery, if you can provide some simple example code will be very much appreciated.
I know how to write Localstorage, read Localstorage, get JSON data from server API, generate Loop for Listview with unique ID for each <li>.
What I need is, how to use JS to make <li> clickable (link to Detail Page) and write to Localstorage at the same time.
I have tried:
$('.liClass').click(function() { //block of code to write Localstorage };
But the <li> is not clickable and no key/value written to Localstorage. Not to mention to detect which <li> is clicked (this I have no idea).
Please advice, thank you.
Code update:
//Show restaurant listing - NOTE: This is not first page. Link from other Page.
$('#restaurantList').on("pagebeforecreate", function() {
$.getJSON("http://mydomain.com/api/restaurant", function( data ) {
function rstListing(data) {
if ($.isEmptyObject(data) === true) {
alert ('JSON return empty');
} else {
for (i=0; i<data.length; i++){
$('#restaurantListing').append('<li id="' + data[i].restaurant_id + '" class="rstList"><img src="http://mydomain.com/file/img/' + data[i].restaurant_logo + '"><h2>' + data[i].name + '</h2><p>' + data[i].city + '</p></li>');
$('#restaurantListing').listview('refresh');
}
}
}
rstListing(data);
}
);
});
//Listview link to Detail Page
$(document).ready(function(){
$('.rstList').click(function() {
var id = $(this).attr("id"); // Get the ID
alert(id);
console.log(id);
});
});
Also tried:
//Listview link to Detail Page
$('#restaurantList').on("pageload", function() {
$('.rstList').click(function() {
var id = $(this).attr("id"); // Get the ID
alert(id);
console.log(id);
});
});
You don't need to make any <li> element to be clickable by your self, when you add the click event to any element, that will be triggered when the item is clicked.
Your problem will basically be that the element is not loaded when the event is bind to it. So you have to add your code inside document ready event like this.
$(document).ready(function(){
$('.liClass').click(function() {
var id= $(this).attr("id"); // Get the ID
};
});
$('.liclick').click(function() {
alert($(this).attr("id"));//Get id of clicked li
localStorage.setItem($(this).attr("id"),$(this).attr("id")); //stored into localStorage
alert("Data from localStorage "+localStorage.getItem($(this).attr("id"))); // get stored id
});
Working Fiddle
You will need to use the event delegation to assign the click event since you are building the HTML DOM dynamically via JSON request, thus not being able to locate the 'li' elements at the time of the page load. So, it would look like:
$(document).on("click", ".rstList", function (event) {
// click event
}
See this link for more details:
jQuery event delegation
I have solved my problem with the example code provided by stackoverflow member here. My previous problem is because I separate the creation of the listview and bind the click listener in two different page event.
After testing the page event sequence, I'm now putting the click listener into the same page event instead of separate to two. Now my code look like this, hope this will help someone bump into the same problem as me:
//Show restaurant listing
$('#restaurantList').on("pagebeforecreate", function() {
alert('pagebeforecreate event triggered');
$.getJSON("http://mydomain.com/api/restaurant", function( data ) {
function rstListing(data) {
if ($.isEmptyObject(data) === true) {
alert ('JSON return empty');
} else {
for (i=0; i<data.length; i++){
$('#restaurantListing').append('<li id="' + data[i].restaurant_id + '" class="rstList"><img src="http://mydomain.com/file/img/' + data[i].restaurant_logo + '"><h2>' + data[i].name + '</h2><p>' + data[i].city + '</p></li>');
$('#restaurantListing').listview('refresh');
}
}
}
rstListing(data);
alert('rstListing() executed');
$('.rstList').click(function() {
alert($(this).attr("id"));//Get id of clicked li
localStorage.setItem($(this).attr("id"),$(this).attr("id")); //stored into localStorage
alert("Data from localStorage "+localStorage.getItem($(this).attr("id"))); // get stored id
});
}
);
});

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

Categories

Resources