Jquery set an event function on a form - javascript

I have a form thats displayed in a modal box now I want to be able to use the same modal box for 2 different pages where they do slightly different things. Is there a way I can set an event or something for the forms submit button to set which javascript function it calls.
I want to do this from within javascript without changing my form code.
Whats the best way to do this?
Can I set a function to a variable and have it called by my button code?
ie:
var buttonFunction;
//Set the button function on load
function MyButtonFuntion() {
buttonFunction();
}

you could do it like this:
var buttonFunction;
if(someCondition){
buttonFunction = function(){
alert("some action");
};
}else{
buttonFunction = function(){
alert("other action");
};
}
function MyButtonFuntion() {
buttonFunction();
}

You may declare a variable with the function name to be called on submit. The following code is an example. Declaring the function to call in a variable functionToCall inside the form will always work here.
<script type="text/javascript">
function callMyFunction(formName) {
var formObj = eval("document." + formName);
if(formObj != null) {
var functionToCall = eval(formObj.functionToCall.value);
if(functionToCall) {
functionToCall();
}
}
}
</script>
<form method="post" name="form1">
<input type="hidden" name="functionToCall" value="form1Function"/>
<input type="button" onclick="callMyFunction('form1')"/>
</form>

Related

javascript timeout function in onSubmit login-form for RememberMe

I'm using javascript for storing cookies in my login form(Remember Me checkbox) and I would want that if user checks the box = cookies saved, and if he unchecks it = cookies deleted(that's ofc if they are saved). That should all happen when the user submits the form(login). It works when for example I put some button so when I click it, cookies are deleted.
This is my form:
<form name="login-form" class="login-form" action="login_exec.php" onSubmit="if(this.checker.checked) toMem(this)" method="post">
These are my js functions:
function toMem(a) {
newCookie('theUsername', document.forms["login-form"]["username"].value);
newCookie('thePassword', document.forms["login-form"]["password"].value);
}
function delMem(a) {
eraseCookie('theUsername');
eraseCookie('thePassword');
document.forms["login-form"]["username"].value = '';
document.forms["login-form"]["password"].value = '';
}
Ok so, I tried to make it like this:
<form name="login-form" class="login-form" action="login_exec.php" onSubmit="if(this.checker.checked) {toMem(this)} else setTimeout(delMem(this), 3000)" method="post">
It didn't work... It deleted the input before the form was submitted. So anyone got an idea?
function toMem(a) {
newCookie('theUsername', document.forms["login-form"]["username"].value);
newCookie('thePassword', document.forms["login-form"]["password"].value);
}
function delMem(a) {
eraseCookie('theUsername');
eraseCookie('thePassword');
//document.forms["login-form"]["username"].value = ''; i commented this out because
//document.forms["login-form"]["password"].value = ''; you dont want to delete the values if a user unchecks remember me
}
"this", inside of setTimeout refers to the window object. Also, setTimeout expects to be passed a function, not an invocation.
better to use a listener here, but I think this should work...
onSubmit="var that = this;if(this.checker.checked) {toMem(this)} else setTimeout(function(){delMem(that)}, 3000)"

Referencing a form assigned to a variable in jQUERY

I have a form with id='form1' as well as another one with 'form2'. On submit, i want to pass both forms as objects to a single validate function which can validate them. I am confused on how to do this.
If i do something like
var form = $('#form1');
Validate(form);
how do i access the text-fields of the variable form?
i don't want to write duplicate validate functions as both forms are ALMOSt similar.
You can do following also...
A Complete example is here...
function validate(formid){
var form = $("#"+formid);
var name = form.find("#name");
var number = form.find("#number");
alert(name.val());
alert(number.val());
}
validate("form1");
validate("form2");
Try .find. Your form will serve as the context and you could reuse it for different forms.
See below:
var form = $('#form1');
function Validate(form){
var field1 = form.find(".field1");
}
With the name of the fields, you can do this:
function Validate(form) {
form = form[0]; // raw element
if (check_syntax(form.name.value)) { doSomething(); }
if (check_syntax(form.email.value)) { doSomething(); }
if (check_syntax(form.anotherfield.value)) { doSomething(); }
}
If every field in the form has a name, you can access it via form.fieldName or form['fieldName'].
Regards.
Assuming both forms are similar:
ValidateForm($("#form1, #form2"));
function ValidateForm(forms){
forms.each(function(){
$(this).find('input[type=text]').each(function(){
//Do something to validate text field
})
$(this).find('input[type=checkbox]').each(function(){
//Do something to validate checkbox
})
})
}

What this the best way to validate a form without using "Fancy Javascript"

I am using backbone.syphone to serialize data and save them to the server.
I am wondering what is the best way to handle the error or validate the date before to send them to the server without using "Fancy Javascript".
P.S.
I just need to check all the fields are not empty.
here is my code:
var myView = Backbone.View.extend({
submitData: function (event) {
event.preventDefault();
var data = backboneSyphon.serialize(this);
myModel.save(data, {
success: function () {
},
error: function () {
}
}
}
Unless you want to do purely server-side validation you will have to use some Javascript to do the validation; I'm not exactly sure what you mean by "fancy". Since you're using Backbone, that very likely means you're using jQuery (well, or Zepto), so I'll consider jQuery to be within "fanciness" boundaries ;-)
With jQuery, the simplest JS I can think of would be something like:
var failed;
$('#yourForm :input').each(function(input) {
if (!$(input).val()) {
alert("You need to fill in " + input.name);
failed = true;
return false;
}
}
// Do whatever else you want to do if (failed)
If you don't want to use fancy javascript code,
in your case, since you are using Backbone,
I recommend you to use backbone.validation.
Here's the link to this library: backbone.validation
Here is a "non fancy javascript" :)
<!DOCTYPE html>
<title></title>
<form id="form" method="post" action="someform.php">
<input id="name" name="Name" value="Name*">
<input type="submit" value="">
</form>
<script>
window.onload = function () {
var yourForm = document.getElementById('form'),
yourInput = document.getElementById('name');
yourForm.onsubmit = function () {
if(yourInput.value == yourInput.defaultValue || yourInput.value == '') {
alert('You must write something');
return false;
}
}
}
</script>

simple if/else form check(should be simple)

I'm attempting a simple if/else that worked in a previous project. But I'm having trouble making it work in a new project.
I have trimmed it down to the simplest version here.
HTML:
<form name="mainForm" action="formProc.php" method="get" id="mainForm" onSubmit="return allChecks();" >
<input type="text" name="name" id="name"/>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
//formVars
var name = $('#name');
function allChecks(){
if(name.val()==""){
alert("lopan");
return false;
}
if(name.val()===""){
alert("lopan");
return false;
}
if(name.val()== null){
alert("lopan");
return false;
}
return false;
}
});
</script>
I'm trying to force a "false" on the form but it still goes to the next page.
I also created another button in the form with type="button", declare it and used:
var btn= $('#clearF');
btn.click(allChecks);
This works, but I'm not sure why.
In troubleshooting, I noticed it went through to the next page. So I started trying to prevent it from going to the next page by adding validation to the fields. The goal is to block it from going to the next page unless valid.
allChecks is not 'visible' for your markup. It is inside of $(document).ready() handler. To make it 'visible' just declare it like this:
window.allChecks=function(){
instead of onsubmit on the markup, why not use jQuery in creating a handler?
$(document).ready(function(){
$('#mainForm').on('submit',function(){
//whatever you want to do on submit
});
});
you can handle submit event this way:
$(document).ready( function(){
//formVars
var name = $('#name');
$("#mainForm").submit( function() {
if ( name.val() === "" ) {
alert("lopan");
return false;
}
else {
return true;
}
});
});
http://jsfiddle.net/YMg9V/1/
Had something like that a while ago, productive code that suddenly changed behavior with submitting. What i now do is in stead of your (fairly normal) code.
<form name="mainForm" action="formProc.php" method="get" id="mainForm" >
<input type="text" name="name" id="name"/>
var btn= $('#clearF');
btn.click(allChecks);
$(document).ready( function(){
//formVars
var name = $('#name');
function allChecks(){
if(name.val()==""){
alert("lopan");
return false;
}else{
mainForm.submit();
}
return false;
}
});
</script>

How to submit form after event.preventDefault();?

I have used javascript to add this when a particular page get loaded.
document.getElementById('commit').addEventListener("click", validateSubmit,
false);
this validateSubmit method have some code which will validate form data and
it will do this
function validateSubmit(){
//some code
window.addEventListener('submit', newsubmit, true);
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = newsubmit;
}
function newsubmit(event) {
var target = event ? event.target : this;
event.preventDefault();
return false;
}
so for the first time while submitting form by clicking its coming in this method and it is preventing form values to submit and after fixing al those values when i am again trying to click on submit button then its not working,in console i am getting this error-
"Uncaught TypeError: Cannot call method 'preventDefault' of undefined"
Please help me...
Thanks in advance..
Try changing your function declaration from
function newsubmit(event) {
to
var newsubmit = function(event) {
the function has to be declared as a variable if you want to use it as a parameter of an event listener.
I don't think you need to go through such pains to prevent user from submitting incomplete form. Try this:
<form name="form1" id="form1" onsubmit="return validateForm()" ....>
<input type="text" id="txtName" />
</form>
function validateForm()
{
//CHECK IF FORM FIELDS CONTAIN VALID VALUES?
var formValid=....;//validation logic
return formValid;
}
Now if during validation you find any error you will set formValid variable to false otherwise if all input is correct set formValid to true. When form will getfalseas return value fromvalidateForm` function it will not submit.
Try this:
function validateSubmit(){
window.addEventListener('submit', newsubmit, true);
HTMLFormElement.prototype.submit = newsubmit;
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
}
function newsubmit(event) {
var target = event ? event.target : this;
event.preventDefault();
return false;
}

Categories