Can't trigger click event on a link - javascript

My problem is that I got 2 aspx controls generated like this :
<a id="sortByDate" href="javascript:__doPostBack('sortByDate','')">Date</a>
<a id="sortByLastName" href="javascript:__doPostBack('sortByLastName','')">Last name</a>
so those links allow you to sort the results. I'm trying to put this in a combobox instead of using links.
So I made it like this
<select id="sortBySelect" onchange="javascript:sortBy(this);">
<option value="sortByLastName">Last name</option>
<option value="sortByDate">Date</option>
</select>
with this javascript function
function sortBy(sel) {
var id = sel.value;
$("#" + id).trigger("click");
}
So when you change the selected element in the combobox I want to trigger the click event on the link to call the dopostback to sort.
It does nothing so far. I tried "click", "onclick", "onClick" and nothing works. Unfortunately, this is for IE quirks mode.
I know, this is really not elegant, but I'm really short in time and I need something quick and dirty. I will make an aspx control eventually to handle this nicely.
Any ideas how I could make this work in ie quirks mode?
Thank you

Try changing the location of the page:
document.location = $("#" + id).attr('href');

why don't you just fire the __doPostBack directly:
function sortBy(sel) {
var id = sel.value;
__doPostBack(id,'');
}

Use:
function sortBy(sel) {
var id = sel.value;
alert($("#" + id).length);//just for conforming that the element exists.
$("#" + id).click();}
Actually, jQuery only triggers any event bound to an element. You are trying to call the href action.
If you don't want to change the markup, you could try this solution.
Otherwise, you will have to change your html markup to bind javascript events & then try triggering it.
Good luck!

Everything works as intended!
JSFiddle proof.
Make sure you have an element with the id sortById and sortByLastName !
JavaScript/jQuery
$(document).ready(function(){
$('#sortByDate').click(function(){
alert('Sort By Date Click Event fired!');
})
});
function sortBy(sel) {
var id = sel.value;
$("#" + id).trigger("click");
}
Alternative
Force the window.location change
JavaScript/jQuery
function sortBy(sel) {
var id = sel.value;
window.location = $("#" + id).attr('href');
}
Note: You won't see any change in JSFiddle:
Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

Related

CasperJS click is leads to error even when the element exists

I'm trying to click on a logout button, which I have retrieved from the current page. I successfully got the id of the logout link. But when I click on it, an error occurs
Cannot dispatch mousedown event on nonexistent selector
function getLogoutId()
{
var logoutid = "";
$(document).find("a").each(function(key,value){
var id = $(this).attr("id");
if(id.toLowerCase().indexOf("logout") > -1)
{
__utils__.echo("insidelogout" + id);
logoutid = id;
}
});
return logoutid;
}
var logoutid = this.evaluate(getLogoutId);
fs.write("logout.txt", this.getHTML(), 'w');
this.thenClick("#"+logoutid, function(){});
I have written the html content to a file, in which I checked for the id and it is there. The id attribute in question looks like this:
et-ef-content-ftf-flowHeader-logoutAction
I see nothing wrong with your code aside from strange usage of jQuery.
You can try other CSS selectors for clicking:
casper.thenClick("[id*='logout']"); // anywhere
or
casper.thenClick("[id$='logoutAction']"); // ending
or
casper.thenClick("[id|='logoutAction']"); // dash-separated
Maybe it is an issue with the code that follows the shown code. You can try to change thenClick to click.
Have you tried using just this.click("#"+logoutid);?
Also have you considered using jQuery to click on the button? Something like this...(first make a variable of your id so you can pass into jQuery).
var id = "#"+logoutid;
this.evaluate(function(id){
jQuery(id).click();
},id);

how to create onclick for a link

i have a div for which i set value dynamically during run time, if there is value than i have enable or create a link which will have onclick method where i will call a javascript method.
how to do this in jquery or javascript?
I set value to a div like the following,
document.getElementById('attachmentName').innerHTML=projectInforamtionMap.Cim_AttachmentNames;
this the div :
<tr>
<td align="left"><div id="attachmentName"> </div></td>
</tr>
Kindly help me to find and fix.
Best Regards
You can set a onclick function:
document.getElementById('attachmentName').onclick = function() {};
Assume that your function are previously define like this
function foo(){alert('function call');}
After adding innerHTML
In Javascript
document.getElementById('attachmentName').setAttribute('onclick','foo()');
In Jquery
$("#attachmentName").attr('onclick','foo()');
You have several alternatives
JavaScript:
// var elem = document.getElementById('attachmentName');
elem.onclick = function() {};
elem.setAttribute('onclick','foo()');
elem.addEventListener('onclick', foo, false); // The most appropiate way
jQuery:
// var elem = $('#attachmentName');
elem.click(foo);
elem.on('click', foo);
$('body').on('click', elem, foo);
Between the 3 jQuery alternatives, the last is the best one. The reason is due to the fact that you are attaching an event just the body element. In this case, it does not matter but in other cases, you are probably willing to attach the same event to a collection of elements, not just one.
Therefore, using this approach, the event is attached to the body but works for the elements clicked, instead of attaching the same event to every element, so it's more efficient :)
$('#attachmentName').click(function(){
//do your stuff
})
jquery way:
$("#attachmentName").click(function() {
some_js_method();
});
You can do this without inserting link in the div in following way
document.getElementById("attachmentName").onClick = function () {
alert(1); // To test the click
};
You can achieve it with the help of jQuery as well in the following way.
$("#attachmentName").click(function ()
{
alert(1);
});
for this you have to include jQuery liabray on the page. refer jQuery.com
Still if you forecefully want to include the link in Div then following is the code for it
var link = $("<a>"+ $("#attachmentName").text() +"</a>");
$("#attachmentName").html($(link);
link.click(function () {
alert(1);
});
Hope this would help.
as i was converting a classical asp details page to a one-page ajaxified page, i converted the existing links in the page to get the details loaded in the DIV in the same page. i renamed the href tag to dtlLink and got that data in the jquery load() function.
detail.asp (server.urlencode is added and required here )
<a href=""#"" onclick=""javascript:LoadDetails(this)"" dtllink="detail.asp?x=" & Server.URLEncode(Request("x"))&y=" & Server.URLEncode(Request("y")) > link text </a>
parent.asp (it has some extra code for holdon.js spinner image, button enable/disable, results div show/hide)
Jquery
function LoadDetails(href) {
//get the hyperlink element's attribute and load it to the results div.
var a_href = $(href).attr('dtllink');
console.log(a_href);
$('#divResults').html('');
DisplayHoldOn();
$('#divResults').load(a_href, function (response, status, xhr) {
$('#divCriteria').hide();
HoldOn.close();
if (status == "error") {
var msg = "There was an error: ";
$("#divResults").html(msg + xhr.status + " " + xhr.statusText);
$('#divCriteria').show();
$("#cmdSubmit").removeAttr('disabled');
}
});
}

Unable to find click event

Here is my JQuery Code:
$(function () {
$('[id*=clickbtn]').click(function () {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});
Now the problem is, i have 4 to 5 buttons whose id contains 'clickbtn' when i click the any one of them for first time it works well. But it does not works for second click, any help why is this happening?
[EDIT]:
I tried putting the JQuery on page and it worked.. But wnt to know why it does not work on when i put the same on .JS file?
Yes, the result of your event handlers depends very much on the content of your event handlers. If you'd like to share with us the rest of the code we might be able to help. For now the answer is: working as intended
jsFiddle
If your clicks only work on the first try, then I can assure you that it is only the missing code which is to blame. Provide the contents of oWnd.setUrl and oWnd.show and we might be able to help.
Your wildcard selector is wrong. It should be
$("[id$=clickbtn]")
Try this:
$('input[ID*="Button"]')
OR
First set class="btn" to all buttons you want to do this action then
$(function() {
$('.btn').click(function() {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});

Load Html Content if not exist JQuery AJAX

I have a page with 3 buttons. >Logos >Banners >Footer
When any of these 3 buttons clicked it does jquery post to a page which returns HTML content in response and I set innerhtml of a div from that returned content . I want to do this so that If I clicked Logo and than went to Banner and come back on Logo it should not request for content again as its already loaded when clicked 1st time.
Thanks .
Sounds like to be the perfect candidate for .one()
$(".someItem").one("click", function(){
//do your post and load the html
});
Using one will allow for the event handler to trigger once per element.
In the logic of the click handler, look for the content having been loaded. One way would be to see if you can find a particular element that comes in with the content.
Another would be to set a data- attribute on the elements with the click handler and look for the value of that attribute.
For example:
$(".myElements").click(function() {
if ($(this).attr("data-loaded") == false {
// TODO: Do ajax load
// Flag the elements so we don't load again
$(".myElements").attr("data-loaded", true);
}
});
The benefit of storing the state in the data- attribute is that you don't have to use global variables and the data is stored within the DOM, rather than only in javascript. You can also use this to control script behavior with the HTML output by the server if you have a dynamic page.
try this:
HTML:
logos<br />
banner<br />
footer<br />
<div id="container"></div>
JS:
$(".menu").bind("click", function(event) {
event.stopPropagation();
var
data = $(this).attr("data");
type = $(this).attr("type");
if ($("#container").find(".logos").length > 0 && data == "logos") {
$("#container").find(".logos").show();
return false;
}
var htmlappend = $("<div></div>")
.addClass(type)
.addClass(data);
$("#container").find(".remover-class").remove();
$("#container").find(".hidde-class").hide();
$("#container").append(htmlappend);
$("#container").find("." + data).load("file_" + data + "_.html");
return false;
});
I would unbind the click event when clicked to prevent further load requests
$('#button').click(function(e) {
e.preventDefault();
$('#button').unbind('click');
$('#result').load('ajax/test.html ' + 'someid', function() {
//load callback
});
});
or use one.click which is a better answer than this :)
You could dump the returned html into a variable and then check if the variable is null before doing another ajax call
var logos = null;
var banners = null;
var footer = null;
$(".logos").click(function(){
if (logos == null) // do ajax and save to logos variable
else $("div").html(logos)
});
Mark nailed it .one() will save extra line of codes and many checks hassle. I used it in a similar case. An optimized way to call that if they are wrapped in a parent container which I highly suggest will be:
$('#id_of_parent_container').find('button').one("click", function () {
//get the id of the button that was clicked and do the ajax load accordingly
});

JavaScript: changing the value of onclick with or without jQuery

I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps

Categories

Resources