I want to use an event listener for preventing the onclick statement of a submit button, however, using event.preventDefault() doesn't work as intended.
The code is like this:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript">
function addListener() {
document.getElementById("submit").addEventListener("click",
function(ev) {
alert("listener");
ev.preventDefault();
},
false);
}
</script>
<title></title>
</head>
<body onload="addListener();">
<form id="form" method="post" target="">
<input type="submit" id="submit" onclick="alert('onclick')" value="test" />
</form>
</body>
</html>
The expected behaviour is only "listener" will be alerted, but in practice (Firefox 3.7a5pre), "onclick" and "listener" are both alerted, in the given order.
It seems that onclick is being executed before the listener, so event.preventDefault() doesn't work. Is there a way to prevent onclick from being executed?
DOM0 handlers (onclick attributes and the like) and DOM2 handlers (dynamically added via attachEvent/addEventListener) are independent of one another.
The only thing you can do is remove the DOM0 handler (by assigning an empty string to the attribute) and go with just DOM2 handlers.
You can retrieve the DOM0 handler from the attribute before removing it, and re-register it as a DOM2 handler instead. You get into some browser inconsistencies (some will give you a Function object, others will give you a string), but those are readily handled in the code.
You can try this:
function addListener() {
document.getElementById("submit").addEventListener("click",
function(ev) {
alert("listener");
ev=ev¦¦event;
ev.preventDefault? ev.preventDefault() : ev.returnValue = false;
},
false);
}
Related
Hello I came across a weird behavior with an onclick attribute regarding form submission.
Page on Server:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-us" >
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Return Form Example</title>
<script type="text/javascript">
function doSomething(){
alert("hey");
return false;
}
</script>
</head>
<body>
<form action="submit.php" method="post">
<input type="submit" onclick="return doSomething()" value="click me!">
</form>
</body>
</html>
In this example, running on my server, when I click the submit button I get an alert saying hey and I stay on the current page. However, I tried to set this same example up on jsfiddle and I get an 404 error meaning the form was submitted. I cannot figure out why this occurs.
Here is the jsfiddle where I am trying to replicate the behavior on my server.
jsfiddle:
http://jsfiddle.net/46XSv/
You want to check the option "no wrap - in <head>" which is "Do not wrap the Javascript code, place it in section".
Select "no wrap - in <head>" under "Framework and extensions"
In this page you'll find the description of each of the options around the bottom: http://doc.jsfiddle.net/basic/introduction.html.
Also its a good practice to include semicolon at the end of your return statement, like the following:
<input type="submit" onclick="return doSomething();" value="click me!">
You should use onsubmit on the <form> element instead of onclick on the <input> element. It will work correctly.
with inline event listeners I mean HTML elements attributes for event registration like onsubmit/onreset attributes rather than dom node properties for registering event.
I'm asking because when I register an event handler that returns false to onsubmit/onreset attributes of a form, by submitting/reseting the submit/reset process is performed.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<script type="text/javascript">
function f()
{
return false;
}
</script>
</head>
<body>
<form action="" id = "form" onsubmit = "f()" onreset = "f()">
<input type="text">
<input type = "submit" value = "submit">
<input type = "reset" value = "reset">
</form>
</body>
</html>
When you provide event handlers via the HTML attributes, the string you provide creates a function which is called by the browser when the event occurs.
So in your example, the onsubmit and onreset attributes create two functions equivalent to:
function() {
f();
}
Because that anonymous function doesn't return false, the submit and reset events aren't blocked. If that is what you want to do, you can do one of the following.
To always block default handling:
onsubmit="f(); return false;" onreset="f(); return false;"
To conditionally block default handling (and a little bit better code style, IMO):
onsubmit="return f();" onreset="return f();"
Whenever the jQuery is triggered I recieve the error 500 Internal Server Error, does anyone have any ideas why the code below might be causing this?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="../meta/js/jquery-1.7.2.js"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(e){
e.preventDefault();
alert('I clicked it');
});
});
</script>
</head>
<body>
<form name="form1" method="post">
<button id="button">grab user data</button>
<select></select>
</form>
</body>
</html>
I'm gonna guess its because of this variable:
<%=button.ClientID %>
There is nothing else (shown) that would signify anything else that would throw an error.
Can you clarify what you mean by 'jQuery is triggered'? Does that mean upon 'click' ?
Or just by loading this page (I assumed the later)
I would guess that it's giving the error with this line:
$('#<%=button.ClientID %>')
Hard code a value instead and test it:
$('#buttonID')
In order to achieve what you want this will do the job:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#myButton').on('click',function(){
alert("i clicked it");
});
});
</script>
</head>
<body>
<button id="myButton">Click Me!</button>
</body>
</html>
$(document).ready is used to execute your code just after your page is rendered, then $('myButton') will get any element with an id "myButton", then you will use the method "on" to attach any event you want, in this case you will want to choose the "click" event, then you should give an anonymous function where you will put the code you would like to execute on that action.
Your button is inside a tag with action="". This will cause a postback to "/". If your server doesn't handle this correctly, you will get an internal server error.
if you only want the alert to show, you can call preventDefault on the jQuery event object. Se example below:
$(document).ready(function() {
$('#<%=button.ClientID %>').click( function(e) {
e.preventDefault();
alert("i clicked it");
});
});
EDIT:
Forget what i wrote above. It doesn't work. Instead, use the submit event on the form. Like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="#{'/public/javascripts/jquery-1.6.4.min.js'}" type="text/javascript" charset="${_response_encoding}"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(e){
e.preventDefault();
alert('I clicked it');
});
});
</script>
</head>
<body>
<form id="form1" method="post" action="">
<button id="button">grab user data</button>
<select></select>
</form>
</body>
</html>
you are attaching the submit event to #form1 but your form doesn't have an id, only a name. You must select the form by name, $("form[name='form1']") or give it an id of id="form1".
So can someone please tell why neither of these options will actually submit the form? I am trying to do something more complicated but I have boiled it down to this to try and figure out why I can't seem to get this form to submit using a click event and submit()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#submitButton').click(function(e) {
e.preventDefault();
$("#testForm").submit();
});
$('#submitLink').click(function(e) {
e.preventDefault();
$("#testForm").submit();
});
});
</script>
</head>
<body>
<form action="javascript:alert('submitted');" method="post" id="testForm">
<label>Name</label>
<input type="text" name="name" value="" />
<input type="submit" name="submit" value="Submit" id="submitButton" />
<p>Submit Form</p>
</form>
</body>
</html>
Thank you!
it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.
Why not simply use the submit button to run the code you want. If your function returns false, it will cancel the submission.
$("#testForm").submit(function() {
/* Do Something */
return false;
});
If you have a form action and an input type="submit" inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
Using jQuery button click
$('#button_id').on('click',function(){
$('#form_id').submit();
});
Do you need to post the the form to an URL or do you only need to detect the submit-event? Because you can detect the submit-event by adding onsubmit="javascript:alert('I do also submit');"
<form action="javascript:alert('submitted');" method="post" id="testForm" onsubmit="javascript:alert('I do also submit');">...</form>
Not sure that this is what you are looking for though.
I've written a jquery script which works fine, but now I'm trying to make it into a plugin. Once it's in the plugin though, the mouseup function on the html appears to increase the cache of the same element by one every time, and I can't figure out why.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head>
<body>
<div class="box">Box 1</div>
<script type="text/javascript">
//<![CDATA[
$(function(){
(function($) {
$.fn.myPlugin = function() {
return this.each(function(){
var $this = $(this);
$('html').mouseup(function(){
console.log('cached +1: ' + $this);//this ouput increases by one every mouseup
});//html mouseup
console.log('cached once: ' + $this);// this output displays once per mouseup
});// return this each
} //fn myPlugin
})(jQuery);
$('.box').mousedown(function(){
$(this).myPlugin();
});//.box mousedown
});//document ready
//]]>
</script>
</body>
</html>
If someone could explain why this is happening (in as much layman's terms as possible), I'd be very grateful.
Thanks
You should tell us what you actuallywant to achieve but for a start:
Every time you click the element, $(this).myPlugin() gets executed.
This function itself binds an event handler to the mouseup event, so every time you click the element, a new mouseup event handler is added (but they are all doing the same thing).
So
click: $(this).myPlugin(); gets called -> 1 mouseup event handler.
click: $(this).myPlugin(); gets called -> 2 mouseup event handlers.
click: $(this).myPlugin(); gets called -> 3 mouseup event handlers.
etc.