Javascript - verify the values of fields with dynamic names - javascript

I have a set of text fields qty with dynamic names: like qty541 ; qty542 ; qty957
formed by the word: "qty" and the product id
How can I verify if all my qty fields are empty or not with Javascript ?
Thanks a lot.

The easiest way is to use a javascript framework like JQuery, Protoype, etc. With this framework you can create a search pattern in reg expr manner. If you unable to use one, it does need more work:
One way:
var formObj = document.forms[0]; //as an example
var fields = formObj.getElementsByTagName("input");
for (i=0; i < fields.length, i++)
{
if (fiedls[i].name.indexOf("qty") > 1)
{
//do something
}
}

You can loop through the elements of the form:
var form = document.getElementById('theForm');
var index;
var field;
for (index = 0; index < form.elements.length; ++index) {
field = form.elements[index];
if (field.name.substring(0, 3) === "qty") {
// Check field.value here
}
}
Live example
The above assumes the form has an id, but however you get access to the form element, the rest follows.
Off-topic: A lot of this stuff is made much simpler by the utility functions available in various JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others. They also smooth over browser differences (or outright browser bugs), allowing you to focus on the job in hand rather than worrying about browser inconsistencies.

Using:
<p>
<input type="text" name="qty3232" value="43"/><br/>
<input type="text" name="qty5532" value="as"/><br/>
<input type="text" name="qty5521" value=""/><br/>
<input type="text" name="qty3526" value="34"/>
</p>
<br/>
<h3>Log</h3>
<pre id="log"></pre>
Javascript (no jQuery):
var inputs = document.getElementsByTagName('input');
var log = document.getElementById('log');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'text' && inputs[i].name.substring(0,3) == 'qty') {
if (inputs[i].value == '') {
log.innerHTML += inputs[i].name + " value empty.\n";
} else {
log.innerHTML += inputs[i].name + " value not empty.\n";
}
}
}
http://jsfiddle.net/jxmMW/
This is much easier using a selector in jQuery, though.
var log = $('#log');
$('input[name^="qty"]').each(function(){
if (this.value == '') {
log[0].innerHTML += this.name + " value empty.\n";
} else {
log[0].innerHTML += this.name + " value not empty.\n";
}
});
http://jsfiddle.net/jxmMW/1/

Plain JS:
For example use class="quantity" on all fields and use getElementsByClassName - which almost takes us into jQuery mode
window.onbeforeunload=function() {
var elems = document.getElementsByClassName("quantity"); // needs help in some browsers
for (var i=0,n=elems.length;i<n;i++) {
if (elems[i].value!="") {
return "You have filled in a quantity");
}
}
}
window.onload=function() {
document.forms[0].onsubmit=validate;
}
function validate() {
var elems = document.getElementsByClassName("quantity");
for (var i=0,n=elems.length;i<n;i++) {
if (elems[i].value=="") {
alert("Please fill in a quantity");
elems[i].focus();
return false;
}
}
}
standard method:
function validate() {
var elem;
for (var i=0,n=this.elements.length;i<n;i++) {
elem = this.elements[i];
if (elem.name && elem.name.indexOf("qty")===0) {
if (elem.value=="") {
alert("Please fill in a quantity");
elem.focus();
return false;
}
}
}
return true; // allow submit
}

Related

Validating different types of form inputs with criterias

I want to get the answers to a form upon submission and parse them to JSON.
This works quite good but I want some validation before sending the data.
I tried a lot of variations of the snippet down below but am still stuck.
Steps:
Prevent default event on "send"
Get Form
Iterate through the elements of the form
Eliminate empty items and their value
If checkbox is checked: value = true
Store correct items in data
Return data
Somehow I can't get to work steps 4 and 5 work at the same time, every time I get one of them to work I screw over the other one.
In this snippet, the checkbox works as intented but the textfield doesn't:
If anybody can point me in the right direction with the if/else statements or something like that it would be greatly appreciated.
document.addEventListener('DOMContentLoaded', function(){
var data = {};
var formToJSON = function formToJSON(form) {
var data = {};
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value =="") {
continue;
}
else {
if (item.checked == false) {
data[item.name] = false;
}
else {
data[item.name] = item.value;
}
}
}
return data; };
var dataContainer = document.getElementsByClassName('results__display')[0];
form = document.getElementById('formular').querySelectorAll('input,select,textarea');
butt = document.getElementById('knopfabsenden');
butt.addEventListener('click', function (event) {
event.preventDefault();
handleFormSubmit(form = form);
});
var handleFormSubmit = function handleFormSubmit(event) {
var data = formToJSON(form);
dataContainer.textContent = JSON.stringify(data, null, " ");
}
}, false);
<div id="formular">
<label class="formular__label" for="machineName">Textfield Test</label>
<input class="formular__input formular__input--text" id="machineNumber" name="machineNumber" type="text"/>
<br>
<input class="formular__input formular__input--checkbox" id="checkTest" name="checkTest" type="checkbox" value="true"/>
<label class="formular__label formular__label--checkbox" for="checkTest">Checkbox Test</label>
<br>
<button class="formular__button" id="knopfabsenden" type="submit">Submit</button>
</div>
<div class="results">
<h2 class="results__heading">Form Data</h2>
<pre class="results__display-wrapper"><code class="results__display"></code></pre>
</div>
The problem is .checked will always be false if it doesn't exist. So the text field gets the value false.
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value ==="") {
continue;
}
else {
if (item.type === "text") {
data[item.name] = item.value;
}
else if (item.type === "checkbox"){
data[item.name] = item.checked;
}
}
}
In this code snippet I check the type of the input and handle it accordingly. also notice I use the === operator and not the == operator as a best practice (Difference between == and === in JavaScript)

How do I (1) Create A Randomly Generated Email in Javascript (2) Auto fill a form with it

and thanks for taking time to at least pity my lack of knowledge.
I have a wordpress installation (stay with me..) that has a plugin where you enter some information including an email, in order to add, in this instance a new booking (crm type thing). This is done in the back end by admin. On some occasions, the client doesn't have an email address and as a hacky workaround i'd like the system to just generate a random email address in the box whenever it's left empty.
Much of the plugin is in Javascript and i think i've found the validation function where my snippet might need 'injecting':
(1)
I'm fairly comfortable with PHP, and have written something that generates a random email (which will only be used internally)
//Random email address generator
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$randomString .= "#mysite.co.uk";
return $randomString;
}
(yes I know, there are a million neater ways to accomplish the above)
(2) I think i've found the bit of javascript that validates the email input and was just hoping this may be the chunk of code i'd need to look at in order to generate a random email, if nothing else was entered.
function sln_validateBooking() {
var $ = jQuery;
$('.sln-invalid').removeClass('sln-invalid');
$('.sln-error').remove();
var hasErrors = false;
var toValidate = [
'#_sln_booking_service_select'
];
var fields = $('#salon-step-date').attr('data-required_user_fields').split(',');
$.each(fields, function(k, val) {
toValidate.push('#_sln_booking_' + val);
});
$.each(toValidate, function (k, val) {
if (val == '#_sln_booking_phone' && !$('[name=_sln_booking_createuser]').is(':checked')) {
return;
} else if (val == '#_sln_booking_email') {
if (!$('[name=_sln_booking_createuser]').is(':checked') && !$(val).val()) {
return;
} else if (!sln_validateEmail($(val).val())) {
$(val).addClass('sln-invalid').parent().append('<div class="sln-error error">This field is not a valid email</div>');
if (!hasErrors) $(val).focus();
hasErrors = true;
}
} else if (val == '#_sln_booking_service_select') {
if (!$('[name=_sln_booking\\[services\\]\\[\\]]').size()) {
$(val).addClass('sln-invalid').parent().append('<div class="sln-error error">This field is required</div>');
if (!hasErrors) $(val).focus();
hasErrors = true;
}
} else if (!$(val).val()) {
$(val).addClass('sln-invalid').parent().append('<div class="sln-error error">This field is required</div>');
if (!hasErrors) $(val).focus();
hasErrors = true;
}
});
return !hasErrors;
}
What would be great to know is a) if i should just shoot myself in the face and never go near a line of code again and also b) if there is a neat solution to this that I may forever be in your debt for solving.
UPDATE:
I've decided it would probably be better to pass this randomly generated email address to the empty field via a metabox, and not to hack at the plugin's code (which would only get overwritten)..
However.. I get 'uncaught referenceError : rand is not defined at HTMLinputelement.onclick for both functions if i do something like this:
<input type="text" id="txt_name" placeholder="click to generate" value="" />
<br/>
<input type="button" class="button button-primary button-large" id="btn_Gen"
onclick="rand();" value="Generate" />
<br/>
<input type="button" class="button button-primary button-large" id="btn_Run"
onclick="fn_copy();" value="Autofill" />
<br/>
<script>
function rand() {
document.getElementById("txt_name").value = generateRandStr();
}
function generateRandStr() {
var candidates = "ABCDEFGHIJKLMNOPQRSTUVWXY123456789";
var randomemail = "",
rand;
for (var i = 0; i < 1; i++) {
for (var j = 0; j < 8; j++) {
rand = Math.floor(Math.random() * candidates.length);
randomemail += candidates.charAt(rand);
}
randomemail += "#blahblah.co.uk";
}
return randomemail;
}
//working
function fn_copy() {
var temp = document.getElementById("txt_name").value;
if (temp != "") {
document.getElementById("_sln_booking_email").value = temp;
} else
alert("Text is Empty");
}
</script>
HELP!
After this line
} else if (!sln_validateEmail($(val).val())) {
remove all the code that notifies the user of invalid input and set the value to your random email.
} else if (!sln_validateEmail($(val).val())) {
$(val).val(Math.random().toString(36).substring(5) + "#mysite.co.uk")
}
I'm not sure you want to lean on that Math.random call to make billions of unique emails but it might get you by.

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Override <input type="file"> value property

It's possible to override value property in tag? My code in JavaScript
var element = document.createElement('input');
element.type = 'FILE';
element.__defineGetter__('value',function(){ return 'ololo'; });
alert(element.value);
It show empty string. Also I try override 'value' with prototype
function BPFILEINPUT(value)
{
this.value = value;
}
BPFILEINPUT.prototype = element;
var myFileInput = new BPFILEINPUT('ololo');
alert(myFileInput.value);
It work, but crash on
form.appendChild(myFileInput);
I try pass test for upload form on 4shared.com
var uplElems = aUploadForm.elements;
for (var i = 0; i < uplElems.length; i++) {
var currentUploadElement = uplElems[i]
if (currentUploadElement.type == 'file') {
if (currentUploadElement.value == '') {
// skip
} else {
if (!checkFileLength(currentUploadElement)) {
return false;
}
filesToUpload += getNumberOfSelectedFiles(currentUploadElement);
}
}
}
if (filesToUpload < 1) {
alert('You didn\'t select any file to upload yet.');
return false;
}
UPDATE
I use UIWebView.
AFAIK, you can't set the value of <input type="file"> programmatically because of security reasons. A user has to explicitly click on it to set its value.

More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script...
$("#send").click(function() {
var fullname = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
if (fullname == ""){
$("input#fullname").css("background","#d02624");
$("input#fullname").css("color","#121212");
}else{
$("input#fullname").css("background","#121212");
$("input#fullname").css("color","#5c5c5c");
}
if (email == ""){
$("input#email").css("background","#d02624");
$("input#email").css("color","#121212");
}else{
$("input#email").css("background","#121212");
$("input#email").css("color","#5c5c5c");
}
if (subject == ""){
$("input#subject").css("background","#d02624");
$("input#subject").css("color","#121212");
}else{
$("input#subject").css("background","#121212");
$("input#subject").css("color","#5c5c5c");
}
if (message == ""){
$("textarea#message").css("background","#d02624");
$("textarea#message").css("color","#121212");
}else{
$("textarea#message").css("background","#121212");
$("textarea#message").css("color","#5c5c5c");
}
if (name && email && subject && message != ""){
alert("YAY");
}
});
How can i write this more efficiently and make the alert show if all the fields are filled out, thanks.
$("#send").click(function() {
var failed = false;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
var item = $(this);
if (item.val()) {
item.css("background","#121212").css("color","#5c5c5c");
} else {
item.css("background","#d02624").css("color","#121212");
failed = true;
}
});
if (failed){
alert("YAY");
}
});
glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation.
Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass()
Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required").
Then you do something like this:
var foundEmpty = false;
$(".required").each(function()
{
if($(this).val())
{
foundEmpty=true;
$(this).style("background-color", "red");
}
});
if(foundEmpty)
{
alert("One or more fields require a value.");
}
Giving them a common class, define classes to apply the styles, and do this:
JS
$("#send").click(function() {
$('.validate').attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( $('.invalid').length === 0 ) {
alert('YAY');
}
});
CSS
.valid {
background:#121212;
color:#5c5c5c
}
.invalid {
background:#d02624;
color:#121212;
}
HTML
<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">
JSFIDDLE DEMO
A little bit more efficient approach:
var validate = $('.validate');
$("#send").click(function() {
validate.attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( validate.filter('.invalid').length === 0 ) {
alert('YAY');
}
});
You can use jQuery to iterate over each object and get their values. Depending on your form, this code will change, but it's to give you an example. I'm probably missing a couple of brackets here and there but the concept is there.
var objectName=$(this).attr('id');
$('#formId').children().each(
function(){
if ($(this).value == ""){
$(this).css("background","#d02624");
$(this).css("color","#121212");
$error[objectName]='true';
}else{
$(this).css("background","#121212");
$(this).css("color","#5c5c5c");
$error[objectName]='false';
}
}
);
$.each(error, function(key, value){
if (value=='false'){
alert (key + 'is empty');
}
});
I would probably divide part of this up into my css file. If any of the fields are empty add a class like "empty" to the object, if not, remove it. Then in your css file you can add some descriptors like:
input#fullname,
input#email {
...
}
input#fullname.empty,
input#email.empty {
...
}
You can use jQuery addClass() and removeClass().
You can then add a loop as follows:
var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
var value = $(inputs[0]).val();
if (value.length > 0) {
$(inputs[i]).removeClass("empty");
} else {
complete = false;
$(inputs[i]).addClass("empty");
}
}
if (complete) {
}
EDIT:
There you go, fixed it for you.

Categories

Resources