Problems with executing code after a for-in-Loop - javascript

I have a form with multiple added dynamic rows, and i want to do a little validation of the input before i submit the form, e.g. check if all fields have input and such.
So i call this little function when i have an onclick-Event on my Submit-Button:
function validateAndSubmit() {
var form = document.getElementById("mainForm");
var formGroups = document.getElementsByClassName("form-group");
for (var x in formGroups) {
// Validation goes here
....
if (valid == false) {
return;
}
}
form.submit();
So in my logic, the code should iterate over each form-group (which basically represent the individual rows in the form) and check if they are valid. After the first invalid row, the function will return without any result. But if all formGroups are checked, the for-Loop will exit and the form.submit(); call will submit the form.
However, the final submit does not happen. Even if all form elements have valid input, the form does not submit. However, during some debugging i commented out the whole for-loop, and the form submits, but with no validation, of course.
So i am assuming that somehow the for-loop does not exit properly, and could need some help with that problem.
The whole project is written in plain Javascript, however, the library i am using to dynamically add and remove items to the form bases on jQuery.
For reference, you can find the project online here

you shouldn't use for-in at the first place. Just use the plain for form:
for(var i=0;i<formGroups.length;i++)
remember, for-in is for Objects / dictionaries. eg. {'key':'value'}
the first "x" you got in your loop is "length" - your formGroups[x] became formGroups[undefined] and throw an exception instantly.

You could also use a jQuery selector to get the elements. In your example,
$('.form-control').each(function() {
// Validation goes here
console.log($(this));
});

Related

Adobe Acrobat - Error Iterating Over All Fields in a PDF with JavaScript

I'm having trouble iterating over all of the fields in my document to remove the tooltip. Here's my code:
var index=0;
while(index<this.numFields)
{
var nom=this.getNthFieldName(index);
var fieldName=this.getField(nom);
fieldName.userName = "";
index=index+1;
}
I'm getting an error saying fieldName is null and my script won't run. I've seen this answer already:
Iterating over all fields in a PDF form with JavaScript
I get the same error with that code too. If I manually assign a field name to fieldName using var fieldName=this.getField("field1");, it works fine.
Does anyone have any idea why this would error on me?
Edit:
I can iterate over the list and output nom to the console so I know it's grabbing the names of the fields properly. It seems to have trouble dropping that name into the this.getField(nom) statement. No idea why...
Why use while… for this?
Doing exactly the same (setting the mousetip text to a blank string) is simpler using
for (var i = 0 ; i < this.numFields ; i++) {
this.getField(this.getNthFieldName(i)).userName = "" ;
}
and that should do it.
However, unless you have a very good reason, setting the userName to the blank string is not recommended; it is needed if your form is used with assistive devices, and it is also the very nearest and simplest help item.
I figured out my issue.
When I created the form, I used the automatic field detection to create my fields for me in order to save time (there are like 250 fields on this form). The reason I needed the script in the first place was to remove the crummy tooltip names that the feature generates.
Apparently, in its infinite wisdom, the field detection feature named a handful of fields with a leading space ( something like " OF INFORMATIONrow1"). Since getNthFieldName(index) returns the fields in alphabetical order, it was returning one of these broken fields and erroring immediately because getField() doesn't like the leading space in the name.
I renamed the handful of fields and the script works like a charm.

Testing equality for numbers using javascript

newbie with Javascript. I have a javascript function that is checking user input. The html document has two forms. I call validateForm(document.forms[0]) with the first form as an argument. Then in my function I rename the argument to TheForm. (e.g. validateForm(theForm).) The fields contain integers. In validateForm I simply want to check equality for two form fields like this:
if(theForm.Field1.value == theForm.Field2.value)
{
//do something
}
Pretty simple eh? I have tried
theForm.Field[x].value.toString, theForm.Field[x].toString.Trim, theForm.Field[x].
Also tried to assign vars for both fields and test. Viewing the contents in Visual Studio I can see where the fields are exactly the same, and hence, the boolean check should fire.

Using jquery to send a javascript variable to rails variable on submit

So I have this javascript variable I'm generating on my html.erb views that I want to send to a rails variable the form submit. I understand that I can do this using jquery or ajax but my attempts have failed. Here is what I am trying:
Rails variable:
<%= f.text_field :antennatime, :id => "antenna_time" %>
Some HTML:
<input type="checkbox" id="Antenna" onclick="fun();" value="1">
My javascript:
<script>
var str = "This is Some Sample Text";
var ant = document.getElementById("Antenna").checked;
if(antenna == true){
$(document).ready(function(){
$("antenna_time").val(str);
});
}
</script>
To my expectations this is not working. Could someone show the steps I should use to use jquery or ajax to send my javascript var str to my rails variable :antennatime?
It looks like you've misspelled a variable and missed a # from your jQuery selector:
var str = "This is Some Sample Text";
var ant = document.getElementById("Antenna");
if (ant.checked){
$(function(){ // same as $(document).ready()
$('#antenna_time').val(str);
});
}
For clarity, using an if statement is for checking expressions/evaluating - I would add your .checked logic there as it's more clear what's happening.
Your question is a bit confusing. Let me paraphrase to make sure I understand: you have a form, of which one field is filled with a attribute of a model, and when a checkbox is set, you want to set the value of that field, using javascript.
So in reality, you are not setting some "rails variable" but you are changing one field in a form, before submitting it to the server.
So, in that case it is simple, you just omitted the # in your jquery. So you will have to write
$('#antenna_time').val(str)
This will set the field to the requested value. But as per your code, it will do this, only when the page is loaded and when the checkbox is clicked.
This might be what you want, but I would suspect you
want it to be set/unset when the checkbox is clicked? (the fun() function is not shown --speaking of cryptic names)
to be checked before submit only (possibly confusing for the user, and why not just check the value of the checkbox server-side instead then)
Please note, to set a rails variable you will have to post something to the server.
It is not entirely clear why you overwrite the id of the field, which imho is potentially dangerous, since rails uses the id/names to build the params hash to be posted to the rails server. The id of an input-field of an attribute in a model is always built as follows: <model-name>_<attribute-name> which is unique (and clear) enough imho to just use that.
You need to compare the ant variable not antenna since you've defined it above if condition as well as using # to target element with id named antenna_time
Also wrap all your code inside DOM ready, final code look like this:
$(document).ready(function(){
var str = "This is Some Sample Text";
var ant = document.getElementById("Antenna").checked;
if(ant == true){
$("#antenna_time").val(str);
}
});

Check for correct answer (quiz) using PHP and AJAX

I have a picture quiz with a single input field for each image. I need a way to check if the value entered into the input field matches the correct answer and if it does, perform a few operations like add/remove a few CSS classes and increase the score count. And I need this to be done in real time using AJAX.
This is the pseudo-code for the functionality that I want...
if input value == correct answer {
some jQuery to add/remove a few classes
some PHP (I assume) to add 1 to the score count
} else {
some jQuery to add/remove a few classes
}
However, how do I get the value of the input field in real time? Do I still use PHP Post to get the value? What AJAX do I need to do this without a page refresh?
Any help would be greatly appreciated... I'm okay with PHP but very little experience with AJAX. Thank you.
yes this can be done with AJAX, and with jquery (which is not the same).
You can get input string with $("#input_id").val() , show a simple error message with alert("my message"), and use the onchange event. see also what is e.preventDefault() to make the form not submitable if all is not correct
If you want to check if datas are correct with a php request, that's also possible with $.ajax()
See jquery documentation on the web for further information about all theses functions
In case this is useful for anyone else, this is how I achieved my original goal. Contrary to what I first thought, this can all be done using JS and does not require PHP or AJAX to update in real time.
$('input').keyup(function () {
if (($(this).val() == 'test') {
//Stuff
} else {
//Other Stuff
};
});
The .keyup() function is what allows this to work in real-time, as it is called whenever a key is hit on your keyboard.
Then within this, the .val() function is what is used to check the actual user-entered value of the input field. In this case, if this value equals 'test', then it performs whatever you place in the if statement.
Hope that helps if anyone has stumbled across this question hoping for this answer!

Individual Input Validation on Blur

I'm trying to use HTML5 to validate a number input. I am using jQuery to create the element. How can I have the browser display the error message onBlur without having to click the submit button?
jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"});
Set up a .blur() handler. See here.
jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"}).blur(function(){
var val = parseInt(jQuery(this).val(),10);
if(val < parseInt(jQuery(this).attr('min'), 10))
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to min
if(val > parseInt(jQuery(this).attr('max'), 10)){
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to max
});
Something along those lines
Actually, you can't invoke the native validation ui through an API. Due to the fact, that the the validation ui automatically also focuses the element, this would not be a good usability (user can't leave field invalid and decide to do something else on the page).
If you want to do this: you have to implement the validation yourslf using the validity property and the validationMessage property. The code could look like this:
$('input[type="number"]').blur(function(){
//if field is validation candidate and is invalid alert the validationmessage
if( $.prop( this, 'willValidate' ) && !$.prop( this, 'validity').valid){
alert( $.prop( this, 'validationMessage' );
}
});
Of course using an alert, is a little bit stupid, but makes the code clean. If you want to use webshims lib, there is a showError helper. I have put up a demo here
About the helper method $.webshims.validityAlert.showFor:
showFor requires a dom element jQuery object or selector as first argument.
the validationmessage as optional second
and the last is a boolean, which will show the message without focusing the field.

Categories

Resources