JavaScript For Loop Round Form Input Fields - javascript

I'm currently working on creating an expenses form and am writing a function to validate the entered data.
I allow for 6 expense amounts to be entered and a description on each and onClick of the submit button I am trying to write a for loop that will loop round the amount fields, check if they are numeric and, if they are, then check to ensure a description has been entered.
The form basically looks like:
<form action="##" name="myForm" id="myForm" method="post">
<input type="text" name="otherExpenseDesc1" id="otherExpenseDesc1">
<input type="text" name="otherExpenseAmount1" id="otherExpenseAmount1">
<input type="text" name="otherExpenseDesc2" id="otherExpenseDesc2">
<input type="text" name="otherExpenseAmount2" id="otherExpenseAmount2">
<input type="text" name="otherExpenseDesc3" id="otherExpenseDesc3">
<input type="text" name="otherExpenseAmount3" id="otherExpenseAmount3">
<input type="text" name="otherExpenseDesc4" id="otherExpenseDesc4">
<input type="text" name="otherExpenseAmount4" id="otherExpenseAmount4">
<input type="text" name="otherExpenseDesc5" id="otherExpenseDesc5">
<input type="text" name="otherExpenseAmount5" id="otherExpenseAmount5">
<input type="text" name="otherExpenseDesc6" id="otherExpenseDesc6">
<input type="text" name="otherExpenseAmount6" id="otherExpenseAmount6">
<input type="submit" name="formSubmitBtn" value="SUBMIT" onClick="checkForm();">
</form>
And the javascript I have at the moment is:
function checkForm() {
var errMsg = "";
var otherExpense1 = document.getElementById('otherExpenseAmount1').value;
var otherExpenseDesc1 = document.getElementById('otherExpenseDesc1').value;
var otherExpense2 = document.getElementById('otherExpenseAmount2').value;
var otherExpenseDesc2 = document.getElementById('otherExpenseDesc2').value;
var otherExpense3 = document.getElementById('otherExpenseAmount3').value;
var otherExpenseDesc3 = document.getElementById('otherExpenseDesc3').value;
var otherExpense4 = document.getElementById('otherExpenseAmount4').value;
var otherExpenseDesc4 = document.getElementById('otherExpenseDesc4').value;
var otherExpense5 = document.getElementById('otherExpenseAmount5').value;
var otherExpenseDesc5 = document.getElementById('otherExpenseDesc5').value;
var otherExpense6 = document.getElementById('otherExpenseAmount6').value;
var otherExpenseDesc6 = document.getElementById('otherExpenseDesc6').value;
for (i=1; i<7; i++) {
expenseNo = 'otherExpense' + i;
expenseDescNo = 'otherExpenseDesc' + i;
if (expenseNo != "") {
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
showDialog('alert', 'OK', '', errMsg, '');
}
}
When I'm submitting the form with valuesin a couple of the fields it still displays an alert for each otherExpenseAmount item saying that it is not numeric, although it is, and the border style doesn't change.
Any idea where I'm going wrong?

You're trying to access a variable with a string. You should change your code to utilise arrays, something like this:
jsFiddle
function checkForm() {
var errMsg = "";
var otherExpense = [];
otherExpense.push(document.getElementById('otherExpenseAmount1').value);
otherExpense.push(document.getElementById('otherExpenseAmount2').value);
otherExpense.push(document.getElementById('otherExpenseAmount3').value);
otherExpense.push(document.getElementById('otherExpenseAmount4').value);
otherExpense.push(document.getElementById('otherExpenseAmount5').value);
otherExpense.push(document.getElementById('otherExpenseAmount6').value);
// 0-based index for arrays
for (i=0; i<6; i++) {
if (otherExpense[i] != "") {
if (isNaN(otherExpense[i])) {
alert('otherExpense ' + (i + 1) + ' is not a number (=' + otherExpense[i] + ')');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
} else {
alert('otherExpenseAmount' + (i + 1) + ' is a number');
document.getElementById('otherExpenseAmount' + (i + 1)).style.border = '2px sold #990000';
}
}
}
if (errMsg != "") {
alert(errMsg);
//showDialog('alert', 'OK', '', errMsg, '');
}
return false;
}

Your problem is on these lines; you're setting the border to be the same, regardless of the condition (easy mistake to make).
if (isNaN(expenseNo)) {
alert(expenseNo + ' is not a number');
errMsg = errMsg + 'The amount must be a number.<br />';
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
} else {
alert('otherExpenseAmount' + i + ' is a number');
document.getElementById('otherExpenseAmount' + i).style.border = '2px sold #990000';
// -----------------------------------------------------------------------------^^^^^^
}
Suggestion
I hate to be that guy.
Have you considered adopting jQuery? It's perfectly designed for tasks such as this.
Utilising methods such as filter and simple selectors, it's easy to determine whether all inputs fulfil your requirements. Here's an example:
// select all inputs with a class of "number"
// then filter those inputs, selecting only those where the value is "not a number"
// if there is a length, i.e. more than 0 were found, alert a message
if ($('input.number').filter(function() { return isNaN(this.value); }).length) {
alert('Please ensure all numbers are valid');
}
This would obviously require you to make small amendments to your HTML, by adding the number class to the required elements, but it's a small sacrifice to make.
jsFiddle demo

Related

how to get the values from input fields dynamically

i have a page in my website that has a form that conatains inputs fields, i also have a button that creates more input fields incase the user needs to inputs more things. the problem now is that if the user makes a mistake and creates inputs feilds that he/she doe not need he can remove them but this creates a problem when inserting the value of the input fields in the database. i am using a for loop to get all the value of the input fields by id eg. id1, id2, id3 etc, but if the user removes one of the inputs field for example id2, i cant get id3 becuase the for loop will still run normally from 1 too the end and will not skip 2.
here is the code to create more input feilds:
let counter = 1;
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
// new_section.style.display = "flex";
new_section.insertAdjacentHTML('beforeend',
` <div class="lowerlayer2" id="close${counter}">
<button id="delete" onclick="deleteme(${counter})"><i class="fa fa-minus"></i></button>
<input type="text" placeholder="Word Type" id="wtype${counter}" />
<input type="text" placeholder="Synonym" id="syn${counter}" />
<input type="text" placeholder="Antonyms" id="anty${counter}" />
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`
);
counter++;
});
here is the code to delete the input feilds:
function deleteme(id) {
document.getElementById(`close${id}`).style.display="none";
document.getElementById(`close${id}`).innerHTML="";
counter--
}
here is the code to get the values from the values of input fields:
document.getElementById("wan").addEventListener("click", (e) => {
e.preventDefault();
type = "";
syn = "";
anty = "";
history = "";
example = "";
def1 = "";
for (let i = 0; i < counter; i++) {
type += document.getElementById(`wtype${i}`).value + "^";
syn += document.getElementById(`syn${i}`).value + "^";
anty += document.getElementById(`anty${i}`).value + "^";
history += document.getElementById(`history${i}`).value + "^";
example += document.getElementById(`example${i}`).value + "^";
def1 += document.getElementById(`def1${i}`).value + "^";
}
console.log(
type +
" . " +
syn +
" . " +
anty +
" . " +
history +
" . " +
example +
" . " +
def1
);
});

How to mask phone number as 123-456-7890?

In my database I have phone number as 123-456-7890 and 1234567890, Is there any way to format display in as 123-456-7890 format in my textbox
In my view I have phone textbox as
<input asp-for="PhoneNumber" type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" readonly class="form-control" id="PhoneNumber" placeholder="">
I need to format all phone number as 123-456-7890
i tried:
function formatPhoneNumber(txt) {
if (String(txt)[3] != "-") {
txt = "" + txt.slice(0, 3) + "-" + txt.slice(3, 6) + "-" + txt.slice(6);
}
return txt;
}
and in my text box
<input asp-for="PhoneNumber" type="tel" readonly pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" onchange="formatPhoneNumber(this)" class="form-control fa-mask" id="PhoneNumber" placeholder="">
Here is a demo to show how to bind data of Model with format 111-111-1111,and when change the input with the format 111-111-1111.
Controller:
public IActionResult Index()
{
TestReadOnly t = new TestReadOnly { PhoneNumber = "1231231234" };
return View(t);
}
View:
#model TestReadOnly
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<input asp-for="PhoneNumber" type="tel" aria-label="Please enter your phone number" placeholder="ex. 111-111-1111" onchange="change()">
#section scripts{
<script type="text/javascript">
$(function () {
//bind the data from Model with format 111-111-1111
let txt = JSON.stringify(#Model.PhoneNumber);
if (String(txt)[3] != "-") {
txt = '' + txt.substring(0, 3) + "-" + txt.substring(3, 6) + "-" + txt.substring(6);
}
$('[type="tel"]').val(txt);
})
//when change the input value,format 111-111-1111
function phoneMask() {
var num = $(this).val().replace(/\D/g, '');
$(this).val(num.substring(0, 3) +'-'+ num.substring(3, 6) + '-' + num.substring(6, 10));
}
$('[type="tel"]').keyup(phoneMask);
</script>
}
result:
If you want to call the function you can write <script>formatPhoneNumber("1234567890")</script> after the input tag.
note that if you write (this) in the input, the parameter is the element itself (in this case, the input).
So, if you write the (this), just change the function a little:
function formatPhoneNumber(el)
{
let txt = el.value; // add this line
if (String(txt)[3] != "-")
{
txt = '' + txt.slice(0, 3) + "-" + txt.slice(3, 6) + "-" + txt.slice(6);
}
//return txt // delete this line
el.value = txt // add this line instead
}
If you don't call the functio via the input (which means you write <script>formatPhoneNumber(parameter)</script>), the parameter will be document.getElementById("PhoneNumber").

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

Increment Serial Numbers and calculate - javascript

Our company has a client that requires a specific checksum on their bar codes. I've come up with the following which allows the user to enter the distributor part number, our part number and our serial number. Right now, when you click save, it will calculate correctly for the bar code with the checksum. NOW, we have added a quantity box so that we can print x number of barcodes with our serial number incrementing by 1. (i.e. 1st serial number is 000001, next will be 000002 and so on). What I've been trying to do for the last week is alter this code so the user can input the part numbers and sn, and it will calculate each bar code up to the quantity.
This is what we would like to have:
If user enters part numbers, first serial number and quantity then clicks "Save" this should be the result. At present, this can only be achieved by entering each serial number and clicking save
*note: while the quantity can be entered, the actual value has not been used in my code...yet
So, to achieve this, I need to find a way to increment the serial numbers without dropping off the leading zeros but maintaining the length of qty.length.
I also need to figure out how to loop each new serial number through with part numbers to get the correct checksum for the bar code. After a week of staring at this, I'm hoping some fresh and experienced eyes can assist. Here is my code.
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Capture Form Fields to CSV</title>
<script type="text/javascript">
<!--
function saveValues() {
var frm = document.form1;
var str = frm.text1.value + frm.text2.value + frm.text3.value;
var dpn = frm.text1.value;
var wpn = frm.text2.value;
var wsn = frm.text3.value;
var strArray = str.split("");
var calcArray = strArray;
var total =0;
for (var i = 0; i < str.length; i++)
strArray[i] = strArray[i].charCodeAt(0);
for (var i = 0; i < strArray.length; i++){
if (strArray[i] >= 65 && strArray[i] <= 90){
calcArray[i] = (strArray[i] - 64) * (i+1)
}
else if (strArray[i] >=97 && strArray[i] <=122) {
calcArray[i] = (strArray[i] - 96) * (i+1)
}
else if (strArray[i] >=48 && strArray[i] <=57) {
calcArray[i] = (strArray[i] - 48) * (i+1)
}
else {
calcArray[i] = 1 * (i+1)
}
}
for (var i in calcArray){
total += calcArray[i];}
var mod2 = str.length - (2*(Math.floor(str.length/2)));
var mod10 = (total + mod2) - (10*(Math.floor((total + mod2)/10))) ;
var chk = mod10;
var record = ""
+ dpn + "," + wpn + "," + wsn + "," +dpn + "~" + wpn + "~" + wsn + "~" + chk + "\n";
frm.textarea1.value += record;
}
function clearText() {
document.form1.textarea1.value = "";P
form1.text1.value = "";
form1.text2.value = "";
form1.text3.value = "";
}
function csvSave() {
var a = document.createElement('a');
with (a) {
href='data:text/csv;base64,' + btoa(document.getElementById('textarea1').value);
download='csvfile.csv';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//-->
</script>
</head>
<body>
<h1>Capture Form Fields to CSV</h1>
<form name="form1" >
<p>
Distributor Part Number: <input name="text1" type="text" value="GDM1301" /><br />
Our Part Number: <input name="text2" type="text" value="PCBDM160"/><br />
Our Serial Number: <input name="text3" type="text" value="000001"/><br />
Label Quantity: <input name="qty" type="text" value="3"/>
</p>
<p>
<input name="save" type="button" value="Save"
onclick="saveValues(); return false"/>
 
<input name="clear" type="button" value="Clear"
onclick="clearText(); return false"/>
<button onclick="csvSave()">CSV</button>
</p>
<p>
<i>Click 'Save' to add content</i><br />
<textarea id="textarea1" cols="80" rows="20"></textarea>
</p>
</form>
</body>
</html>

How do I define a variable and call it in a hidden input field?

I have a javascript code that does some math and I need to be able to just pull the final result and include it in a form. To do that I wanted to just use a <input type="hidden" name="new total">. I want to grab the results from the field "New Total". You can see my javascript code in action here. http://jsfiddle.net/danielrbuchanan/yjrTZ/5/
var prices = [];
function remove(arr,itm){
var indx = arr.indexOf(itm);
if (indx !== -1){
arr.splice(indx,1);
}
}
function calculateSectedDues(checkbox, amount) {
if (checkbox.checked === true) {
prices.push(amount);
} else {
remove(prices, amount);
}
var total = 0;
for (var i = 0, len = prices.length; i < len; i++)
total += prices[i];
var min = prices.slice().sort(function(a,b){return a-b})[0];
if(typeof min === 'undefined') min = 0;
var withDiscount = total - min;
var discountAmount = withDiscount - total;
//document.grad_enroll_form.total.value = total;
document.querySelector("#value").innerHTML = "Total: $"+total+'<br>';
document.querySelector("#value").innerHTML += "Discount: $"+discountAmount+'<br>';
document.querySelector("#value").innerHTML += "New total: $"+withDiscount+'<br>';
}
It seems simple, for some reason I'm drawing a blank on how to do it.
What i think you want is to set an input value with your variable, so i think it should go like this:
Javascript:
document.getElementById("newTotal").value = your_new_total;
HTML:
<form>
<input id='newTotal' type='hidden' name='NewTotal' value='' />
</form>
Hope this helps.
<input type="hidden" id="new_total" name="new_total">
<!-- no spaces in name and id -->
Put this code at end of the calculateSectedDues function
document.getElementById('new_total').value = withDiscount
You have a couple of options.
Option 1:
jQuery
Add a visible div, how ever you want to do things.
Bind onChange() events to your input fields that drive the calculation.
<div id="finalValue"></div>
<script language="javascript">
$(function() {
$("form input").change(function() {
calculateSectedDues($("#checkboxid"), $("#amountid").val());
});
});
</script>
In the calculateSectedDues() function add this to the end:
$("#finalValue").html("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");
Option 2:
No jQuery
<div id="finalValue"></div>
<script language="javascript">
function bindEvent() {
calculateSectedDues(document.getElementById("checkboxid"), document.getElementById("amountid").value);
}
window.onload = function()
{
var elJ = document.getElementsByTagName("input");
for (var i=0;i<elJ.length;i++) {
elJ[i].addEventListener('change',bindEvent,false);
}
}
</script>
In the calculateSectedDues() function add this to the end:
document.getElementById("finalValue").InnerHtml("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");
Is that what you are trying to get after?
You should also remember to do the calculation on the Server Side too and not rely on the JavaScript to do it for you. This would simply be to notify the user what they are getting before hand. Otherwise, front-end hacks could easily be done if you are using a hidden total field.

Categories

Resources