How do I pass form elements to a javascript validation function? - javascript

I have a form that lists users, and for each user there is a drop down menu (2 choices: waiting, finished) and a comments textbox. The drop down menus are each labeled "status-userid" and the comments textbox is labeled "comments-userid" ... so for user 92, the fields in his row are labeled status-92 and comments-92.
I need to validate the form in the following way:
If the value of the status is "finished", I have to make sure that the user entered comments to correspond with that specific drop down menu.
So far, I have:
function validate_form () {
valid = true;
/*here's where i need to loop through all form elements */
if ( document.demerits.status-92.value == "finished" &&
document.demerits.comments-92.value == "")
{
alert ( "Comments are required!" );
valid = false;
}
return valid;
}
How do I loop through all of the status-userid elements in the form array?! Or is there another way to do this?

This should do it in raw Javascript (no framework).
var form = document.demerits;
for (var i = 1; i <= 100; i++)
{
if (form["status-" + i.toString()].value == "finished" &&
form["comments-" + i.toString()].value == "")
{
// enable visibility of element next to comments indicating validation problem
valid = false;
}
}
Using alerts would be bad though.

You'll need a collection of the dropdowns in your form. This can be acquired by using getElementsByTagName.
var dropdowns = document.demerits.getElementsByTagName("select");
for (var i = 0; i < dropdowns.length; i++)
{
// You can now reference the individual dropdown with dropdowns[i]
}

Related

JavaScript waitFunction

I’m facing a small issue in JavaScript. I need to to make a code stop and do nothing for a while. I tried setTimeout, but it only scheludes the function, continues in executing the code and then comes back. I really need to wait for the user to put some value in the input field and then press the button. The sleep function on the beginning of my code works, but the code somehow stops showing my html input form and button. I can’t figure out why. I also can’t use onclick attribute on the submit button, because of the same problem. Does someone know what can be the problem here??
var returning = 0; // variable for deciding which part of function to use
function sleep(milliseconds) { // sleep method found here on stackoverflow
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function acceptValue(){
// show an input field with button next to it
if (returning == 0) {
var co = document.createElement("input"); // show input field and set attributes
var kam = document.getElementById("telo");
var indexId = 0;
while(document.getElementById("pole" + indexId) != null) {
indexId++; // look for closest unused id name
}
co.setAttribute("id", "pole" + indexId);
kam.appendChild(co);
var co1 = document.createElement("input");
var kam1 = document.getElementById("telo");
var indexId1 = 0;
while(document.getElementById("cudlik" + indexId1) != null) {
indexId1++; // look for closest unused id name
}
co1.setAttribute("id", "cudlik" + indexId1); // show button and set attributes
co1.setAttribute("type", "submit");
co1.setAttribute("value", ">");
co1.setAttribute("onclick", "vraceni()");
kam1.appendChild(co1);
console.log(document);
document.getElementById("telo").appendChild(document.createElement("br"));
returning = 1;
acceptValue();
} else if (vrat == 1) {
sleep(500);
acceptValue();
}
} else {
var indexPole = 0;
while (document.getElementById("pole" + indexPole) != null) {
indexPole++;
}
vrat = 0;
return document.getElementById("pole" + (indexPole - 1)).value; // return the value from last shown input field
}
}
function returnFunc() {
vrat = 2; // called from html button
}
Thanks,
Adam Hendrych
I think the feature you are attempting to create here may need some re-architecting. It feels very strange to have all these while loops and sleep tricks in place.
What you describe wanting this code to do is basically the default behavior of how inputs and buttons work. A simple form containing an input and submit button, with an onsubmit handler on the form, should meet the "accept input and fire an action when the button is pressed" requirement.
An example

Validate all or none text fields in Kendo & dynamically remove messages

For the code below it looks for an empty field in the 4 required fields if the user enters the address/city/state/zip field. Then it loops to check if any of them are empty. If all 4 are empty, then validation passes. If All of them contain data, then it should pass. The only time it should fail is if 1-3 of them are empty.
var validator = $("#AddressInfoForm").kendoValidator(
{
rules: {
PayeeRequired: function (input) {
if (input.is("[name=Address]") || input.is("[name=City]") || input.is("[name=State]") || input.is("[name=Zip]")) {
var fieldsBlank = 0;
var requiredFields = ["Address", "City", "State", "Zip"];
for (var i = 0; i < requiredFields.length; i++) {
var val = $('#' + requiredFields[i]);
if (val.val() == "") {
fieldsBlank += 1;
}
}
if (fieldsBlank > 0 && fieldsBlank < 4 && input.val() == "")
input.addClass("inputfields-validation-error");
fieldsBlank = 0;
return false;
}
input.removeClass("inputfields-validation-error");
return true;
}
}
},
}
).data("kendoValidator");
The issue I'm having with this is that...
The previous validation messages do not disappear. They only disappear once I click into each input box. It should be checking dynamically across the board since all 4 fields are linked. This means if 3 fields are empty except one, then there should be errors for those 3 fields. Once I clear the 4th field, then all of those errors should hide. Unfortunately it only hides for the last field that I input into and then I need to individually click into each field.
Working code expectant...
Overall I am looking for improve/correct my code so that
Show the error message for the blank fields when more than zero and less than 4 are blank.
Dynamically update so that when I clear all the fields, it clears all the error messages. When I fill one, then the other 3 blank fields display errors.
No errors when all 4 are filled.
edit--------
utilizing
$("#Address, #City, #State, #Zip").on("change", function () {
isModified = true;
validator.validate();
});
Seems to work how I want; however, validator.validate() sets off the validation errors for all the other fields in my form. I only want the validation set off for the 4 fields Address, City, State, and Zip. Any ideas?
$("#Address, #City, #State, #Zip").on("change", function () {
validator.validateInput($("input[name=Address]"));
validator.validateInput($("input[name=City]"));
validator.validateInput($("input[name=State]"));
validator.validateInput($("input[name=Zip]"));
});
Seems to work well. Let me know if there's a better way to do this!

Set value/text to dropdown list

I am using the following jquery postcode lookup and I am trying to push values and hard code the process in javascript.
I am using the following to give the postcode textbox a valid postcode, and then forcing the button click to find the addresses.
document.getElementById("idpc_input").value = "LL17 0PN";
document.getElementById('idpc_button').click();
This so far works, after this a dropdownlist appears with the id of 'idpc_dropdown', I am trying to (in javascript or jquery) select an option
Here is what I have done but it does not work
var select = document.getElementById("idpc_dropdown");
document.getElementById("idpc_dropdown").text = '2 Elwy Cottages Heol Esgob';
And also:
var desiredValue = "2 Elwy Cottages Heol Esgob"
var el = document.getElementById("idpc_dropdown");
for(var i=0; i<el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.selectedIndex = i;
break;
}
}
UPDATE:
Let me explain the process and order, 1- Type in postcode and press the button to find my address 2- a dropdownlist then renders and appears .. I Think this is why it is not working for my desired dropdownlist as its not loaded when the page is loaded, it is when the button has been pressed
Provided that i is the same as the index of the item you wish to select, I'd set the dropdown's value attribute to that index:
let el = document.getElementById("idpc_dropdown");
for(let i = 1; i <= el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.value = i; // here
break;
}
}

Limiting the number of checkboxes selected by user

i have a page on there.i have number of check boxes.i want user to select on three not more than that and one check box has the value "NOT interested ",if user click on this all other check box must has to disabled.for that i tried javascript.
this is what i tried
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.form1.user[portal_choice].length; i++) {
if (document.form1.user[portal_choice][i].checked) {
total = total + 1;
}
if (total > 3) {
alert("Please Select only three")
document.form1.user[portal_choice][j].checked = false;
return false;
}
}
}
i getting error in the portal_choice variable.That is mapped with the database column name and user is my table name.
help me to do that and suggest me to disabling the checkbox when user click on "NOT INTERSTED".and its not rail 3.0
thanks pal for consideration.........
Using this syntax document.form1.user[portal_choice], you are telling Javascript that you want the form called 'form1' and from that form, get the elements called 'user', and look at the one with an index that is contained in the (javascript) variable 'portal_choice'. That variable is not defined in your function.
I am not familiar with Ruby, but from some quick reading, it looks like you can refer to Ruby variables directly in html, but not in Javascript. I think you have to wrap it with <%= %> like so:
document.form1.user[<%= portal_choice %>].length
However, I don't see why you would use a Ruby variable here. You just want to iterate through all of the checkboxes, right? I don't think checkbox elements are ever 2-dimensional arrays, as in
document.form1.user[portal_choice][i]
I think you really just want to do this:
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.form1.user.length; i++) {
if (document.form1.user[i].checked) {
total = total + 1;
}
if (total > 3) {
alert("Please Select only three")
document.form1.user[j].checked = false;
return false;
}
}
}
Check this fiddle

Limit the number of children in a form using Javascript

I am trying to limit the number of additional form input fields that a user can add dynamically to a file upload form to just 3. The form is loaded with one static input field and through javascript can add additional fields with an add button or remove additional form input fields with a remove button. Below is the html in it's static form.
<fieldset>
<legend>Upload your images</legend>
<ol id="add_images">
<li>
<input type="file" class="input" name="files[]" />
</li>
</ol>
<input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/>
</fieldset>
With javascript I would like to create a function where the number of child elements are counted and if the number is equal to three then the "Add Another Image" button becomes disabled. In addition, if there are three elements in the form the user - with the remove button - removes a child then the "Add Another Image" button becomes enabled again.
I think I'm may be missing some crucial lines of code. The below javascript code only allows me to add one additional input field before the Add Another Image button becomes disabled. Removing this field with the remove file button removes the field but the Add Another Image button is still disabled. Below is where I'm currently at with the javascript.
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
}
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = nodelist.length;
for(i = 0; i < count; i++) {
if (nodelist[i] ==3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
}
}
Oh, OK, I've tested out the code now and see a couple of problems:
You're counting the number of child elements but this includes the text elements so there's actually one for the <li> and one for the text within it.
You've enclosed the true/false setting for the disabled property in quotes but it doesn't work and always set's it to false.
The remove button doesn't re-enable the add button.
I found this to work:
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
toggleButton();
}
toggleButton();
}
function toggleButton() {
var form = document.getElementById('add_images');
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = 0;
for(i = 0; i < nodelist.length; i++) {
if(nodelist[i].nodeType == 1) {
count++;
}
}
if (count >= 3) {
document.getElementById("addFile").disabled = true;
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = false;
}
}
I would suggest a slightly different approach. Create all three file input fields statically and provide a clear button. If the user chooses to leave it empty they can. If that is not elegant use your "Remove" to simply hide the field (CSS style display: none;).
I'm not sure why you're using the for loop? Shouldn't it be like this:
var nodelist = form.childNodes;
if (nodelist.length >= 3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
The last part of that function is a bit strange. Technically, when adding fields, you should only be disabling the button (i.e. you could never enable the button by adding fields). I would suggest removing the for loop and going with:
var count = form.getElementsByTagName("li").length;
if(count == 3)
document.getElementById("addFile").disabled = true;
The reason the add field button is still disabled when you remove an item is because you don't re-enable the add field button when you click remove. Try this for the remove button click handler:
rb.onclick = function () {
form.removeChild(this.parentNode);
document.getElementById("addFile").disabled = false;
}

Categories