Combining inline onclick event with jquery onclick event - javascript

I have some code that has inline onclick events, and that code cannot be changed.
The code does
onclick="javascript:document.myform.hiddenfield.value='1234';
document.myform.submit(); return false;"
Now, I want to intercept and modify this with an external jQuery file.
However, I have found that the inline onclick will run before any attached event through jQuery.
So my idea was to do something onload, like fetch the inline onclick text, write it to a new attribute for the link, say oldonclick, then set onclick to null via $.prop()
Then my event handler can do it's thing, and if the requirements are met, actually read and execute the old value.
However, at the first hurdle I get a bit stuck, $.prop("onclick") returns a function, not the string from onclick. Therefore I can't assign it to some dummy value and move to the next step.
How can I read the onclick as text, and how could I achieve this jQuery intercept some other way?

Try this:
var onclick = $("a").attr("onclick"); //This is a string
Check the fiddle: https://jsfiddle.net/p50keLy6/

Related

Javascript eventlisteners override other buttons?

I've run into a problem using eventlisteners and javascript (though onclick seems to have the same effect).
I have this in html
<input id="srch" type="button" value="Zoek gebruikers!" onclick="searchButton()">
Now, this initially worked fine and executes the expected javascript code. But, when I add this in another javascript function
var addbutton = document.createElement("input");
addbutton.setAttribute("id","openAddMenu");
addbutton.type = "button";
addbutton.value = "search";
addbutton.innerHTML = "Zoek";
addbutton.addEventListener('click',searchFriendsAsync(),false);
Now my initial button wil try to execute 'searchFriendAsync()' as well.
I'm quite inexperienced with javascript, so I'm sure it's something basic I'm missing. Yet search results on google find answers regarding adding one event to multiple buttons etc, which is .. about the opposite of what I want. I need multiple buttons with different events - some buttons are generated using javascript. (Note, when I add another eventlistener to a third button, both the first and second button will mess up).
One problem is here:
addbutton.addEventListener( 'click', searchFriendsAsync(), false );
I assume searchFriendsAsync is a function defined in your code that you wish to call when addbutton is clicked, is that right?
That's not what this code does. It calls searchFriendsAsync immediately (because of the parentheses) and passes its return value to addEventListener, which doesn't do any good. Simply remove the parentheses to pass a reference to the function itself instead of calling it:
addbutton.addEventListener( 'click', searchFriendsAsync, false );
In JavaScript, there is a difference between searchFriendsAsync and searchFriendsAsync(). The first one is just giving a reference to the function that has to be executed. The second one is actually invoking the function.
The onclick attribute expects JavaScript code. Thus you want to execute the function. Thus the parentheses are needed.
However when you specify the button in JavaScript, you would just want to tell the name/reference of the function to be executed I.e. without the parentheses. The addEventListener function would make sure that the reference is executed. Thus your code would be like this
addbutton.addEventListener('click', searchFriendsAsync, false);

Can you/is this the correct way to add an even listener to an <HTML>/<body> tag?

I'm trying to make a function to check, anytime something is changed on my page, if all input is valid. I thought the best way to do this, rather than attach the function to every input would be to put it on the entire page (hence html/body tag,) but this didn't seem to work in that nothing happened. My code looks like:
<body onchange="removewarn()">
.
form elements
.
.
</body>
and the function
function removewarn(){
if(all input is valid)
{
document.getElementById('warning').style.visibility="hidden";
}
}
The point of which, is to remove a warning put on the page if all elements are not filled in or are not valid.
The onchange event does only work with Form elements, so you will have to add it to every form element. However! there is a easier and cleaner way to do this than doing it inline:
for(i=0; i<document.FormName.elements.length; i++)//gets all the elements of your form.
{
document.FormName.elements[i].onchange = removewarn();//adds the removewarn function to the onchange handler of this element.
}
The onchange event is only supported by inputs, selects and textareas, wich is why your function will never be called if you try to bind it to the body tag.
You will either have to bind it on every input, or to use something like jQuery's delegate method.

Using JQuery to get string value of an onclick() event

Wondered if there was good way to do this, thought I would post to the SO community...
There is a 3rd party web page that I have no control over how it renders, but they allow me to add JQuery.
Using the JQuery, I am creating a nav menu on the side of the page, it will be a list of links. The onclick event of these links I get from existing onclick events already on the page, but when I do a:
var linkLoc = $('#theLink').attr("onclick");
linkLoc returns:
function onclick(event) {
handleJumpTo("com.webridge.entity.Entity[OID[E471CB74A9857542804C7AC56B1F41FB]]", "smartform");
}
instead of what I would expect:
handleJumpTo("com.webridge.entity.Entity[OID[E471CB74A9857542804C7AC56B1F41FB]]", smartform");
I think JQuery is trying to get the event for binding, but I need the actual Javascript markup since I'm creating the HTML dynamically. I guess I could substring the "function onclick(event) {" out, but seems kind of hacky.
Any ideas of an elegant way I could get the onclick markup?
$("#theLink") would return a jQuery object whereas $("#theLink")[0] would give a DOM object. This is a resson that $("#thelink")[0].getAttributeNode('onclick').value would work.
The type of $('#theLink').attr("onclick") is a function, so you can just use that when you bind events to the links.
var linkLoc = $('#theLink').attr("onclick");
$('a#link1').live('click', linkLoc);
Example: http://jsfiddle.net/BdU6f/
You can also run other code in the click handler too, if you need:
var linkLoc = $('#theLink').attr("onclick");
$('a#link1').live('click', function(e){
// Code...
linkLoc(e);
});
Example: http://jsfiddle.net/BdU6f/1/
The "onfoo" attributes have values that are functions, not strings. The semantics of:
<whatever onclick='code code code'>
are that the browser constructs a function object as if you had code that did this:
document.getElementById('whatever').onclick = new Function("event", "code code code");
Thus you don't really need the raw string, since you've got something better: the function itself, ready to be called. You can then bind it as a handler to other elements via JavaScript code, not HTML (which is really a better way to do things anyway). You're using jQuery, you say, so you can use the jQuery ".bind()" API to bind those functions to whatever elements you need.
You should also be aware that there are other ways of binding event handlers to elements, ways that will leave the "onfoo" attributes completely unset.
If I understand where you're going with this, you should be able to assign the returned onclick function straight through to the onclick of your new nav element...
$('#NewNavElement').click($('#theLink').attr('onclick'));
If you need to add additional code to the handler, you can just bind another click handler.
try this;
$('#theLink').getAttributeNode('onclick').value
Revised as per comment:
$('#theLink').get().getAttributeNode('onclick').value

Use jQuery to find an event object

jQuery has wonderful selectors for DOM elements, but can you 'select' an event object.
That is, if I use inline JavaScript on the onclick attribute of an element, could I have a selector to find that event object so I can act on it.
I know I could do something like this:
$("a#some_link").click(function(event){//act on event here});
But how would I find the event object if inline JavaScript was used:
click me
This question is a supplement to an earlier question: calling e.stopImmediatePropagation() from onclick attribute
onclick = "alert(event.type);return false;"
<a id="some_link" href="somepage.html" onclick="alert(event.type);return false;">click me</a>
Test it
Simple $('a').attr('onclick') gets you that data. In Firefox it's wrapped with function() { }
Well this should find 'onclick' events, I do not believe it picks up the jQuery bound events.
$("a,input").filter(function() {
return $.isFunction(this.onclick)
});
If there are any other tag types you might have such an event on, then you would need to add them, you can use "*" as the selector, but that is quite slow.

How to work with dynamically created fields?

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

Categories