javascript interest calculator over multiple years - javascript

I need to make three textboxes with date of birth, amount (money) and interest.
with click on the button a overview of doubled amount should appear if I put my money on the bank at a certain interest rate.
I don't know how to start.

Textboxes:
Generally, for creating User Interface on the web, you will write HTML. Using your case, for example, we know you need three textboxes. I would use <input> elements like this:
Step 1
<input name="dob" type="date" />
<input name="amount" type="number" step="0.01" />
<input name="interest" type="number" step="0.001" />
Step 2
We can further wrap these to add text labels using <label> elements, like so:
<label>
Date of Birth
<input name="dob" type="date" />
</label>
<label>
Amount
<input name="amount" type="number" step="0.01" />
</label>
<label>
Interest
<input name="interest" type="number" step="0.001" />
</label>
Step 3
Then, to link them together, we wrap them using a <form> element:
<form>
<label>
Date of Birth
<input name="dob" type="date" />
</label>
<label>
Amount
<input name="amount" type="number" step="0.01" />
</label>
<label>
Interest
<input name="interest" type="number" step="0.001" />
</label>
</form>
Step 4
Finally, we need elements for calculation. I would use the aptly-named <output> element and a <button> element to submit the form:
<form>
<label>
Date of Birth
<input name="dob" type="date" />
</label>
<label>
Amount
<input name="amount" type="number" step="0.01" />
</label>
<label>
Interest
<input name="interest" type="number" step="0.001" />
</label>
<label>
Total
<output name="total">0</output>
</label>
<button type="submit">Calculate</button>
</form>
Calculation:
As you see above, <input> is an interactive element that generally has a name and value. value can be updated by someone using your page or via JavaScript, after the elements in question have been fully loaded. To update these elements and get values for your calculations via JavaScript, you would use something called the DOM (Document Object Model) and react to user input by "listening" to events (like "click", for example). The form fires an event called "submit" when you click the "Calculate" button in the example above. We can use that instead of "click", which makes it easier to handle everything inside the form (like the textboxes). For example:
// Step 1: Create a JavaScript function (actually gets run later)
const calcForm = form => {
// Get values (and totalElement) from form.elements
const {
amount: {value: amount},
interest: {value: interest},
total: totalElement,
} = form.elements
// Update the totalElement with interest * amount
totalElement.value = (interest * amount).toFixed(2)
}
// Step 2: Wait for the DOM to fully load (so formElement exists)
window.addEventListener('DOMContentLoaded', (event) => {
// Step 3: Get form element using the "js-form" class
const formElement = document.querySelector('.js-form')
// Step 4: Run calcForm on "submit" event
formElement.addEventListener('submit', (e) => {
e.preventDefault()
calcForm(e.target)
})
// Step 5: Run calcForm at start
calcForm(formElement)
})
One helpful thing to do is use classes as JavaScript "hooks", so I also changed the form HTML to read: <form class="js-form"> at this step. I use js- prefixes on classes to make it clear where it is used (that is, not CSS). You'll notice the line that says document.querySelector('.js-form')...this is what gets the <form> as an object in JavaScript.
Finally, putting all of this together, here's a working snippet with some basic (fully optional) CSS styling, but:
const calcForm = form => {
const {
amount: {value: amount},
interest: {value: interest},
total: totalElement,
} = form.elements
totalElement.value = (amount * interest).toFixed(2)
}
window.addEventListener('DOMContentLoaded', (event) => {
const formEl = document.querySelector('.js-form')
formEl.addEventListener('submit', (e) => {
e.preventDefault()
calcForm(e.target)
})
calcForm(formEl)
})
.form {
display: grid;
margin: 0 auto;
width: min-content;
justify-items: end;
text-align: right;
gap: 1rem;
}
.form__label {
display: grid;
gap: 0.5rem;
font-weight: bold;
}
.form__input {
width: 150px;
text-align: inherit;
}
<form class="js-form form">
<label class="form__label">
Date of Birth
<input class="form__input" name="dob" type="date" />
</label>
<label class="form__label">
Amount
<input class="form__input" name="amount" type="number" step="0.01" value="50.00" />
</label>
<label class="form__label">
Interest
<input class="form__input" name="interest" type="number" step="0.001" value="0.025" />
</label>
<label class="form__label">
Total
<output name="total">0</output>
</label>
<button type="submit">Calculate</button>
</form>

Related

CSS change text coloration when disabled by javascript

I used the javascript code for making my inputs disabled. It works, but only for inputs. I would like to change the font color also when my inputs are disabled.
My code looks as follows:
$("input[name=h3g_civils_required]").on('click', function() {
var h3gCivils =
$('#h3g_civils_dimensions'); //Question 15
// if is company
if ($(this).val() ==
"Yes") {
// show panel
h3gCivils.show();
// remove disabled prop
h3gCivils.find('input,select,radio').prop('disabled', false);
} else {
// if is not company, hide the panel and add disabled prop
//managerOnSite.hide();
h3gCivils.find('input,select,radio').prop('disabled', true); //Question 16 inactive
}
});
.textparagraph {
margin-left: 15px;
}
.textparagraph:disabled {
color: blueviolet;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<figure class="fig">
<label>
<div class="order">18</div>
<p>Civils required?<span class="asterisk">*</span>
</p>
</label>
<br>
<input id="h3g_civils_required_yes" name="h3g_civils_required" class="radiobtn" type="radio" value="Yes" required>Yes
<input id="h3g_civils_required_no" name="h3g_civils_required" class="radiobtn" type="radio" value="No">No
<br>
</figure>
<figure class="fig" id="h3g_civils_dimensions">
<label>
<div class="order">19</div>
<p>Civils lengths (in Mtrs):</p>
</label>
<br>
<p class="textparagraph" disabled>
Soft Dig: <input class="otherinput" type="number" min="1" name="h3g_soft_dig" required> Footway: <input class="otherinput" type="number" min="1" name="h3g_footway" required> Carriageway: <input class="otherinput" type="number" min="1" name="h3g_carriageway"
required> Chamber: <input class="otherinput" type="number" min="1" name="h3g_chamber" required>
</p>
<br>
</figure>
I put disabled next to my textparagraph class, like they shown here but there is no reaction at all.
Is there any chance to change the text coloration, when the whole <figure> defined by id is disabled by javaScript?
As mentioned above, to solve your problem only need one additional css class for switch and two line of the js (add & remove class).
$('input[name=h3g_civils_required]').on('click', function () {
var h3gCivils = $('#h3g_civils_dimensions'); //Question 15
// if is company
if ($(this).val() == 'Yes') {
// show panel
h3gCivils.show();
// remove disabled prop
h3gCivils.find('input,select,radio').prop('disabled', false);
h3gCivils.find('.textparagraph').removeClass('disabled');
} else {
// if is not company, hide the panel and add disabled prop
//managerOnSite.hide();
h3gCivils.find('.textparagraph').addClass('disabled');
h3gCivils.find('input,select,radio').prop('disabled', true); //Question 16 inactive
}
});
.textparagraph {
margin-left: 15px;
}
.textparagraph.disabled {
color: blueviolet;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<figure class="fig">
<label>
<div class="order">18</div>
<p>Civils required?<span class="asterisk">*</span></p>
</label>
<br />
<input
id="h3g_civils_required_yes"
name="h3g_civils_required"
class="radiobtn"
type="radio"
value="Yes"
required
/>Yes
<input
id="h3g_civils_required_no"
name="h3g_civils_required"
class="radiobtn"
type="radio"
value="No"
/>No
<br />
</figure>
<figure class="fig" id="h3g_civils_dimensions">
<label>
<div class="order">19</div>
<p>Civils lengths (in Mtrs):</p>
</label>
<br />
<p class="textparagraph" disabled>
Soft Dig:
<input
class="otherinput"
type="number"
min="1"
name="h3g_soft_dig"
required
/>
Footway:
<input
class="otherinput"
type="number"
min="1"
name="h3g_footway"
required
/>
Carriageway:
<input
class="otherinput"
type="number"
min="1"
name="h3g_carriageway"
required
/>
Chamber:
<input
class="otherinput"
type="number"
min="1"
name="h3g_chamber"
required
/>
</p>
<br />
</figure>
You can not use disabled on a <p> tag. Or better, you can use it, but is not accessible with CSS selector :disabled. It can be selected as .textparagraph[disabled] (See here). So this will work:
.textparagraph[disabled] {
color:blueviolet;
}
But I would suggest you move the disabled attribute on the <input> tags (to effectively disable them) and then style them as follow:
.textparagraph input:disabled {
color:blueviolet;
}
Or if you need to manipulate the <p> tag (as CBroe pointed out) use a class. Something like this:
.textparagraph.disabled {
color:blueviolet;
}
Then style your component as <p class="textparagraph disabled">

Multiplication in jQuery dynamically

I am trying to make a multiplication function in jquery where which helps change the default value-based output.
For example - if I type the input#mainInput value then it will change all the inputs value base own his default value * input#mainInput and if the value == 'NaN' it will do dirent funcion.
Please help me how to I make this function in jQuery.
$(document).on('keyup', 'input#mainInput', function() {
thisParentQtyValueBox = $(this).val();
daughtersBoxValueAttr = $("input.input__bom").attr("inputid");
daughtersBoxValue = $("input#daughterInput_" + daughtersBoxValueAttr).val();
$("input#daughterInput_" + daughtersBoxValueAttr).val(thisParentQtyValueBox * daughtersBoxValue);
if ($("input#daughterInput_" + daughtersBoxValueAttr) == 'Nan') {
$("input#daughterInput_" + daughtersBoxValueAttr).val('3' * daughtersBoxValue)
}
});
//If
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" value="25" /><br/>
If I understand correctly, when the input is not a number, you want to do as if the input was 3.
Some issues in your code:
$("input.input__bom").attr("inputid") is always going to evaluate to 1, as only the first matching element is used. And it is strange to use this attribute value to then retrieve that element again via its id property.
You would need a loop somewhere so to visit each of the "input__bom" elements.
== 'Nan is never going to be true. You should in fact test the main input itself to see if it represents a valid number. For that you can use isNaN.
It is a bad idea to give these elements a unique id attribute. You can use jQuery to visit them each and deal with them. There is no need for such id attribute.
Don't use the keyup event for this, as input can be given in other ways than pressing keys (e.g. dragging text with mouse, or using the context menu to paste). Use the input event instead.
There is no good reason to use event delegation here on $(document). Just bind your listener directly the main input element.
Declare your variables with var (or let, const). It is bad practice to no do that (it makes your variables global).
It seems like the 5 "bom" input elements are not really intended for input, but for output. In that case the placeholder attribute makes no sense, and they should better be marked with the readonly attribute.
$("#mainInput").on('input', function() {
var mainInput = $(this).val();
var multiplier = +mainInput; // convert to number with unary +
// default value in case input is not a valid number, or is empty
if (Number.isNaN(multiplier) || !mainInput) {
multiplier = 3;
}
$('.input__bom').each(function() {
$(this).val( multiplier * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" type="text" readonly data-value="5" value="5"><br/>
<input class="input__bom" type="text" readonly data-value="10" value="10"><br/>
<input class="input__bom" type="text" readonly data-value="15" value="15"><br/>
<input class="input__bom" type="text" readonly data-value="20" value="20"><br/>
<input class="input__bom" type="text" readonly data-value="25" value="25" /><br/>
You have to store the default value in the data attr so then it will not multiple by result value and it will multiple by your default value. for dynamic multiplication, you can use jquery each. check below code.
$(document).on('input', 'input#mainInput', function() {
thisParentQtyValueBox = parseInt( $(this).val() );
if( Number.isNaN( thisParentQtyValueBox ) ){
thisParentQtyValueBox = 3;
}
$('.input__bom').each(function(){
$(this).val( thisParentQtyValueBox * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" data-value ="5" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" data-value ="10" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" data-value ="15" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" data-value ="20" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" data-value ="25" value="25" /><br/>

Iterate through N number of input boxes, updating each to their max value

Is there a way to give a bunch of inputs the same ID, and then iterate over them, when a checkbox is checked, and update their respective values to the MAX attribute? For example, with the following HTML:
CHECK ALL: <input type="checkbox" id="someIDname">
<input type="number" max="80" id="anotherIDname">
<input type="number" max="90" id="anotherIDname">
<input type="number" max="99" id="anotherIDname">
<input type="number" max="65" id="unrelated">
<input type="number" max="75" id="unrelated">
... and the JS is like this:
<script type="text/javascript">
$(document).ready(function() {
$('#someIDname').click(function(event) {
if(this.checked) {
$('#anotherIDname').each( function() {
var maxValue = $("#anotherIDname").attr("max");
document.getElementById("anotherIDname").value = maxValue;
});
}
});
});
</script>
I'd like to, when the checkbox is checked, have it fill in all of the MAX attributes from anything with the "anotherIDname" ID. (I'd then have three boxes, onewith 80, one with 90, one with 99. The other two are different IDs, so it would leave those alone.)
Total beginner with JS / jQuery here... The above script works on the 1st box, but does not update the others with the "anotherIDname" ID. (I thought maybe that ".each" would make it do them all, one at a time, but ... I guess that's not how it works. (I'm more of a PHP guy, normally, and that would be how something like this could maybe work if it was server-side.) Any thoughts appreciated.
There are few things wrong
id is always unique in the page.Same class is assigned to elements having same features
You should use $(this).val() to set the value
$(document).ready(function() {
$('#someIDname').click(function(event) {
if(this.checked) {
$('.anotherIDname').each( function() {
var maxValue = $(this).attr("max");
console.log(maxValue);
$(this).val(maxValue)
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="someIDname">
<input type="number" max="80" class="anotherIDname">
<input type="number" max="90" class="anotherIDname">
<input type="number" max="99" class="anotherIDname">
<input type="number" max="65" class="unrelated">
<input type="number" max="75" class="unrelated">
Added a class name and used querySelectorAll. Does this work as you want?
$(document).ready(function() {
$('#someIDname').click(function(event) {
if(this.checked) {
document.querySelectorAll('.max').forEach(a => {
a.value = a.max;
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CHECK ALL: <input type="checkbox" id="someIDname">
<input type="number" max="80" id="anotherIDname" class="max">
<input type="number" max="90" id="anotherIDname" class="max">
<input type="number" max="99" id="anotherIDname" class="max">
<input type="number" max="65" id="unrelated" class="max">
<input type="number" max="75" id="unrelated" class="max">
The id must be unique in the page. So, you can't use same id in several places. However, you can use same class in several places.
So, you'll need to change the id to class for eg.:
<input type="number" max="80" class="maxinput" />
And to set the value from max attribute:
$('.maxinput').val(function() {
return $(this).attr('max')
});
However, I would suggest to use data-* instead of simple attribute:
<input type="number" data-max="80" class="maxinput" />
And get the data value:
$('.maxinput').val(function() {
return $(this).data('max')
});
But I am still in surprise why you aren't simply setting their values initially?
<input type="number" class="maxinput" value="80" />

Restrict values in HTML input field at time of input?

In this hypothetical page I have these inputs:
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
The that's confusing me is I know that they're restricted if I put the inputs in a form and submit the form.
But if you go to the fiddle: Fiddle
You can easily type in 100 or -20 or anything out side of the range of 1-9.
Is there a way to restrict the values in an input field at the time of inputting them? / without submitting it
(side questions: when do the min/max attributes of the input fields take effect? is it only at the time of submitting the form? Is it possible to validate the values without submitting a form?)
It looks like Google Chrome will enforce the min/max values when you use a submit button on the form.
I've updated your sample, with 3 submit buttons (labelled accordingly)... one will enforce the validation, the others will show the errors, but submit anyway.
http://jsfiddle.net/uatxcvzp/12/
<form>
<input type="number" min="1" max="9" required />
<input type="number" min="1" max="9" required />
<input type="number" min="1" max="9" required />
<input type="number" min="1" max="9" required />
<br/>
<br/><input type="button" value="Submit With No Forced Validation" onclick="this.form.submit();"/>
<br/><input type="submit" value="Submit With No Forced Validation" onclick="this.form.submit();"/>
<br/><input type="submit" value="Submit With Forced Validation"/>
</form>
In Firefox, the validation occurs on field blur, highlighting the field border in red and showing a tooltip explaining the error on hover. Using either submit style will halt and require that the errors are fixed.
In IE10, only the native submit button will force validation when you try to submit the form.
In Safari on iOS9.1, it looks like it is completely ignored regardless of the submit button/code style used. :-(
try this:
$("input[type='number']").change(function() {
var $this = $(this);
var val = $this.val();
var span = $(".error");
if (val > 9 || val < 1) {
span.text("value must be between 1 and 9");
}else{
span.text("");
}
});
input {
width: 40px;
height: 40px;
font-size: 1.4em;
}
.error {
color: red;
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<input type="number" min=1 max=9 required />
<span class="error"></span>
you can try the following code:
<input type="number" min=1 max=9 required onKeyDown="if(this.value.length==1) return false;" />
thy this its work for me
<input type="text" name="number" minlength='1' maxlength="9" required>
It looks like it's not natively possible as an uncontrolled component and it needs to become a controlled component - either writing javascript/jQuery manually, or using a library.
If using React, you can use something like react-hook-form and the code would look something like below. Specifically, see the age input.
Full documentation is here: https://react-hook-form.com/api/useform/register
import * as React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: '',
lastName: '',
age: '',
}
});
return (
<form onSubmit={handleSubmit(console.log)}>
<input {...register("firstName", { required: true })} placeholder="First name" />
<input {...register("lastName", { minLength: 2 })} placeholder="Last name" />
<input
{...register("age", {
validate: {
positive: v => parseInt(v) > 0,
lessThan200: v => parseInt(v) < 200,
}
})}
/>
<input type="submit" />
</form>
);
}

How do I input variables to change label text using javascript

I am trying to make it so that when the user inputs a names into the inputbox and then clicks the 'Enter Candidates' button, it will then change the name of the labels below. Is there a way to do this in javascript? i have just started coding so i am a bit of a newbie.
<form class="simple-form">
<div>Enter your candidate <b>names</b> in the boxes below:</div>
<br/>
<label for="C1">Candidate 1:</label>
<input type="text" name="C1" id="C1" class="InputBox" />
<br/>
<label for="C2">Candidate 2:</label>
<input type="text" name="C2" id="C2" class="InputBox" />
<br/>
<label for="C3">Candidate 3:</label>
<input type="text" name="C3" id="C3" class="InputBox" />
<br/>
<label for="C4">Candidate 4:</label>
<input type="text" name="C4" id="C4" class="InputBox" />
<br/>
<label for="C5">Candidate 5:</label>
<input type="text" name="C5" id="C5" class="InputBox" />
<br/>
<input type="button" OnClick="EnterCandidates" value="Enter Candidates" />
<br/>
<br/>
<div>Enter the candidates <b>votes</b> in the boxes below:</div>
<br/>
<label for="V1" id="L_V1">Name 1:</label>
<input type="text" name="V1" id="I_V1" class="InputBox" />
<br/>
<label for="V2" id="L_V2">Name 2:</label>
<input type="text" name="V2" id="I_V2" class="InputBox" />
<br/>
<label for="V3" id="L_V3">Name 3:</label>
<input type="text" name="V3" id="I_V3" class="InputBox" />
<br/>
<label for="V4" id="L_V4">Name 4:</label>
<input type="text" name="V4" id="I_V4" class="InputBox" />
<br/>
<label for="V5" id="L_V5">Name 5:</label>
<input type="text" name="V5" id="I_V5" class="InputBox" />
<br/>
<input type="button" OnClick="" value="Enter Votes" />
<br/>
</form>
Thanks everyone who helped me.
One more question.
I have decided to use this code (thanks #David Thomas):
function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function(label, index) {
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
});
}
How do i add a verification so that the user can only use string and it has a certain character limit like 20 characters?
I tried to add one of your guys suggestions to it but i guess i did it wrong because it did not work.
You probably want to use
document.getElementById('Label ID').innerHTML = document.getElementById('Input ID').value
Please see here : http://jsfiddle.net/jzqp70oq/
Hope this is what you are expecting.
document.getElementById('L_V1').innerHTML= document.getElementById('C1').value;
//character validation
var val = document.getElementById('c2').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
//Length validation
if (val.length >10) {
alert("characters are too long !")
}
Try this
<head>
<script type="text/javascript">
function test(){document.getElementById('Label_ID').innerHTML=document.getElementById('Input_ID').value;
}
</script>
</head>
//....
<input type="button" onClick="EnterCandidates();" value="Enter Candidates" />
//...
The following JavaScript achieves your desired output, I think:
function EnterCandidates() {
// Using document.querySelectorAll() to get the <input> elements
// whose id attribute/property starts with the upper-case letter C:
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
// finding the <label> elements whose 'for' attribute starts with
// the upper-case letter V, and whose id starts with the string "L_V":
names = document.querySelectorAll('label[for^=V][id^=L_V]');
// using Function.prototype.call() to iterate over the Array-like
// nodeList, returned by document.querySelectorAll, using an
// an Array method (Array.prototype.forEach()):
Array.prototype.forEach.call(names, function (label, index) {
// the first argument of the anonymous function ('label')
// is the array-element of the Array (or Array-like) structure
// over which we're iterating, and is a <label> element,
// the second argument ('index') is the index of that current
// element in the Array (or Array-like structure).
// if the value of the <input> at the same index in the collection
// as the current <label>'s index has a value that is not
// equal to its default-value:
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
// we update the textcontent of the <label> to be
// equal to that of the value entered in the <input>
label.textContent = candidateNameInputs[index].value;
}
});
}
function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function(label, index) {
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
});
}
label::before {
content: "\A";
white-space: pre;
}
label::after {
content: ': ';
}
label,
input {
box-sizing: border-box;
line-height: 1.4em;
height: 1.4em;
margin-bottom: 0.2em;
}
input[type=button]:last-child {
display: block;
}
<form class="simple-form">
<fieldset>
<legend>Enter your candidate <b>names</b> in the boxes below:</legend>
<label for="C1">Candidate 1</label>
<input type="text" name="C1" id="C1" class="InputBox" />
<label for="C2">Candidate 2</label>
<input type="text" name="C2" id="C2" class="InputBox" />
<label for="C3">Candidate 3</label>
<input type="text" name="C3" id="C3" class="InputBox" />
<label for="C4">Candidate 4</label>
<input type="text" name="C4" id="C4" class="InputBox" />
<label for="C5">Candidate 5</label>
<input type="text" name="C5" id="C5" class="InputBox" />
<input type="button" onclick="EnterCandidates()" value="Enter Candidates" />
</fieldset>
<fieldset>
<legend>Enter the candidates <b>votes</b> in the boxes below:</legend>
<label for="V1" id="L_V1">Name 1</label>
<input type="text" name="V1" id="I_V1" class="InputBox" />
<label for="V2" id="L_V2">Name 2</label>
<input type="text" name="V2" id="I_V2" class="InputBox" />
<label for="V3" id="L_V3">Name 3</label>
<input type="text" name="V3" id="I_V3" class="InputBox" />
<label for="V4" id="L_V4">Name 4</label>
<input type="text" name="V4" id="I_V4" class="InputBox" />
<label for="V5" id="L_V5">Name 5</label>
<input type="text" name="V5" id="I_V5" class="InputBox" />
<input type="button" value="Enter Votes" />
</fieldset>
</form>
JS Fiddle demo, for experimentation and development.
Please note that I edited your HTML structure as well, to try and make it more semantic in its structure; removed the <br> nodes, and switched to CSS to to break the elements into new-lines; used the <legend> elements to hold the 'instructions' for each section (removing the <div> element you originally used). Also, I grouped the associated elements together using <fieldset> elements to wrap the <label> and <input> groups together, along with the relevant 'control' button.
Further, since it made it slightly easier to update the text without having to add back 'presentation' strings (the colons), I used CSS to achieve that end in order that presentation could be easily updated without using search/replace when – inevitably – the design changes.
With regard to the update to the question, and the question left in comments:
is there a way to add a verification to this so that the user can only use letters of the alphabet. Also a character limit so that the user can only type <20 characters?And how do i implement it in this code? I will edit my post if there is an answer.
The answer, of course, is "yes," to do so I'd suggest the following approach:
function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]'),
// A regular expression literal; which means:
// the complete string, from the start (^)
// to the end ($) must comprise of characters
// a-z (inclusive), apostrophe (') and white-space
// (to allow O'Neill, for example); this must be
// zero to 20 characters in length ({0,20}) and
// is case-insensitive (i):
validity = /^[a-z'\s]{0,20}$/i,
// two empty/uninitialised variables for use within
// the forEach() loop:
tempNode, tempVal;
Array.prototype.forEach.call(names, function (label, index) {
// caching the candidateNameInputs[index] Node:
tempNode = candidateNameInputs[index];
// caching the value of that Node:
tempVal = tempNode.value;
// if the value of the Node is not equal to the default-value
// of the Node, AND the value of the Node matches the regular
// expression (returns true if so, false if not):
if (tempVal !== tempNode.defaultValue && validity.test(tempVal)) {
// we remove the 'invalid' class from the Node if
// it's present:
tempNode.classList.remove('invalid');
// update the text of the <label>:
label.textContent = tempVal;
// otherwise, if the value does not match (!) the
// the regular expression:
} else if (!validity.test(tempVal)) {
// we add the 'invalid' class-name to the
// Node:
tempNode.classList.add('invalid');
// and set the text of the <label> to
// its original state, by concatenating
// the string "Name " with the result of the
// current (zero-based) index of the <label>
// after adding 1 (to make it one-based):
label.textContent = 'Name ' + (index + 1);
// otherwise, if the value is equal to the default-value
// we do nothing other than remove the 'invalid'
// class-name from the <input> Node:
} else if (tempVal === tempNode.defaultValue) {
tempNode.classList.remove('invalid');
}
});
}
function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]'),
validity = /^[a-z'\s]{0,20}$/i,
tempNode, tempVal;
Array.prototype.forEach.call(names, function(label, index) {
tempNode = candidateNameInputs[index];
tempVal = tempNode.value;
if (tempVal !== tempNode.defaultValue && validity.test(tempVal)) {
tempNode.classList.remove('invalid');
label.textContent = tempVal;
} else if (!validity.test(tempVal)) {
tempNode.classList.add('invalid');
label.textContent = 'Name ' + (index + 1);
} else if (tempVal === tempNode.defaultValue) {
tempNode.classList.remove('invalid');
}
});
}
label::before {
content: "\A";
white-space: pre;
}
label::after {
content: ': ';
}
label,
input {
box-sizing: border-box;
line-height: 1.4em;
height: 1.4em;
margin-bottom: 0.2em;
}
input[type=button]:last-child {
display: block;
}
input.invalid {
border-color: #f00;
}
<form class="simple-form">
<fieldset>
<legend>Enter your candidate <b>names</b> in the boxes below:</legend>
<label for="C1">Candidate 1</label>
<input type="text" name="C1" id="C1" class="InputBox" />
<label for="C2">Candidate 2</label>
<input type="text" name="C2" id="C2" class="InputBox" />
<label for="C3">Candidate 3</label>
<input type="text" name="C3" id="C3" class="InputBox" />
<label for="C4">Candidate 4</label>
<input type="text" name="C4" id="C4" class="InputBox" />
<label for="C5">Candidate 5</label>
<input type="text" name="C5" id="C5" class="InputBox" />
<input type="button" onclick="EnterCandidates()" value="Enter Candidates" />
</fieldset>
<fieldset>
<legend>Enter the candidates <b>votes</b> in the boxes below:</legend>
<label for="V1" id="L_V1">Name 1</label>
<input type="text" name="V1" id="I_V1" class="InputBox" />
<label for="V2" id="L_V2">Name 2</label>
<input type="text" name="V2" id="I_V2" class="InputBox" />
<label for="V3" id="L_V3">Name 3</label>
<input type="text" name="V3" id="I_V3" class="InputBox" />
<label for="V4" id="L_V4">Name 4</label>
<input type="text" name="V4" id="I_V4" class="InputBox" />
<label for="V5" id="L_V5">Name 5</label>
<input type="text" name="V5" id="I_V5" class="InputBox" />
<input type="button" value="Enter Votes" />
</fieldset>
</form>
JS Fiddle demo, for experimentation and development.
References:
CSS:
::after pseudo-element.
::before pseudo-element.
content property.
HTML:
<fieldset>
<label>.
<legend>.
JavaScript:
Array.prototype.forEach().
Element.classList.
Function.prototype.call().
HTMLFieldSetElement.
HTMLLabelElement.
HTMLLegendElement.
JavaScript Regular Expressions Guide.
Node.textContent.
RegExp.prototype.test().

Categories