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.
Related
I'm building a tabbed for using a mixture of JavaScript and CSS. So far I have validation on my text inputs that ensure a user can't progress unless data has been input.
I have got it working so that my script detected unchecked radios, but the problem is that I want the user to only select one. At the moment even when one gets selected the script won't let you progress because it's seeing the other three as unchecked. How could I add a rule to look at the radios and set valid = true if one is selected - if more or less than 1 then fail?
my function:
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].type === "text") {
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].classList.add('invalid');
// and set the current valid status to false:
valid = false;
} else if (!y[i].value == "") {
y[i].classList.remove('invalid');
valid = true;
}
}
if (y[i].type === 'radio') {
//y[i].classList.remove('invalid');
//valid = true;
if (!y[i].checked) {
y[i].classList.add('invalid');
valid = false;
} else {
y[i].classList.remove('invalid');
valid = true;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Do I need to split the validation down into further functions to separate validating different field types?
I think that radio buttons are the way to go. Especially from a UI point of view. Why would you let the user pick more than one item only to tell them later they can't?
Having said that, you can do what you're trying to do with something like this:
function validateForm() {
var checkBoxHolders = document.querySelectorAll(".checkboxholder");
var valid = true;
for (var i = 0; i < checkBoxHolders.length; i++) {
var numChecked = checkBoxHolders[i].querySelectorAll("input[type='checkbox']:checked").length;
if (numChecked === 1) {
checkBoxHolders[i].classList.remove('invalid');
} else {
checkBoxHolders[i].classList.add('invalid');
}
valid = valid && numChecked === 1;
}
document.getElementById('valid').innerHTML = 'I am valid: ' + valid;
}
.invalid {
background-color: orange;
}
<input type="text" id='foo'>
<input type="text" id='bar'>
<div class='checkboxholder'>
First group
<input type="checkbox" id='check1'>
<input type="checkbox" id='check2'>
</div>
<div class='checkboxholder'>
Second group
<input type="checkbox" id='check3'>
<input type="checkbox" id='check4'>
</div>
<button type='button' onclick='validateForm()'>Validate me</button>
<div id='valid'>
</div>
With jQuery, it'd be something like:
if (jQuery('input[name=RadiosGroupName]:checked').length === 0) {
valid = false;
}
After dynamic table creation, I created a jQuery function that allows the user to copy chosen entries' input values into a staging area via buttons. The values are cloned successfully, but after each button click, the parsley validation error message
"This value should be a valid integer."
appears for every input in the table. Why is the validation perceiving an invalid number entered into the input, and how can this error message be avoided?
Also, there is a button that copies a group of inputs to a staging area, and after that click, the parsley validation error message does not appear. Can anyone see why the single copy would generate the validation message and the group copy would not? The only differences I see are that the validation-triggering code: 1) is called when a class member is clicked as opposed to an ID; and 2) uses the .closest(), .children(), and .eq() methods to navigate the table as opposed to using only IDs to reference table elements. Thanks very much in advance!
The dynamic table row creation in a loop after an AJAX call:
var row = $('<tr></tr>');
var idCell = $('<td></td>').append($('<input type="submit" class="btn btn-info contractToOffer" value="Add To Contracts">'));
row.append(idCell);
idCell = $('<td class="text-center" id="contractID' + data[i].ContractID + '"></td>').append(data[i].ContractID);
row.append(idCell);
idCell = $('<td class="text-center"></td>').append(Number(Number(data[i].ContractPrice) + Number(data[i].ContractMargin)).toFixed(2));
row.append(idCell);
idCell = $('<td class="text-center"><input id="contractValue' + data[i].ContractID + '" value="' + Number(Number(data[i].ContractPrice) + Number(data[i].ContractMargin)).toFixed(2) + '" step="0.01" class="contractInput" type="number" name="quantity" min="1" max="50000"></td>').append();
row.append(idCell);
Moving function that generates validation message:
$("#contractPanel").on("click", ".contractToOffer", function () {
var $offerContractOne = $("#OfferContract1"),//In staging area
$offerPriceOne = $(".price1"),//Also in staging area
$movingContract = 0,
$movingPrice = 0.00,
$oCells = $(this).closest('tr').children('td');
$movingContract = $oCells.eq(1).text();
$movingPrice = $("#contractValue" + $movingTerm.toString()).val();
$offerContractOne.val($movingTerm);//Staging area
$offerPriceOne.text($movingPrice);//Also staging area
});
And finally, the group copying that doesn't generate any message via a "standardOffers" button, which I would also like the single-copy code to do:
$("#contractPanel").on("click", "#standardOffers", function () {
var $oContractOne = $("#OfferContract1"),
$oPriceOne = $(".price1"),
$oContractTwo = $("#OfferContract2"),
$oPriceTwo = $(".price2"),
$oContractThree = $("#OfferContract3"),
$oPriceThree = $(".price3"),
$oContractFour = $("#OfferContract4"),
$oPriceFour = $(".price4"),
$oContractFive = $("#OfferContract5"),
$oPriceFive = $(".price5"),
//The preceding are in the staging area
$standardPrice = 0.00
for (var i = 1; i < 6; i = i + 1) {
if ($("#contractID" + i).length > 0) {
$standardPrice = $("#contractValue" + i.toString()).val();
if (i == 1) {
$oContractOne.val(i.toString());
$oPriceOne.text($standardPrice);
}
else if (i == 2) {
$oContractTwo.val(i.toString());
$oPriceTwo.text($standardPrice);
}
else if (i == 3) {
$oContractThree.val(i.toString());
$oPriceThree.text($standardPrice);
}
else if (i == 4) {
$oContractFour.val(i.toString());
$oPriceFour.text($standardPrice);
}
else {
$oContractFive.val(i.toString());
$oPriceFive.text($standardPrice);
}
}
}
});
Building on top of my comment:
You have 2 options:
event.preventDefault();
this will:
Cancels the event if it is cancelable, without stopping further propagation of the event.
Source
2nd Option:
event.stopPropagation();
this will:
Prevents further propagation of the current event in the capturing and bubbling phases.
Source
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
The following function loops through form elements to validate they've been filled in. The bestresult element is optional and if there's no user input, value of 0 should be inserted into to the form element. When I submit the form, fields with empty elements are submitted to the server instead of alerting user to provide values. Any thoughts?
function validateForm()
{
//Validates that form elements are not empty
for(var i=0; i < document.results.elements.length; i++)
{
if(document.results.elements[i].value == null ||
document.results.elements[i].value == "")
{
if(document.results.elements[i] == document.results.besttime)
{
document.results.elements[i].value = 0;
}else
{
alert("Error " + document.results.elements[i].getAttribute("name") + " must be given a value");
return false;
}
}
}
The function itself is fine. I've discovered there's been a problem with a regular expression which is not included in the code snippet
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;
}
}