simple jquery does not work [duplicate] - javascript

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/

Related

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

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();
})

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

javascript addEventListener and alert box

<html>
<head>
<script type="text/javascript">
function fire()
{
document.getElementById("submit1").addEventListner("click",sub,false);
}
function sub()
{
window.alert("submited");
}
window.addEventListener("load",fire,false);
</script>
</head>
<body>
<form action="#">
<input type="button" name="cal" value="Calculate" id="submit1"/>
</form>
</body>
</html>
I don't know where is the error in my code because I am not familiar with addEventListener method, can I know what is the difference between addEventListner and onsubmit ? addEventlistener must use in my code but I am familiar with onsubmit method only, how to change it to addEventListenr ?
You have a typo:
document.getElementById("submit1").addEventListner("click",sub,false);
document.getElementById("submit1").addEventListener("click",sub,false);

"How do I use jQuery's form.serialize but exclude empty fields" does not work (with php)

I'd like to use How do I use jQuery's form.serialize but exclude empty fields but it does not work. I used a minimal example that redirects to a php script:
<html><head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function(){
$("#myForm :input[value!='']").serialize();
alert('JavaScript done');
});
});
</script>
</head>
<body>
<form id="myForm" action="php.php" method="get">
<input id=id1 name=name1 type="text" /><br>
<input id=id2 name=name2 type="text" /><br>
<input id=id3 name=name3 type="text" /><br>
<input id=id4 name=name4 type="text" />
<input type="submit" value="submit form"/>
</form>
</body></html>
An here is the php script
<?php
print_r($_GET);
?>
If I write "111" only into the first textbox, I get from php:
Array ( [name1] => 111 [name2] => [name3] => [name4] => )
Thus, all fields made it into the get parameters.
Can you please help me?
TIA
You cannot use attribute selector for value as it is a changing property.
Use .filter()
$(document).ready(function () {
$('#myForm').submit(function () {
$(this).find(":input").filter(function () {
return $.trim(this.value).length > 0
}).serialize();
alert('JavaScript done');
});
});
Demo: Fiddle
Note: just serializing the input fields does not change in form submission, it can be used only if the form is submitted via ajax.
If you want to do a normal form submission but want to remove the empty fields then use .remove()
$(document).ready(function () {
$('#myForm').submit(function () {
$(this).find(":input").filter(function () {
return $.trim(this.value).length == 0
}).remove();
alert('JavaScript done');
});
});
You can try it with ajax, and get the array data in php file, see below code.
<html><head>
<script src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit_form').click(function(e){
$("#myForm :input[value!='']").serialize();
var form_data= $("#myForm :input[value!='']").serializeArray();
$.post("php.php",form_data,function(data){
alert('JavaScript done');
},"json");
e.preventDefault();
});
});
</script>
</head>
<body>
<form id="myForm">
<input id=id1 name=name1 type="text" /><br>
<input id=id2 name=name2 type="text" /><br>
<input id=id3 name=name3 type="text" /><br>
<input id=id4 name=name4 type="text" />
<input type="submit" id="submit_form" value="submit form"/>
</form>
You need to AJAX the form - just calling serialize does not remove the fields from the request
Live Demo
$('#myForm').on("submit",function (e) {
e.preventDefault(); // cancel the form itself
var opts = $(this).find(":input").filter(function () {
return $.trim(this.value).length > 0;
}).serialize();
$.get($('#myForm').attr("action"),opts,function(data) {
alert(data);
});
});

Implementing jQuery function

I have been trying to implement some JavaScript that would disable a submit button until all fields were filled. I found a great here: Disabling submit button until all fields have values. Hristo provided a link that does exactly what I need here: http://jsfiddle.net/qKG5F/641/.
My problem is that when I try to put together a full "minimum working example" I am completely stumped. I'm sure there's some minor aspect that I'm missing but here's what I've come up with:
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to https://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to https://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
</script>
</head>
<body>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="text" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="text" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br />
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
<div id="test">
</div>
</body>
I simply copied/pasted and added in what I thought would be necessary to make the page work but my submit button remains permanently disabled. What simple part am I missing to make this work??
Thanks!
You have to surround it with an onload function:
$(window).load(function(){
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
});
If you look at the source of the jsFiddle, you'll see it got wrapped the same way.
I tested this on my system, works with your own version of jquery, as well as code with a little change and wrapping javascript in document.ready().
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
});
</script>
</head>
<body>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="text" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="text" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br />
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
<div id="test">
</div>
</body>
</html>
Your original js is an immediately-invoked function expression. Here's a link explaining that pattern:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
You defined an anonymous function and then immediately called it. By the time your html page had loaded, the script had already run. As others correctly answered, you need to instead wait for all the DOM elements to load before executing the script.
While
$(window).load(function(){};
works, you should probably use the jQuery version of this:
$(document).ready(function(){ };
For one, it's the jQuery idiom, and for another, $(window).load fires at a later time, where as $(document).ready() fires as soon as all DOM elements are available; not as soon as all assets (possibly large) are loaded.
Source: window.onload vs $(document).ready()
If you place the JavaScript (the entire script element) at the end of the page, right before the closing body tag, it should work. This is because the JavaScript needs to be run after the DOM is built. By placing your script after the page is loaded (and then immediately invoking it as you are doing), the document will be ready and it should work.
Working example: http://jsfiddle.net/NgEHg/

Categories