Why is event.preventDefault(); not working here? - javascript

The browser URL is not supposed to be altered but it is anyway. That is supposed to be prevented by event.preventDefault() in the event listener for the cityNameSubmit button.
<!DOCTYPE html>
<html>
<head>
<script>
function bindButton() {
document.getElementById('cityNameSubmit').addEventListener('click', function (event) {
event.preventDefault();
})
}
</script>
</head>
<body>
<form>
<fieldset>
<legend>Choose a City</legend>
<input type="text" name="cityName" id="cityName">
<input type="submit" id="cityNameSubmit">
</fieldset>
</form>
</body>
</html>

You created a function but you forget to call this function. try this:
<script>
function bindButton() {
document.getElementById('cityNameSubmit').addEventListener('click', function (event) {
event.preventDefault();
})
}
window.onload = function() {
bindButton();
}
</script>

In fact in your actual code you are just declaring the function bindButton(), you have to call it in order to attach the event, for example in the body onload event, using <body onload="bindButton()"> like this:
<!DOCTYPE html>
<html>
<head>
<script>
function bindButton() {
document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
event.preventDefault();
console.log("form submission prevented !");
})
}
</script>
</head>
<body onload="bindButton()">
<form>
<fieldset>
<legend>Choose a City</legend>
<input type="text" name="cityName" id="cityName">
<input type="submit" id="cityNameSubmit">
</fieldset>
</form>
</body>
</html>
Or even better using an Immediately-invoked function expression (IIFE), like this:
(function() {
document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
event.preventDefault();
console.log("form submission prevented !");
})
})();
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<fieldset>
<legend>Choose a City</legend>
<input type="text" name="cityName" id="cityName">
<input type="submit" id="cityNameSubmit">
</fieldset>
</form>
<script>
(function() {
document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
event.preventDefault();
console.log("form submission prevented !");
})
})();
</script>
</body>
</html>
Note:
Make sure to put the script at the end of the body tag, to ensure that the HTML was parsed.

You need to call the function bindButton() somewhere or simply remove this function definition and leave just
document.getElementById('cityNameSubmit').addEventListener('click',function(event){
event.preventDefault();
})

Related

Why won't this focus event trigger

I have a very simple html file that contains an input element. Whenever the input element is focused on, I want to console.log a message. What happens is, the console.log is fired immediately upon the loading of the page, and never again. I can't use inline onfocus and no jquery. Here is what I've tried.
first
<html>
<body id="fname" >
<input id="fname" type="text" >
</body>
<script>
window.onload = () => document.getElementById("fname").addEventListener(`onfocus`,console.log(`hi`));
</script>
</html>
second
<html>
<body id="fname" >
<input id="fname" type="text" >
</body>
<script>
window.onload = () => document.getElementById("fname").onfocus = console.log(`hi`);
</script>
</html>
What gives?
I think it's because you're not passing in a function to the onfocus event. Try this:
<html>
<body id="someOtherId" >
<input id="fname" type="text" >
</body>
<script>
window.onload = () => document.getElementById("fname").onfocus = () => console.log(`hi`);
</script>
</html>
The console.log statement is executed immediately,
To execute the listener onfocus, you want to wrap it in a function body:
document.getElementById("fname")
.addEventListener(`onfocus`, () => console.log(`hi`) );
You have a duplicated id on the body and didn't provide a function for the onfocus-event.
A working version:
<html>
<body>
<input type="text" >
<input id="fname" type="text" >
</body>
<script>
document.getElementById("fname").onfocus = function() {
console.log("hi");
}
</script>
</html>
I added another input so you can switch between them and see the event fire only on the second one.

Javascript, how to check if handler is attached

If I run dispatchEvent, on an element that has no handlers attached, nothing happens.
<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
function submitHandlers() {
var target = document.getElementById('myForm');
var event = new Event('submit');
var result = target.dispatchEvent(event);
// nothing happens because no handler is attached to target submit event
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="test" value="this is a test">
<input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
</form>
</body>
</html>
How can I determine that no handler is attached an then decide to manually run the document.getElementById('myForm').submit(); ?
I need a Vanilla Js answer...
In pseudo Javascript it would be something like:
<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
function submitHandlers() {
var target = document.getElementById('myForm');
if(target.hasEventListener('submit')) {
var event = new Event('submit');
var result = target.dispatchEvent(event);
}
else {
target.submit();
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="test" value="this is a test">
<input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
</form>
</body>
</html>
Update
I think that this is a Chrome issue, Firefox behavior is different: when you call dispatchEvent if no custom handler is defined, it fires the native "html" submit event (the same as document.getElementById('myForm').submit())

can't ajax post a from with firefox

I want to post a from using jQuery ajax without page reloading, it works fine in Chrome but not works in Firefox 6.0. Below is my code
<html>
<head>
<script type="text/javascript">
function save()
{
$('#myForm').submit(function(event){
event.preventDefault();
$.ajax({
type:'POST',
url:'save.php',
data:$('#myForm').serialize(),
success:function(data)
{
alert('form submitted');
},
error:function()
{
alert('unable to submit');
}
});
});
}
</script>
</head>
<body>
<form id="myForm" action=''>
<input type="text" name="firstName">
<input type="text" name="lastName">
<input type="submit" id="submitForm" onclick="save(myForm);">
</form>
<body>
</html>
Any help would be much appreciated.
You must have a cached version of jQuery in your FF cache, because I do not see you including jQuery anywhere on the page.
Add above other scripts in the head section:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
Include jQuery library in your header section.
I would suggest you get rid of the onclick and save() and just use the jQuery submit handler
<!-- make sure you have doctype -->
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('#myForm').submit(function(event){
event.preventDefault();
$.ajax({
type:'POST',
url:'save.php',
data:$('#myForm').serialize(),
success:function(data)
{
alert('form submitted');
},
error:function()
{
alert('unable to submit');
}
});
});
});
</script>
</head>
<body>
<form id="myForm" action=''>
<input type="text" name="firstName">
<input type="text" name="lastName">
<input type="submit" id="submitForm"><!-- remove onclick -->
</form>
<body>
</html>
Be sure to include jQuery.js also

Form onreset Event after the form reset

Here's a sample form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form onreset</title>
</head>
<body>
<form onreset="myFunction();">
<input type="text" name="fname">
<input type="text" name="lname">
<button type="reset" value="Reset">Reset</button>
</form>
<script>
function myFunction() {
alert("The form was reset!");
}
</script>
</body>
</html>
When I click the reset button, the form onreset event fires first, i.e. the alert message appears before resetting the form fields. How can it happen after the form fields rest?
I also tried the following to no avail:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form onreset</title>
</head>
<body>
<form>
<input type="text" name="fname">
<input type="text" name="lname">
<button type="reset" value="Reset" onclick="myFunction();">Reset</button>
</form>
<script>
function myFunction() {
alert("The form was reset!");
}
</script>
</body>
</html>
Try it
function myFunction() {
setTimeout(function () {
alert("The form was reset!");}, 100);
}

simple jquery does not work [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
When should I use jQuery's document.ready function?
(8 answers)
Closed 9 years ago.
I am new to JavaScript and jquery and want to check fields in a form before submitting. But even a simple example taken from How to do something before on submit? does not work. I do not ge an alert in Firefox and do not see any errors in the webdeveloper's console. See the code:
<html>
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
</script>
</head>
<body>
<form id="myForm" action="foo.php" method="get">
<input type="text" value="" />
<input type="submit" value="submit form" />
</form>
</body>
</html>
And of course there is "jquery.min.js" in the same folder.
You need to add the script in a dom ready handler
jQuery(function () {
$('#myForm').submit(function () {
alert('Handler for .submit() called.');
return false;
});
})
When the js code is executed, the html element has to already exists. To delay the code strat, use document.ready as above:
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
});
</script>
Note: the syntax $('#myForm').submit(function() { is deprecated and should probably be replaced by $(document).on("submit", "#myForm", function() { or something similar :)
EDIT: also for what you ask, see javascript documentation about e.preventDefault(), this could also be useful for what you want :)
This will work too, setting script after element already added to the DOM:
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<form id="myForm" action="foo.php" method="get">
<input type="text" value="" />
<input type="submit" value="submit form" />
</form>
<script type="text/javascript">
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
</script>
</body>
you should try e.preventDefault(); instead of return false; E.g
$(function() { $('#myForm').submit(function(e) { e.preventDefault(); alert('Handler for .submit called.'); }); });
because some times return false; may not be effective on some codes on jquery
<html>
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
});
</script>
</head>
<body>
<form id="myForm" action="foo.php" method="get">
<input type="text" value="" />
<input type="submit" value="submit form" onsubmit="submit" />
</form>
</body>
</html>
demo: http://jsfiddle.net/kapil_dev/6Tf7Y/

Categories