form loop all and check radio + options - javascript

I have a long form and trying to get the loop done. but i am not sure how to
check for options (dropdown) and radio type's, if exist, select the checked or selected and put it in the array.
Is there a better way to construct it?
and when the loop is done, to pass the var for sending it in ajax?

var parameters = "";
var form = document.getElementById("someForm");
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].value) {
if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "hidden")
parameters = parameters + '&' + form.elements[i].name+'='+escape(form.elements[i].value);
if((form.elements[i].type == "radio" || form.elements[i].type == "checkbox") && form.elements[i].checked)
parameters = parameters + '&' + form.elements[i].name+'='+form.elements[i].value;
}
}
I generally use something like this, if I need to ajax a form.
Simply append parameters to the end of your ajax request.

I would take a look at the way jQuery does it. Specifically you will want to look at the serialize (line 6260), serializeArray (line 6264) and param (line 6784) methods.
According to this comparison of form serialization in different JavaScript libraries, jQuery's implementation adheres to the W3C specification better than the competition.

I agree in looking at jQuery, but maybe try implementing something yourself. You could get all inputs / textareas / selects within the form quite easily using jQuery:
// get all input fields, except buttons
var inputs = $("form input:not(:button)");
// get all dropdowns
var dropdowns = $("form select");
// get all text areas (i.e. "big" textboxes)
var textareas = $("form textarea");

I used something like this (I edited line 2 of Sheldon's solution):
var parameters = "";
var form = document.someForm;
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].value) {
if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "hidden")
parameters = parameters + '&' + form.elements[i].name+'='+escape(form.elements[i].value);
if((form.elements[i].type == "radio" || form.elements[i].type == "checkbox") && form.elements[i].checked)
parameters = parameters + '&' + form.elements[i].name+'='+form.elements[i].value;
}
}

Related

How to fix "required fields" in PDF form with Javascript

I tried to use JavaScript for a control mechanism inside a pdf form. There are many fields, checkboxes etc. some of them are required, some of them don't and some of the required only shows when you check a certain box.
My problem now is: some of the required fields are dropdown menus or option fields and the javascript don't show that they are "missing" when I click the button. If I erase the (f.value.length<1)) part it is showing all required fields but don't recognize the ones who are filled e.g. with a dropdown element, text or similiar 'cause the condition is missing.
I need a code which finds all required fields and sees if they are empty or filled with ANYTHING and a way to exclude some fields, cause some are only visible when a certain checkbox is activated or a way to include those fields only when the certain box is activated.
Thank you!
kontrollieren();
function kontrollieren() {
var feld;
feld = ""
for (var i = 0; i < this.numFields; i++) {
var fName = this.getNthFieldName(i);
var f = this.getField(fName);
if ((f.type != "button") && f.required && (f.value.length < 1)) {
feld = feld + fName + "\n";
}
}
if (feld == ""){
app.doc.print();
}
else {
app.alert("Bitte füllen sie vor dem Drucken alle Pflichtfelder aus.\nFehlende Felder:\n\n" + feld);
}
}
all of the inputs should have a name as well as a value field. You may need to identify the input (and thus validation method employed) this way.
In situations such as these, where there are multiple inputs, and multiple conditionals determining what's required, try to catch the false. I'd employ something similar to this:
for (var i = 0; i < this.numFields; i++) {
var fName = this.getNthFieldName(i);
var f = this.getField(fName);
if ((f.type != "button") && f.required) {
// For a Select Input
if (f.name === 'selectInputName') {
// Or whatever the 'default' value is that represents not selecting a value
if (f.value !== 'Select One') {
feld = feld + fName + '\n';
}
}
// For a checkbox
if (f.name === 'checkboxInputName' && f.checked) {
feld = feld + fName + '\n';
}
// For an input
if (f.name === 'textInputName' && f.length.value > 0) {
feld = feld + fName + '\n';
}
}
}
I'm not 100% how your structure works - getNthFieldName() && getField() are two functions I am not familiar with, but hopefully, the idea above is still relatable.

Adding to a url to tick a checkbox

I have a URL www.example.com/index.html
It has an element with an id of DARK_MODE.
It is a checkbox.
I want to add to the URL so that when it loads it automatically gets ticked.
I tried www.example.com/index.html?DARK_MODE=checked
This is not my website that i'm loading.
Am i doing this right?
Thanks.
Here is the solution that I propose. In order to check the checkbox, use, ?DARK_MODE=checked.
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location
.toString()
.replace(/^.*?\?/, '')
.replace(/#.*$/, '')
.split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
if($_GET['DARK_MODE'] === 'checked') document.getElementById('DARK_MODE').checked = true;
<input type="checkbox" id="DARK_MODE" />

Javascript validation on select input

I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating

Pdf.js: how to get input radio values?

I use pdf.js library to generate html5 page from pdf but some capabilities not working. I try to get value for input radio but still abortively:(
For example, in core.js script there are a few lines of code that take type of field:
var fieldType = getInheritableProperty(annotation, 'FT');
if (!isName(fieldType))
break;
item.fieldType = fieldType.name;
How I can get feild value?
I found the solution that work form me!
Add this code around line 260 of core.js file:
function setRadioButton(annotation, item) {
var ap = annotation.get('AP');
var nVal = ap.get('N');
var i = 0;
nVal.forEach(function(key, value){
i++;
if(i == 1 || i == 2) {
if(key != 'Off')
item.value = key;
}
});
}
And this code around line 370 of core.js file:
if (item.fieldType == 'Btn') {
if (item.flags & 32768) {
setRadioButton(annotation, item);
}
}
Also, if you want to get values from select input, you can use this code:
if(item.fieldType == 'Ch') {
item.value = annotation.get('Opt') || []; //return array of values
}

iterate through textboxes

I have text boxes where id for these boxes are from 1 to 20. These boxes are created in PHP for loop.
How can i check using javascript if these textboxes are empty. and throw an error on each box.
foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i">
}
Use jQuery?
$('input[type=text]').each(function(){if ($(this).val() == '') alert("Your Message Here");});
or, if there are other inputs you don't want to process:
$('[id^="q_"]').each(function(){if ($(this).val() == '') alert("Your Message Here");});
Without jQuery (and using jQuery would be easier):
foreach(i = 0, i<20, i++)
{
if (document.getElementById('q_' + i).length == 0) {
alert('box ' + i + 'is empty!');
}
}
document.getElementsById('q_'+i)[0].value.length > 0
in a for loop ought to roughly do it.
(though dropping jQuery into your project would probably be a better plan)
Then you could iterate over a class. i.e.
foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i" class="q">
}
and in your Javascript:
$("q").each(function(index,object){
if(object.value().length <= 0) alert('empty!');
});
Here is a basic form validation that might be what you're looking for
It uses an invisible error message that shows up when you leave an empty field after you push the button. It doesn't accept white spaces. You can validate it multiple times and it behaves as expected
Here's the jquery part:
$(document).ready(function() {
$("button").click(function()
{ $('span[id^=q_]').addClass("hidden");
$('input[id^=q_]').each(function()
{if ($(this).val().replace(/ /g,'') == '')
{ $("#"+$(this).attr('id')).removeClass("hidden");
}
});
});
});
html part:
<style>.hidden{display:none;}
.visible{display:block;}
</style>
<span id="q_1" class="hidden">Missing text</span>
<input type = "Text" id="q_1">
Not very pretty but it does the job

Categories