Validate dynamic input form elements using Validator Plugin Jquery - javascript

I am using this http://jqueryvalidation.org/ jquery validation plugin.
HTML dynamic form will be like this
<form name="baby_book" id="baby_book">
<input name="form_elements[16]" id="form_elements[16]">
<input name="form_elements[17]" id="form_elements[17]">
<input name="form_elements[18]" id="form_elements[18]">
<a class="myfont baby_book_save" href="javascript:void(0)" onclick="validatefilesizeform('save')" >Save</a>
</form>
My JS Code will be like this
<script type="text/javascript">
var validator="";
$(document).ready(function(){
var max_length_rules= <?php echo json_encode($valid_rules); ?>;
validator=$("#baby_book").validate();
$.each(max_length_rules,function(k,v){
$.each(v, function(key, value){
$('input[id="'+key+'"]').rules('add',"required");
});
});
});
function validatefilesizeform(type)
{
if(type == 'save')
{
document.baby_book.sec_submit.value="save";
if(validator.form())
{
document.baby_book.submit();
}
}
</script>
While applying dynamic rules like that it doesn't validate the form.
In console it displays this error
Uncaught TypeError: Cannot read property 'form' of undefined
Can anyone help me how to add dyanmic rules . Thanks.

That's because when the browser finds the validatefilesizeform('save') in the onclick attribute, it evaluates that expression, i.e runs the function. With this syntax you're asigning the result of that evaluation to the onclick event, which is not what you want.
The Cannot read property 'form' of undefined error happens because in that moment the $(document).ready() callback has not yet been executed, and, when the function tries to execute validator.form(), that variable is already undefined. It will be initialized later, inside the $(document).ready().
To get the expected behavior, and avoid the error, you must change the onclick handler to this one:
`onclick="function() { validatefilesizeform('save') }"`
In this case you're registering a function as the value for the onclick attribute. And this function will be evaluated when the control is clicked.
To make it even more clear:
// This is the value returned by the function evaluation:
validatefilesizeform('save')
// This is a function
function() { validatefilesizeform('save'); }
So the second is a function that can be evaluated. The first one evaluates the function. Handlers should always be functions, and not values.

Related

button onclick="e.preventDefault(); return true;" gives e is not defined in browser console

This is my button element:
<button id="loginButton"
...
onclick="e.preventDefault(); return true;"/>
But this approach gives me after login button click error in console:
Uncaught ReferenceError: e is not defined
Do you know how to fix my button to avoid "e is not defined" error in console?
e is a variable commonly used in event handlers. However you never defined e in your code. I recommend using an event listener in JS.
document.getElementById('loginButton').addEventListener('click', function(e) {
e.preventDefault();
return true;
});
This will accomplish what you need.
in events (like onclick="...") you can specify either a function name, then this function has to have a single parameter, where the event object will be passed.
Or you can specify an JavaScript expression (as in your case), in this case there will be created implicit function (event) { ... } with your code placed inside.
I.e. in that case you have to use event (instead of e) as the name of the event object.

Undefined JS alert

I've got an a-tag which reads as this: (and there are number of a-tags being dynamically populated as this stays inside a PHP loop.)
echo "<a onclick='trygettheid();' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
and the JS function looks like below.
function trygettheid()
{
var myvariable = $(this).attr('id');
alert(myvariable);
}
The issue is when a click is triggered, the alert says 'undefined' instead of the desired output of 'main'
Am I missing anything here?
Inside the function this does not refer to the clicked element it may be window object. To fix it pass the reference as an argument to the function. Although there is no need to use jQuery since id can be get from element id property.
PHP :
echo "<a onclick='trygettheid(this);' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
// ------^------
JS :
function trygettheid(ele){
// -----^-----
var myvariable = ele.id;
// ---^--^----
alert(myvariable);
}

How does prototype work for onSubmit:function()?

I was working on Co-drops Minimal Form Interface. I couldn't understand this code snippet in stepsForm.js. (Line 50)
stepsForm.prototype.options = {
onSubmit : function() { return true; }
};
I am new to JS, and wouldn't mind an explanation of the entire code in stepsForm if anyone has the time to do so. But, for the time being, an explanation for the above can do wonders for me. I know what a prototype is, but the onSubmit part is going over my head. I read on another question that this is to prevent refresh, but I feel that is wrong.
The library exposes options property that you may/can use to pass your own overriding values.This one in particular, exposes onSubmit.
For any html form an onSubmit is called when the submit action is invoked by another function or by click.
In the library the default onSubmit is returning true, meaning just execute the action. This can be overriden with you custom function like this...
<script>
var FORM_ELEMENT = document.getElementById( 'myForm' )
new stepsForm(FORM_ELEMENT, {
onSubmit :
function (FORM_ELEMENT) {
alert('You are about to submit the form ');
//manipulate your form or do any preprocess work...
return true;
});
</script>
Within the library the _submit (line 196 stepForm.js) is called which inturn calls the onSubmit. This time, instead of the default, it will execute the one we added above.
stepsForm.prototype._submit = function() {
this.options.onSubmit(this.el);
}
Hope that helps.

Javascript reference error to function

I want to call a Javascript function every time a checkbox changes its value. I do the same for inputs of the select type and there it works just fine. Both inputs are in one table.
This is one element that calls the first function:
<td>
<select name="minuteEnd" id="minuteEnd" onChange="calculateWorkTime()">'.$dropDown_minuteEnd.'
</select>
</td>
And the part which calls the second function
<td>
<input type="checkbox" name="deleteShift" id="deleteShift" onChange="updateSubmitButton()" /><br />
<input type="checkbox" name="deleteShiftConfirm" id="deleteShiftConfirm" onChange="updateSubmitButton()" />.
</td>
Then I define both functions in separate script tags, but I also tried to define them in one, that did not solve the problem. Because I do not always need both of them I call a PHP-function for each to be written.
These PHP functions are
drawScriptCalculateWorkTime();
drawScriptUpdateSubmitbutton();
the actual Javascript code is this:
function drawScriptCalculateWorkTime()
{
echo'
<script>
function calculateWorkTime()
{
//I work (My name can be found)
}
</script>
';
}
function drawScriptUpdateSubmitbutton()
{
echo'
<script>
function updateSubmitButton()
{
//I do not work. I get the error: ReferenceError: updateSubmitButton is not defined
//This is my code
var delete = document.getElementById("deleteShift").checked;
var deleteConfirm = document.getElementById("deleteShiftConfirm").checked;
if(delete && deleteConfirm)
{
document.getElementById("submitButton").disabled = false;
}
}
</script>
';
}
My Browser-console always tells me
ReferenceError: updateSubmitButton is not defined,
but I checked the name about 20 times. Further, it always tells me on window load this:
SyntaxError: missing variable name
This refers to the first line of Code of the second javascript.
I already checked google and even found a quite similar question here ( Javascript Uncaught Reference error Function is not defined ) but that solution did not work for me.
If I did not provide all information needed I will provide them right away.
John
In javascript, delete is a reserved word and cannot be used for a variable name.

returning functions as string in javascript

I am in the process of writing a javascript object that contains a method that returns the html of a standard form. In this object I also have a method validate();
I'd like the form generated to use validate();
So the typical html of a form with validation would probably look like this:
<form id="a" onSubmit="return validate();">
The problem is that I need to be able to reference the object instance so
it would need to be more like onSubmit="my_object.validate();">
I've tried something like
return '<form id="a" onSubmit="return ' + this.validate + '();">';
but I get really strange behavior.
If I make the validate function arbitrarily return true the form gets submitted, false it doesn't. If I do any other calculations in the method I get this error:
> Error: syntax error Source Code:
> return id ==
Has anyone experienced anything like this?
Rather than outputting the event handler in the HTML attribute, you can output the HTML, get a reference to the form object, then attach an event handler programmatically, like this:
<html>
<head>
<script type="text/javascript">
var my_object = {
outputForm: function(container) {
container.innerHTML =
'<form id="a"><input type="submit" value="Validate" /></form>';
this.createdForm = document.getElementById('a');
this.createdForm.onsubmit = this.validate;
},
validate: function() {
// use this.createdForm to get at the controls.
alert("Who dares awake my slumber?");
}
};
function createTheForm() {
my_object.outputForm(document.getElementById('container'));
}
</script>
</head>
<body onload="createTheForm()">
<div id="container"></div>
</body>
</html>
sorry for posting this as an answer, after registering it wouldn't let me edit my original post as non registered user?
I thought about eval but I'm not sure how to even use it in this situation? I've tried it like so
' onSubmit="return eval(' + this.validate+'();)">';
and some other variations but I get the same error.
I would like to avoid having to manually add the event handling as I would like it to be pretty self contained. I was thinking about setting up a regular function which sits outside of the object and then doing something like
' onSubmit="return my_function(' + this + ');">';
then in my_function do this:
my_function(given){ return given.validate(); }
this seems like an awful hack and I'm not even sure if it will work.
Why are you not just applying it to the element after you add it to the page and using a closure to keep scope?
var myId = "bar" + index;
foo.innerHTML="<form id='" + myId + "'>...</form>";
var that = this;
document.getElementById(myId).onsubmit = function(){ that.validate(this); }
Adding event handlers to the markup is always a bad idea.
Use eval() to execute a string as javascript
[EDIT}
Sounds then like you need to prototype the form and then in submit call this.validate(). Get a reference to the form object when you create it using javascript and then define your method for validation and assign that to the validate property.

Categories