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.
Related
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.
I'm wondering if there's a way to access a JavaScript object from within thymeleaf's inline syntax.
I'm trying to build a URL using the [[#{}]] syntax in JavaScript. However, inside of the URL, I need to get access to a JS variable.
Here's the code:
var fieldPathStr = /*[[#{{lessonId}/questions/{questionId}(lessonId=${lesson.id}, questionId=question.id)}]]*/"1/questions/2";
Specifically, it's the question.id that is the JS variable, but it (obviously) just creates the final URL as:
1/questions/question.id
Is there a way to structure this assignment statement so that I can get the actual value of question.id and have it evaluate it properly?
You can extract values like this:
var lessonId = [[${lesson.id}]];
var questionId = [[${question.id}]];
but I am not sure that it is a way to go. If you are working with the lists, you would need to extract them in js which means twice the work on the machine side...
There is a way to do it, but probably little different than what you thought!
An example of how I managed my popup box to confirm removal of item from the list:
<script th:inline="javascript">
function deleteObject(id) {
bootbox.confirm([[#{msg.ask}]], function(result) {
if (result) {
var url = /*[[ #{'/admin/vozila/izbrisi?vin='} ]]*/ "genericUrl";
url = url+id;
document.location = url;
}
});
};
</script>
Once this is done, all you need is to call it and pass the object id:
<a class="btn btn-default btn-sm" href="#" th:onclick="'javascript:deleteObject(\'' + ${vozilo.vin} + '\');'"><i class="glyphicon glyphicon-remove"></i><span th:text="#{rad.obr}">Radnja - izbrisi</span></a>
So you are not getting thymeleaf rendered inside js, but you pass the values to the function when called.
I guess in your case it would look something like this:
<script th:inline="javascript">
function callLink(lessonID, questionID){
var fieldPathStr = lessonID+/*[[#{'/questions/'}]]*/"1/questions/2";
var finalStr = lessonID+fieldPathStr+questionID;
};
</script>
where questionID, and lessonID should look like this:
Hope this works for you?
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.
Sorry for the vague title. I am using jQuery. I have a small scenario in my app and I am stuck.
Problem: I have two functions in my script named as func1 and func2. I want to execute both of these functions when ever an user clicks on the div element and also to access the value of the code attribute in these two functions.
<div id="testId" code="102">Click ME</div> .
Code:
<html>
<body>
<div id="testId" code="102">Click ME</div>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
script.js:
var code1 = "";
var code2 = "";
func1 = function(){
code1 = $(this).attr('code');
alert("code1 is "+code1);
}
func2 = function(){
code2 = $(this).attr('code');
alert("code2 is "+code2+'2');
}
$('#testId').click(func1, func2);
/*$('#testId').click(function(){
func1();
func2();
});*/
I want to access the value of code="102"in my two functions. I tried two ways.
First I tried the following snippet:
$('#testId').click(func1, func2);
This only executes the func2. The value of the code attribute is also being accessed by func2. But the func1 is not executing! How to do this?
Then I tried a second way. I am able to execute the both functions when ever an user clicks on the div, by using the following snippet
$('#testId').click(function(){
func1();
func2();
});
but now I am unable to access the value of code attribute and it is undefined! How can I access the value of the code attribute in func1 and func2?
I know I can pass the parameters to func1 and func2 like below and later access the values,
$('#testId').click(function(){
func1('value of code');
func2('value of code');
});
But I am looking for a different solution if possible.
Finally I am looking for a way by which I can execute both of the functions and also have access to the value of the code attribute. Any suggestion will be appreciated!
First for all you are ussing the .Click() method so, if you use .click(func1, func2) it hopes that .click( [eventData ], handler ). becouse that only execute the function2 so It's a handlers.
Well you will need execute like:
$('#testId').click(function(){
func1();
func2();
});
If you need get the code, it's much better create a data attribute like:
<div id="testId" data-code="102">Click ME</div>
$('#testId').click(function(){
func1.call(this);
func2.call(this);
});
func1 = function(){ console.log($(this).data('code'));
code1 = $(this).data('code');
alert("code1 is "+code1);
}
With .call() you send who is calling the function.
Advantage:
Well the .data() attr is better becuse all data that you read you will know that it's aditional paramert, instead only code you maybe don't know where it comes from. unsing the .call keep the method clean of parameters.
Disadvantage
You need to know, What does the call do. and Maybe mixing Vanilla with jQuery. :)
LIVE DEMO
This is an issue of scope really. A proper solution can be seen at http://jsfiddle.net/dboots/dhd0dem7/.
In your code, you are referencing $(this) inside func1 and func2. These refer to the actual func1 and func2 scopes and they have no idea what "code" is.
The $(this) inside the click handler, actually refers to the div element you are clicking on so it's fitting to use it there.
In the jsfiddle, we declare code at the global level and set it in the click handler.
var code;
$('#testId').click(function() {
code = $(this).attr('code');
func1();
func2();
});
Then the func1 and func2 functions are able to access it as they see fit.
function func1() {
alert('func1 code: ' + code);
}
function func2() {
alert('func2 code: ' + code);
}
Alternate Solution
Pass the code to the individual functions as seen in http://jsfiddle.net/dboots/dhd0dem7/1/.
function func1(code) {
alert('func1 code: ' + code);
}
function func2(code) {
alert('func2 code: ' + code);
}
$('#testId').click(function() {
code = $(this).attr('code');
func1(code);
func2(code);
});
you can bind your function to the value of this
func1.bind(this)();
func2.bind(this)();
this way when your function tries to access $(this) it will point to the same object as in the click event
Pretty noobish question, and I'm probably thinking about this wrong, but...
Is there a way to pass a javascript object (or a reference to it) to a javascript function within the HTML markup?
For example:
<script type="text/javascript">
var myObject = new Object();
$('body').append('<div onclick=testThis(' + myObject + ')></div>');
function testThis(object)
{
console.log(object);
}
</script>
The markup ends up looking something like this when I inspect it:
<div onclick="testThis([object Object])">
Additional context:
The real use case is a search page in which I am querying SOLR via AJAX and get a result back as JS objects. When the user clicks on the HTML markup representing one of these search results, I want to be able to pass the object(or a reference to it) to a separate JS function for processing.
Am I thinking about this the wrong way?
No, you can't embed a reference to an object into markup.
Instead you probably would like to setup your click event listening in Javascript/jQuery:
var object = new Object();
$('<div/>').appendTo('body').click(function() {
testThis(object);
});
function testThis(value) {
console.log(value);
}