I want to perform an onclick and onsubmit at the same time, is this possible? Or if this is bad practice how can I merge the two codes to perform both events?
I have this piece of code checking a mandatory field on the form tag:
onsubmit="return formCheck(this);"
I then have this piece of code on the submit button for the same form:
onClick="jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) }); return false;"
The problem I have is that on clicking the submit button it completely ignores the onsubmit code. How can I merge them together?
UPDATE I want it to check the mandatory fields first then send the form if all is ok.
UPDATE: I've pasted the whole code here, I'm really struggling as this was done by a previous developer. If someone could literally put the solutions into the code that would be great. I'll up the reward.
Put your onClick code in the same function as the onSumbit code.
UPDATE
At the end of your onClick code you return false;, this stops the normal propagation of events and stops the onSubmit event from firing. So if you want the submit button to submit the form, remove return false; from it's onClick handler.
When you click a submit button you will fire a click event on the button and a submit event on the form in which the button is nested (unless you stop the propagation of events with something like return false;).
So you really only need a submit event handler that does the job of both of your current handlers.
Also since it appears that you have jQuery Core included in your page you can attach event handlers like this:
$(function () {
$('#form-id').on('submit', function () {
var $this = $(this);//$this refers to the form that is being submitted
jQuery.facebox({
ajax : 'wishlist.php?emailme=true&name=' + $this.find('#name').val() + '&country=' + $this.find('#country').val() + '&email=' + $this.find('#email').val() + '&department=' + $this.find('#department').val()
});
//now we run your normal onSubmit code and return it's return value of this event handler
return formCheck(this);
});
});
If you are sending the whole form to the jQuery.facebox function then you can use jQuery's .serialize() function to create the necessary query-string:
$(function () {
$('#form-id').on('submit', function () {
jQuery.facebox({
ajax : 'wishlist.php?' + $(this).serialize()
});
return formCheck(this);
});
});
Here is a demo: http://jsfiddle.net/vAFfj/
Docs for .serialize(): http://api.jquery.com/serialize
Note that .on() is new in jQuery 1.7 and in this case is the same as .bind() of older versions.
UPDATE
If you want to check the return value from the formCheck() function before running the facebox plugin then you can do this:
$(function () {
$('#form-id').on('submit', function () {
//check if the form data is valid
if (formCheck(this) === true) {
//if the form data is valid then run the facebox plugin
jQuery.facebox({
ajax : 'wishlist.php?' + $(this).serialize()
});
//also return true to stop running this function
return true;
}
//if the form data is not valid then return false to stop the submission of the form
return false;
});
});
Make the onclick function submit the form.
Not sure if you have a specific requirement for using both onSubmit() and onclick(), but this might help.
Here's the HTML:
<form id="my_form">
Name: <input type="text" id="name" size="20" />
<br />Country: <input type="text" id="country" size="20" />
<br />Email: <input type="text" id="email" size="20" />
<br />Department: <input type="text" id="dept" size="20" />
<br /><input type="submit" id="submit" value="Login" />
</form>
And here's the JS:
$(document).ready(function() {
$('#my_form').submit(function() {
var name = $('#name').val();
var country = $('#country').val();
var email = $('#email').val();
var dept = $('#dept').val();
/* Validate everything */
if (name != '' && country != '' && email != '' && dept != '') {
/* Validation succeeded. Do whatever. */
jQuery.facebox({
ajax : 'wishlist.php?emailme=true&name=' + name + '&country=' + country + '&email=' + email + '&department=' + dept
});
}
else {
alert('Validation failed.');
}
return false;
});
});
Now, you can do two things:
1) If you're using AJAX to do your form stuff, you might want to keep the return false; in the second-last line, as this will prevent your form from submitting.
2) If you want to post your form anyway, just remove return false;. You can also post your form using $('#my_form').submit() whenever you want.
Here's the fiddle:
http://jsfiddle.net/vAFfj/1/
Hope this helps.
I suggest you to write a separate function which do the same task as onClick event.
First check if all required fields have been entered on onSubmit event, if no return false else if all required fields have been entered call the function which perform the same job as function in 'onClick' event.
First of all, you don't need both actions. In your scenario you only need to use the onSubmit attribute on the form tag.
Second, it would be a lot better (for too many reasons) if the actions on the attributes would contain references to functions, and not inline code.
That said, I would change the code as follows :
//some js file included in the page's header
function formSubmitActions(element) {
if (formCheck(element)) {
jQuery.facebox({
ajax : 'wishlist.php?emailme=true&name=' + element.name.value
+ '&country=' + element.country.value
+ '&email=' + element.email.value
+ '&department=' + element.dept.value
});
return true;
}
return false;
}
//the form
<form [...] onsubmit="return formSubmitActions(this)">
[...]
Hope it helps!
there are 2 issues in your code,
1 - form can be submitted by pressing "enter" on any input field. so the onclick event wouldn't be triggered.
2 - if the user clicks the button (assuming you've added a few hacks and both the onclick and onsubmit events are triggered), but the formcheck returns false, the form wouldn't be submitted, but the click event will be successful (you'll have a request sent to wishlist.php)
my suggestion would be as below,
onsubmit = "readyToSubmit(this); return false"
function readyToSubmit(a){
if(formCheck(a)){
jQuery.ajax({
url : ...,
success : function(data){a.submit()}
})
}
}
You submit form in the onclick event now (jQuery.facebox({ ajax:) so simple move this to on submit event handler (in the bottom of formCheck function after all validations passed)
.click(function(e)
{
e.preventDefault();
// click code
});
.submit(function(e)
{
// submit code
});
and ajax async param to FALSE
Why not just make put them together? the submit will occur on submit and on click so you can do
onsubmit="return formCheck(this);jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) }); return false;"
You can do one thing, just write code for submitting your form, like $('#form_id').submit();, instead of return false;. So it will submit the form, after completion of .onclick() code functionality.
Try combining the two like this:
onClick="if (formCheck(this)) { jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) });} return false;"
Related
here is the problem.
i have HTML Form and it has a button submit with an onclick=validationFunction(). When i click this button, values from form goes to this function.
Now, in this function, the values of the form are cheenter code herecked ifenter code here they are correct or not. In addition, it has 1 input Field who has to be checked for validation, and also checked again from database to see it that value exists there. This part is done via ajax. Below the ajax call, there is a return value(boolen) for the function validationFucntion().
Now, what i want. i want either of the two things.
1) ajax should return true or false within its success
2) or ajax should send the value just below where the ajax call ends. By now, i m failing big times to do either of the things.
Here is a sample pseudo code.
function validationFunction()
{
validations checks in progress
$.ajax({
url:'checkIfNumberExists.php',
data : {
'number : num //this num is coming from above
},
method:'GET',
success: function(data)
{
console.log("Return Value = "+this.toReturn);
if( (this.toReturn) > 0 )
{
either return validationFunction from here or set a flag.
}
else
{
either return validationFunction from here or set a flag.
}
});
}
checkIfNumberExists.php
<?php
$num = $_GET['number'];
$toReturn = 0 ;
$queryCheckNo = mysql_query('SELECT * FROM `TABLE` WHERE `number_from_table`="'.$num.'" ');
while($row = mysql_fetch_assoc($queryCheckNo)){
$toReturn++;
}
echo ($toReturn);
?>
try this plug in
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and keep this inside your form
<form id="tempForm" enctype="multipart/form-data">
<input type="file" name="" id="" />
</form>
and you can find the plug in here
I want to passivate form action because i submit the form with js. But if there is form action js doesn't work and page redirects action url. I remove form tags and put div tags with #combination id but it didn't work neither
js:
$("#combination").submit(function(){
var url = "www.myurl.com/?view=listen&";
var i = 0;
$("input:checked").each(function(){
url += "tag[" + i + "]" + $(this).val() + "&";
i++;
});
alert(url);
location.href = url;
});
html:
<form id="combination" action="" method="get" name="combination" target="_self">
<?php foreach($top_tags as $top_tag):?>
<input type="checkbox" name="tag[]" value="<?php echo $top_tag['tag_name'];?>" /><?php echo $top_tag['tag_name'];?><br />
<?php endforeach;?>
<input name="" type="submit">
</form>
you have to prevent the default behavior of the form with "preventDefault" and than start your ajax-call or what ever ;).
$("#combination").submit(function(event){
event.preventDefault();
var url = "www.myurl.com/?view=listen&";
var i = 0;
$("input:checked").each(function(){
url += "tag[" + i + "]" + $(this).val() + "&";
i++;
});
alert(url);
location.href = url;
});
The problem you really could not call the handler this way:
http://api.jquery.com/submit/
handler(eventObject)A function to execute each time the event is triggered.
basically what happend, instead of submitting form you did redirection.
Think about chain:
you call submit method for form, using jquery.
while the event triggered for form, but before the form actually submitted you change the location.
this cancels submitting and instead redirect you to whatever
If you really want things doing this way you may do it into the two ways:
redirection on the server side after the form is submitted
as it was said use ajax http://api.jquery.com/jQuery.ajax/ submitting into the handler and make disable default action either way
$("#combination").submit(function(event){
event.preventDefault();
// code here
});
OR
$("#combination").submit(function(event){
// code here
return false;
});
I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.
i have this form:
<form id="myform" name="myform" action="test.php" method="post">
<input type="text" name="shout-in" id="proShoutIn" maxlength="80" />
<img src="post.gif"/>
</form>
how can i do a ajax post so that i can use if (isset($_POST['shout-in'])){..do something..}?
i need to get the value that gets entered in the <input> and do a post with it.
any ideas?
thanks
$('#add_shout').click(function () {
var $form=$('#myform');
$.post($form.attr('action'), $form.serialize());
});
$.post() - $.ajax() shorthand for the POST method
.serialize() - creates a text string in standard URL-encoded notation
With the 3rd (optional) parameter of $.post() you can specify a callback function which will receive anything that was sent back as its only parameter. It will run when the AJAX query successfully finished (so you can do DOM modifications that depend on the AJAX call, etc.).
You also might want to prevent default form submission (in a lot of browsers pressing Enter in the input field would trigger it) and run the AJAX submission:
$('#myform').submit(function (e) {
$('#add_shout').click();
e.preventDefault();
});
$.post("test.php", $("#myform").serialize(),
function(data) {
// do something with the response
}
);
$("#myform").submit(function (e) {
$.post(this.action, $(this).serialize(), function (data) {
//handle response
});
//prevent form from submitting. In jQuery, do not use return false
e.preventDefault();
}
Nettuts plus:
Submit A Form Without Page Refresh using jQuery
i made this form:
<form id="form" name="msgform" method="" action="">
<input type="text" size="40" id="msg" name="message"/>
<input type="submit" id="button" name="clicker" value="click" />
</form>
and this jquery script:
$(document).ready(function(){
$("#button").click(function(){
$("#form).submit(function(){
var submision= $("#form).val();
$.post("txt/process.php", submision, function(data){
alert(data);
});
});
});
});
and this is the process.php file:
<?php
echo $_POST['message'] . "";
?>
now when i click the button the form is submited, but it sends it using the GET method because i can see it in the adress bar, but it never gets sent to the php file, and i checked to see if the names are correct and if i specify the POST method it still doesnt go to the php file.
is the server or browser ignoring the code? or am i doing the whole thing wrong?
thanks
Please find the following code, it works and please go through with the documentation, it will tell you that what the mistake was being done.
$(document).ready(function(){
$("#button").click(function(){
$("#form").submit(function(){
/* var submision= $("#form).val();
THIS DOESN'T WORK TO GET ALL OF THE ELEMENTS IN
FORMAT TO PASS TO $.post EVENT,
We can do this as I did in following example
*/
$.post("txt/process.php", { msg: $("#msg").val() }, function(data){
alert(data);
});
/* Also you didn't put return false statement just at the end
of submit event which stops propagating this event further.
so it doesn't get submitted as usually it can be without ajax,
So this stops sending the form elements in url. This was because
by default if you define nothing in method property for form
then it consider it as GET method.
*/
return false;
});
});
});
Let me know please you are facing any issue.
You don't need to register the submit event for the form inside the click handler of the button. As it is a submit button it will automatically try to submit the form for which you register the corresponding handler:
$(function() {
$('#form').submit(function() {
// Get all the values from the inputs
var formValues = $(this).serialize();
$.post('txt/process.php', formValues, function(data) {
alert(data);
});
// Cancel the default submit
return false;
});
});
$("#form).submit(function(){
see if this selector is missing a "
$("#form").submit(function(){