I do have a simple script which is not working properly or as expected.
<script>
function modify_val(target, valeur)
{
$(target).val(valeur)
}
</script>
$row->movie2 ($row->counter relations)
The javascript is working properly as the targeted input value is modified but the page is "redirected" after the click with a page containing:
[object Object]
Why is there a print ? I don't understand... The OnClick method behave the same. href or OnClick="javascript:$('#type1').val('$row->movie2');" also behave the same.
Do you have any idea ?
PS : the page is in https mode.
The return value of an event handler determines whether or not the default browser behaviour should take place as well.
<script>
function modify_val(target, valeur)
{
$(target).val(valeur);
return false;
}
</script>
Change your HTML as. I would suggest you to use onClick attribute
$row->movie2 ($row->counter relations)
Demo
<a href=\"javascript:$('#type1').val('$row->movie2'); void(0);\">
works... Guessing as Mate suggested that a return is mandatory
You probably need to stop the default action of the link by passing the event object and calling preventDefault() or simply returning false from your inline event handler.
function modify_val(target, valeur) {
$(target).val(valeur)
return false;
}
See this post for info on returning false from an inline event handler: What's the effect of adding 'return false' to a click event listener?.
For the cleanest code, I'd recommend not using an inline event handler at all and simply use jQuery (which you seem to already have available) to install a click event handler and keep your code and HTML much more separate (generally considered a good practice). jQuery also allows you to return false from the event handler to prevent the default behavior.
See this article on Unobtrusive Javascript for more info on keeping your HTML and Javascript separate.
Related
I'm newbie in jquery and saw a piece of code with something strange given the functionality of a method, the "preventDefault". Well, to test, i created a test page and made two functions with "preventDefault" inside of it.
I have two questions on the same subject, i hope you can answer me.
$(document).ready( function( ) {
$('a').click( function( event ) {//Func 1
event.preventDefault( );
});
$("#ok").click( function( event ) {//Func 2
event.preventDefault( );
alert("Wut");
//...
});
});
1- Why, in the second function, the "alert( )" runs even if i comment "event.preventDefault( );" and the first function does not happen the same? If i comment "event.preventDefault();" in the first function, the link doesn't work!
I found it strange because regardless of the method "event.preventDefault();" whether or not commented in the second function, the "alert" works the same way. I think even what comes after "alert" would run.
2- What is the real utility of this method, "event.preventDefault ();"? Why, in the second function, it seems to be useless. Can you give me some example of when it might be useful?
Thanks!
The purpose of preventDefault is to prevent the browser's default action related to the event. Your alert isn't the browser's default action, and is unaffected. Following a link is the browser's default action, and so preventing the default prevents following the link.
preventDefault is crucial in many situations. For instance, when handling a form's submit event, we need preventDefault (directly or indirectly) if we do client-side form validation and the form isn't valid; otherwise, the browser would submit the invalid form.
(I said "directly or indirectly" above because jQuery handles the return value of event handlers in a special way: If you return false, it calls preventDefault and stopPropagation for you.)
It prevents the default action of the control. If it a link, it stops the link being followed. If it is a form submission, it prevents the form from being submitted.
It doesn't interact with other JS event handlers on the same element.
Examples of situations where you might use it:
Stopping the browser following a link because you have used Ajax and pushState to load the content and update the URL
Stopping the browser from submitting a form because you have tested the data entered and found a problem with it
The .preventDefault() function prevents the browser from carrying out the normal implicit behavior of an interactive element. If you click on an <a> tag, then apart from anything your JavaScript does the browser will attempt to follow the "href" value and reload the page. That's the "default" behavior that the function name refers to.
Your alert() runs because .preventDefault() has nothing to do with the code in your event handler. If you want to "abort" an event handler, you'd just return from it.
Note that jQuery also gives you .stopPropagation() and .stopImmediatePropagation() to cancel the process of event bubbling. Those also have no direct effect on the code in your event handler.
event.preventDefault() disables the default behaviour of the event. In case of an link the redirect. It does not effect your own code, in this case the alert() call.
I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.
I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.
I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.
EDIT: With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?
You can use the the click function to trigger the click event on the selected element.
Example:
$( 'selector for your link' ).click ();
You can learn about various selectors in jQuery's documentation.
EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined.
You could solve this with something like this:
var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
document.location = linkEl.attr ( 'href' );
} else {
linkEl.click ();
}
Don't know about addEventListener though.
Why not just the good ol' javascript?
$('#element')[0].click()
Just
$("#your_item").trigger("click");
using .trigger() you can simulate many type of events, just passing it as the parameter.
Easy! Just use jQuery's click function:
$("#theElement").click();
Try this
function submitRequest(buttonId) {
if (document.getElementById(buttonId) == null
|| document.getElementById(buttonId) == undefined) {
return;
}
if (document.getElementById(buttonId).dispatchEvent) {
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
document.getElementById(buttonId).dispatchEvent(e);
} else {
document.getElementById(buttonId).click();
}
}
and you can use it like
submitRequest("target-element-id");
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.
I could not make preventdefault to prevent action. I apologize if the answer is too easy but I simply cant find the error. why is it not preventing from entering the link? jsfiddle given below.
http://jsfiddle.net/zwY5p/34/
$('#theForm').click(function(e) {
event.preventDefault();
alert('FORM!');
});
e != event
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
The parameter passed to the handler function is what you need to execute preventDefault on. In your code, you are passing e but calling preventDefault on event.
preventDefault prevents the default browser action. It does not cancel the inline JavaScript, since that runs first. If you have to override that, just remove it (no event listener necessary):
$('#theForm').removeAttr('onclick').
your event parameter name e and the variable you are using event are different,
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
Other than the errors pointed out on other answers there's another small issue, specifically in your markup declaration:
<!-- Use either the closing tag or the slash (/) in the opening tag -->
<button id="theForm" onclick="location.href='http://www.example.com'" />
go to google
</button>
On the topic, you have two different handlers attached to the button element, they are both handling the click event but they are still different and separate things. jQuery won't know about the handler defined in the markup:
var btn = document.getElementById('theForm');
jQuery._data( btn, "events" );
will return an array with a single element which is the handler added via jQuery.
Now you have to re-evaluate the need of two different handlers for the same element and event and apply conditions. Do you really need to do it this way?
You're using 2 'click' events.
You end up using preventDefault once, and it's used after the 1st click event has ran.
If you make your button an href, then your preventDefault will be working.
It will also make more sense, as the JS will be separated from the HTML markup.
Also, of course you must use the same parameter name. (function(event), with event.preventDefault for example).
If you are passing "e" as an event to the function then you should prevent the default action only for that "e" that you have passed and not for "event".
$('#theForm').click(function(e) {
e.preventDefault();
alert('FORM!');
});
jQuery preventDefault() method: http://api.jquery.com/event.preventDefault/
I noticed sometimes that when I use jQuery, a extra '#' gets added to the end of my URL after a jQuery function is called. For example, the URL 'www.mywebsite.com' will change to 'www.mywebsite.com/#' once a jQuery function is initialized. The same for 'www.testsite.com/users.php', is changed to 'www.testsite.com/users.php#'.
Why does jQuery add the '#'?
If your function is running from a link onclick, you need to use event.preventDefault()
See http://api.jquery.com/event.preventDefault/
Probably you're getting this when handling a click event. If you don't want that happens, just add event.preventDefault() or return false at the end in event handler function.
Usually this is because you have a dummy link with a jQuery click handler. It's common to see links with an href of # that are only used to trigger some JavaScript.
Go
Resolve this easily by making a habit of calling e.preventDefault() in your click handlers:
$(function() {
$(".button").click(function(e) {
e.preventDefault();
...
});
});
You can also use return false, but that has the added effect of stopping event propagation. I like to add e.stopPropagation() explicitly if I also want that effect. It makes the code and it's intended effect more explicit and clear for future developers (or myself in 6 months).
I expect this to print "a" because when I call foo(this), the argument seems to be the link tag.
<script type="text/javascript">
function foo (e) {
alert (e .tagName);
}
</script>
click
Instead, it prints "undefined". If I alert(e) it says "object Window". How do I make foo know which element launched it? Without passing/looking up ids.
You should not use href for JavaScript. Bad practice, instead use onclick and this will magically point to the link.
click
You also need to cancel the click action of the link. Either with return false or cancelling the event with preventDefault.
It is better to attach the event with Unobtrusive JavaScript
You can do this directly too
click
The this object is not handled the same in all browsers. This is one of the many items that libraries like Prototype and jQuery try to normalize. That said, however, most browsers will pass the appropriate this during on onclick handle (rather than the href) as many other answers have pointed out. If you want to handle the this appropriately, you'll need to do things like those detailed in this question.
click
function foo(obj) {
alert(obj.tagName);
}
Don't call the element e it's a standard for the event object.
JSfiddle DEMO