I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});
Related
I'm currently loading my page data dynamically clicking on an element like this:
<a onclick="load('url_of_data')">Some Text</a>
But for a better UX I now want to have an element like this:
Some Text&
and then just use preventDefault like this;
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
});
I got this code from this question.
But it does not work, the site is still reloading and not running the function.
I now apply the click handler everytime the dynamic content was loaded and it works fine.
You need to add return false at the end of your function
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
return false;
});
You will need to specify the container div to which the content will be loaded into.
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
//Replace "self" with the container you want to load the content into, e.g. $("#myDiv").load(href);
self.load(href);
});
I Think this will make the work.
$('a').click((e) => {
e.preventDefault();
const href = $(e.currentTarget).attr('href');
window.location.href = href;
});
I just needed to reapply the click handler everytime the dynamic content was loaded.
Now it's working fine
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
window.location.assign(href);
});
It helps you
I plan to add some basic user usage of multiple html pages. To achieve this I want to introduce as little code changes to existing pages as possible. Here is my approach :
Import .js file that contains operations to add listeners to the page and when an event is fired then invoke a function :
<title>myTitle</title>
<input id="click" type="submit" value="click"/>
<input id="test" type="textbox" value="test"/>
<a id="href">href</a>
$('a').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
$('input').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
function sendData(dataToSend) {
console.log('Sending data \n '+dataToSend)
}
for now sendData is just a dummy function, but I plan to modify this to send an ajax request to server endpoint with the dataToSend value.
Is there an alternative method of monitoring what the user clicks instead of coding a tags and input tags ? There may be other input types that I'm not aware of that may get clicked that will not be tracked ?
fiddle :
http://jsfiddle.net/g2Rxc/167/
Because click events may be added after you've imported your listener code, you'll want to use event delegation on the document element.
Since you're running jQuery v 1.6, you'll need to use the delegate method:
$(document).delegate('*', 'click', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 1
Later versions of jQuery handle event delegation using the on method:
$(document).on('click', '*', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 2
I see that your click functions do the same thing so you can nest all the elements in a single click event:
$('a,input,textare,..,..').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
Try:
$("body").find("*").on("click",function()...
You just need to plan what do you want to track, before write the code. By doing that you are going to find which elements and events you really want to track. With that in mind you will write something like:
$('everyElementSeparatedByComma').on('everyEventSeparatedByComma', function(){
...
});
A real example:
$('a, input, textarea, form').on('click, change, keypress, submit', function(){
...
});
I am devloping a website in which I have created an option to upload multiple images using plupload script. Which allows us to trigger a popup when we click on an image to upload mulitple images.
This script requires a JS file to be added which has a function started with the code as below:
$(document).ready(function(){
var baseurl = $('#baseurl').val();
var i = 0;
$('.uploadFiles_one').click(function(){
$('#uploadBox_one').dialog('open');
return false
})
....
..some more js code..
....
})
Now I have modified this JS file so that I would be able to use the same JS file for multiple DOM element in which I have generated via PHP loop, the new script with the code as below:
$( document ).on( "click", ".uploadFiles_loop", function(){
var baseurl = $('#baseurl').val();
var i = 0;
var my_id = $(this).attr('id');
var cnt = my_id.replace("anchor_", "");
$('.uploadFiles_loop').click(function(){
$('#uploadBox_'+cnt).dialog('open');
return false;
});
....
..some more js code..
....
})
The front end would have one Image when any user click on the image it will open a popup. But now when I have modified the script I have to click twice on the image to get the popup. But after that all the rest Image uploader icons got open in single click.
So my question is why I have to click any "Upload Image" twice first time( I mean when the page has been loaded).
Try to remove this extra click handler $('.uploadFiles_loop').click(function(){...});
Leaving just:
$( document ).on( "click", ".uploadFiles_loop", function(){
var baseurl = $('#baseurl').val();
var i = 0;
var my_id = $(this).attr('id');
var cnt = my_id.replace("anchor_", "");
$('#uploadBox_'+cnt).dialog('open');
// Recheck were you want this return false;
return false;
....
..some more js code..
....
})
On your code you had a listener that on click run a function that added a click listener. So only by second click it would run the code $('#uploadBox_'+cnt).dialog('open'); return false;. If you remove that it will run on first click.
P.s. - On your code you have a return false;, if you have more code after it will not work. So I commented it, you might want it after the rest of you code you have.
$(document).ready(function(){
$( document ).on( "click", ".uploadFiles_loop", function(){
var baseurl = $('#baseurl').val();
var i = 0;
var my_id = $(this).attr('id');
var cnt = my_id.replace("anchor_", "");
$('#uploadBox_'+cnt).dialog('open');
return false;
});
....
..some more js code..
....
});
Very very unclear what you are trying to actually accomplish, however, you need to put the action you want to happen when you click, DIRECTLY IN the on function. Don't wrap it in another click function
How can i get the action performed by an hyperlink inside an div using javascript
<div id="example">
<a href="#">a<a>
b
c
</div>
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
alert('a clicked');
}
links[1].onclick = function(){
alert('b clicked');
}
links[2].onclick = function(){
alert('c clicked');
}
Working Example
you can attach event handlers in the loop as well:
var links = document.getElementById('example').getElementsByTagName('a');
for(var i = 0;i < links.length; i++){
links[i].onclick = function(e){
var event = e || window.event;
alert(e.target.innerHTML + ' link was clicked!!!');
}
}
I am guessing you are coming from a java background. So, action performed is not available by default in JavaScript. Neither is an anchor or <a>, an anchor is generally used to link to an external or internal links.
Goes to a mypage.html
Where As what you are asking by action performed is events. For that you should do something like this
Test Link
What this above link does is, executes a javascript function name test();
function test() {
alert('ok the action is performed');
return false; //so that the browser does not decides to navigate after the function is executed
}
Some javascript libraries will give you some workaround for this. Here is an basic example done in JQuery
$("#example a">.click(function() {
//now you have got the action performed work around.
// You can use this as you like
// $this represent the item that was clicked
});
For this functionality in core. #Headshota answers is good example.
#Headshota example of referencing all the links within a div is reasonable, I'm merely expanding on it. I'm not sure what you mean by the action of a link so I'm assuming that you mean the url it points to and perhaps the target (deprecated).
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
// `this` inside this handler points to the <a> element that has been clicked
var href = this.href //where the link points
var target = this.target //if required
//do something with href and target
return false; //don't follow the link
}
etc...
$("#example a").click(function() {
alert("action");
});
If I have id's of the form: t_* where * could be any text, how do I capture the click event of these id's and be able to store the value of * into a variable for my use?
Use the starts with selector ^= like this:
$('element[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
Where element could be any element eg a div, input or whatever you specify or you may even leave that out:
$('[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
Update:
$('[id^="t_"]').click(function(){
var arr = $(this).attr('id').split('_');
alert(arr[1]);
});
More Info:
http://api.jquery.com/attribute-starts-with-selector/
var CurrentID = $(this).attr('id');
var CurrentName = CurrentID.replace("t_", "");
That should help with the repalce.
Try this:
// handle the click event of all elements whose id attribute begins with "t_"
$("[id^='t_']").click(function()
{
var id = $(this).attr("id");
// handle the click event here
});
$("[id^='t_']").click(function()
{
var idEnding = $(this).attr("id");
idEnding.replace(/\t_/,'');
});
Using the click event capture the ID that begins with t_, then replace that with nothing giving a capture the end of the ID value.