i have a complex div with input field somewhat like this
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<div id="section_toClone">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
</div>
<button id="add_more"> Add </button>
now when someone click on add i want something like this to happen
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="checkbox name tree[tree2][color] value="green">Green </input>
<input type="checkbox name tree[tree2][color] value="yellow">yellow </input>
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
<input type="checkbox name tree[tree3][color] value="green">Green </input>
<input type="checkbox name tree[tree3][color] value="yellow">yellow </input>
and so on..... but my script only clone doesnt change the value of tree from tree1 to tree2 to tree3 and so on.... here is my jquery script
$('#add_more').click(function(){
$("#section_toClone").clone(true).insertBefore("#add_more").find('input').val("").val('');
});
how do i increment that automatically?? i want to mention one more thing in actual html code. it has more then 3 input and 3 checkbox field
Don't even bother putting the numbers into the array keys. Just let PHP take care of it itself:
<input name="tree[fruit][]" value="foo" />
<input name="tree[fruit][]" value="bar" />
<input name="tree[fruit][]" value="baz" />
Any [] set which DOESN'T have an explicitly specified key will have one generated/assigned by PHP, and you'll end up with
$_POST['tree'] = array(
0 => 'foo',
1 => 'bar',
2 => 'baz'
);
As long as your form is generated consistently, browsers will submit the fields in the same order they appear in the HTML, so something like this will work:
<p>#1</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][]" value="large" />
<p>#2</p>
<input name="foo[color][]" value="puce" />
<input namke="foo[size][]" value="minuscule" />
and produce:
$_POST['color'] = array('red', 'puce');
| |
$_POST['size'] = array('large', 'minuscule');
But if you start mixing the order of the fields:
<p>#3</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][] value="large" />
<p>#4</p>
<input namke="foo[size][] value="minuscule" />
<input name="foo[color][] value="puce" />
$_POST['color'] = array('red', 'puce');
/
/
$_POST['size'] = array('minuscule', 'large');
Note how they're reversed.
I wouldn't post this without feeling a bit ashamed of how bad it is written, but the following solution does the trick. Badly.
var treeCount = 1;
$('#add_more').click(function(){
$("#section_toClone")
.clone(true)
.insertBefore("#add_more")
.find('input')
.val('')
.each(function(key,element){
var $element = $(element),
oldName = $element.attr('name'),
newName;
if(oldName){
newName = oldName.replace(/tree[0-9]+/, 'tree'+(treeCount+1));
$element.attr('name', newName);
}
else {
treeCount--;
}
})
.promise().done(function(){
treeCount++;
});
});
(please don't shoot me)
Related
Requirements:
A new text box should appear with a delete button at closing after clicking '+Add Stop'.
If a delete(x) button is clicked, the respective text box should be removed and Stop #(sequence numbering) should be changed as well.
Need help on:
I have tried to achieve the both above requirements. I get results for #1. But for #2, After adding more items, the delete button works/removes only the last added item only but it should work the same for all items.
Stop # sequence number should be maintained after the removal of an item(s). I need help with this logic also.
HTML:
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option>
</select><br/><br/>
<label for="fullname">Name: </label><input id="fullname" name="name" size="20" type="text" maxlength="20" placeholder="John Doe" required /><br/><br/>
<label for="phone">Phone: </label><input id="phone" name="phone" maxlength="12" type="tel" placeholder="012-345-6789" required /><br/><br/>
<label for="email">Email: </label><input id="email" name="email" size="30" type="email" maxlength="30" placeholder="contact#example.com" required /><br/><br/>
<label for="ptime">Pickup time </label><input id="ptime" name="pickup-time" type="time" required /><br/><br/>
<label for="pdate">Pickup Date </label><input id="pdate" name="pickup-date" type="date" required /><br/><br/>
<div id="add_stop_here">
</div>
<input type="button" id="add" value="+Add Stop" onclick="test();" />
</form>
JavaScript:
var counter = 0;
function test () {
counter += 1;
var addHtml = '\
<div class="input-box">\
<label for="stop'+counter+'">Stop '+counter+':</label>\
<input type="text" id="stop'+counter+'" name="stop"/ > <a id="rmv'+counter+'" class="remove_stop" href="#">x</a>\
</div>';
var add_hre = document.getElementById("add_stop_here");
add_hre.innerHTML += addHtml;
document.querySelector("#rmv"+counter)
.addEventListener('click', function(){
var removeEl = this.parentNode;
add_hre.removeChild(removeEl);
});
}
Some issues to take care of:
To make this work, I would refrain from using id attributes that have a sequential number. It is not best practice.
Instead, in order to link a label element with its input element, make the input element a child of the corresponding label element. Now the id and for attributes are no longer needed.
Don't use innerHTML += as that will reset the values of the inputs that are already in the document, and will remove the event listeners. Instead use insertAdjacentHTML.
To keep the numbering in pace, use a span element that only has that number, and renumber all those span elements after every change. You can also use it after an insert, just to keep the code clean, and avoid that you need to maintain a counter.
To avoid that you need to attach a new event handler for every new element, listen to click events on the container element, and then check in that single handler which element was clicked. This is called event delegation.
Don't name your function test. Give it a useful name, like insertBusStop.
Instead of binding that handler via HTML attribute, bind it via code.
For multi-line strings you can use back tick delimiters (template literals)
I'd suggest that after clicking the Add button, the focus is put on the newly created input element. This facilitates the input procedure for the user.
Here is how that would work:
var add_hre = document.getElementById("add_stop_here");
document.getElementById("add").addEventListener("click", addBusStop);
function addBusStop() {
var addHtml = `
<div class="input-box">
<label>
Stop <span class="stop_number"></span>
<input type="text" name="stop"/> <a class="remove_stop" href="#">x</a>
</label>
</div>`;
add_hre.insertAdjacentHTML("beforeend", addHtml);
renumber();
add_hre.querySelector(".input-box:last-child input").focus();
}
function renumber() {
let i = 1;
for (let labelSpan of add_hre.querySelectorAll(".stop_number")) {
labelSpan.textContent = i++;
}
}
// Use event delegation
add_hre.addEventListener('click', function(e) {
if (!e.target.classList.contains("remove_stop")) return;
var removeEl = e.target.parentNode.parentNode; // need one more level now
add_hre.removeChild(removeEl);
renumber();
});
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop"/>
You can do this with each() and find() function easily.
var counter = 0;
$("#add").click(function () {
counter++;
$("#add_stop_here").append(
'<div class="input-box"><label for="stop' +
counter +
'">Stop' +
counter +
': <input type="text" id="stop' +
counter +
'" name="stop"/ ></label> <a id="rmv' +
counter +
'" class="remove_stop" href="#">X</a></div>'
);
});
$(document).on("click", ".remove_stop", function () {
$(this).closest("div").remove(); //use closest here
$("#add_stop_here .input-box").each(function (index) {
$(this)
.find("label:eq(0)")
.attr("id", "stop" + (index + 1));
$(this)
.find("label:eq(0)")
.html("Stop" + (index + 1) + '<input type="text" name="stop" />');
});
counter--;
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<form action="https://www.example.com" method="POST">
<label for="stype">Service Type:</label>
<select id="stype" name="service-type">
<option disabled="disabled" selected="selected">Choose Service</option>
<option value="From Airport">From Airport</option>
<option value="To Airport">To Airport</option></select
><br /><br />
<label for="fullname">Name: </label
><input
id="fullname"
name="name"
size="20"
type="text"
maxlength="20"
placeholder="John Doe"
required
/><br /><br />
<label for="phone">Phone: </label
><input
id="phone"
name="phone"
maxlength="12"
type="tel"
placeholder="012-345-6789"
required
/><br /><br />
<label for="email">Email: </label
><input
id="email"
name="email"
size="30"
type="email"
maxlength="30"
placeholder="contact#example.com"
required
/><br /><br />
<label for="ptime">Pickup time </label
><input id="ptime" name="pickup-time" type="time" required /><br /><br />
<label for="pdate">Pickup Date </label
><input id="pdate" name="pickup-date" type="date" required /><br /><br />
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop" />
</form>
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/>
How do I check multiple variable inputs at once to ensure that the regex is working? Everytime I enter anything, the form submits and doesn't alert anything.
I have tried test()method of regex validation too, and still no luck.
I am trying to validate user input with the following regex that makes to where anything that is not a number or blank space is considered a wrong input.
var format=/^(\s*|\d+)$/;
It only accepts numbers and blank spaces in the text box.
The following javascript is what I have:
var pitch = document.getElementById("pitch");
var chisel = document.getElementById("chis");
var saw = document.getElementById("saw");
//var arguments = [chisel, saw, pitch];
var format = /^(\s*|\d+)$/;
function regexTest() {
if (!chisel.match(format) && !saw.match(format) && !pitch.match(format)) {
alert("Repressed Action");
return false;
} else {
alert('Thank you');
}
}
<div class="lab">
<form method="post" action="http://weblab.kennesaw.edu/formtest.php">
Chisels: <input type="text" name="chisels" id="chis" size="5" /> Saw: <input type="text" name="saw" id="saw" size="5" /> Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5" />
<br /> Customer Name: <input type="text" name="customer name" size="25" />
<br /> Shipping Address: <input type="text" name="shipping address" size="25" />
<br /> State:
<input type="radio" id="master" name="card" value="master" /><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american" /><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa" /><label for="visa">Visa</label>
<br />
<input type="reset" value="Reset" />
<div class="lab">
<button onclick="regexTest()">Submit</button>
<button onclick="return false">Cancel</button>
</div>
There are a number of issues with your code, below I've refactored it to be a bit easier to read and so it works.
The validation listener should be on the form's submit handler, not the submit button since forms can be submitted without clicking the button. Also, if you pass a reference to the form to the listener, it's much easier to access the form controls by name.
You should get the values of the form controls when the submit occurs, not before. Your code gets the values immediately, before the user has done anything (and possibly before the form even exists), so put that code inside the listener function.
Lastly, the regular expression needs to match anything that isn't a space or digit, so:
/[^\s\d]/
seems appropriate. However, this will still allow the form to submit if the fields are empty (they don't contain non-digits or non-spaces). You'll need to add a test for that.
function regexTest(form) {
// Get values when the function is called, not before
var pitch = form.pitchfork.value;
var chisel = form.chisels.value;
var saw = form.saw.value;
// Test for anything that's not a space or digit
// var format = /^(\s*|\d+)$/;
var format = /[^\s\d]/;
if (format.test(chisel) || format.test(pitch) || format.test(saw)) {
// There must be at least one non-space or non-digit in a field
alert("Repressed Action");
return false;
} else {
alert('Thank you');
// return false anyway for testing
return false;
}
}
<div class="lab">
<form onsubmit="return regexTest(this)">
Chisels: <input type="text" name="chisels" id="chis" size="5"><br>
Saw: <input type="text" name="saw" id="saw" size="5"><br>
Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5"><br>
Customer Name: <input type="text" name="customer name" size="25"><br>
Shipping Address: <input type="text" name="shipping address" size="25">
<br> State:
<select name="states">
<option>Florida</option>
<option>Georgia</option>
<option>Alabama</option>
</select>
<br>
<input type="radio" id="master" name="card" value="master"><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american"><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa"><label for="visa">Visa</label>
<br>
<input type="reset" value="Reset">
<div class="lab">
<button>Submit</button>
<button onclick="return false">Cancel</button>
</div>
Hopefully this gets you to the next step.
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().
<form name="Details" method="post" action="insertData.jsp" onSubmit="return ValidateForm();">
<label> Name </label > <input type="text" name="name" id="test1" > </input>
<label> ID </label > <input type="text" name="id" id="test2" > </input>
<label> Time </label > <input type="text" name="time" id="test3" > </input>
<label> Latitude </label > <input type="text" name="latitude" id="test4" > </input>
<label> Longitude </label > <input type="text" name="longitude" id="test5" > </input>
<input type= " submit" id="test6" value="submit" > </input>
Validation code in js
function ValidateForm()
{
var uname=document.Detail.name;
if(alphanumeric(uname)){
}
return false;
}
function alphanumeric(uname){
var letter=/*[0-9a-zA-Z]+$/;
if(uname.value.match(letter)){
return true;
}
else{
aler("Enter both alpha and number");
uname.focus();
return false;
}
}
The above validation is to allow a textfield to accept both alphabets and numbers but not only numbers. Its returning false on a wrong input but still the data entered entered is submitted to the database. How to avoid this? what is wrong in my code?
I also want to validate form before submit. After every field is entered it should be validated and displayed if any error just below the field. How do i do it?
You could use a naming pattern for the Ids of hidden <span> tags that represent the form field error messages:
<form onsubmit="return ValidateForm(this);">
<p>
<input type="text" id="name" name="name">
<span style="display: none;" id="name-validation-message"></span>
</p>
</form>
<script>
function ValidateForm(form) {
if (!alphanumeric(form.elements.name)) {
var message = document.getElementById(form.elements.name.id + "-validation-message");
message.innerHTML = "Must be alphanumeric";
message.style.display = "";
}
}
</script>
The elements property on form objects is a key-value store where the keys are the values of the name attribute on the form fields, and the values are either a reference to a single form field DOM node, or a collection.
Consider the following HTML:
<form id="test">
<input type="text" name="foo">
<input type="checkbox" name="bar" value="1">
<input type="checkbox" name="bar" value="2">
<input type="checkbox" name="bar" value="3">
<input type="checkbox" name="bar" value="4">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
</form>
We have three unique form field name attribute values:
foo
bar
things[]
In JavaScript, we'll have the following object model:
var form = document.getElementById("test");
form.elements; // A collection of references to all form fields
form.elements.foo; // Reference to <input type="text" name="foo">
// A DOM node collection referencing all checkboxes whose name is "bar"
form.elements.bar;
form.elements.bar[0]; // First "bar" checkbox
form.elements.bar[1]; // Second "bar" checkbox
// A DOM node collection referencing all text boxes whose name is "things[]"
form.elements["things[]"];
form.elements["things[]"][0]; // First "things[]" textbox
form.elements["things[]"][1]; // Second "things[]" textbox
Many server side languages turn field names with square brackets into arrays. You can access those fields in JavaScript using the Array Notation (e.g. form.elements["bar"] instead of Dot Notation (e.g. form.elements.bar).
Hope the following code helps.
<HTML>
<HEAD>
<TITLE>Verifying User Data</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function checker()
{
var regExp1 = '/^(\d{1,2})\/(\d{1,2})\/(\d{2})$/' ;
var result1 = document.form1.text1.value.match(regExp1);
if (result1 == null || <*any other input doesnt satisfy the required format*>) {
alert("Sorry, that's not a valid date.");
document.form1.text1.focus(); // or document.<formname>.<element_name>.focus();
return;
} else {
document.form1.action="<NextPage.jsp>" ;
document.form1.method="GET"; // or "POST"
document.form1.submit();
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Verifying User Data</H1>
<FORM NAME="form1" >
Please enter a date:
<INPUT TYPE="TEXT" NAME="value1">
<INPUT TYPE="<sometype>" NAME="value2">
<INPUT TYPE="<sometype>" NAME="value3">
..
..
<INPUT TYPE="button" onclick="checker()">
</FORM>
</BODY>
Write another javascript on submit button like
<input type= " submit" id="test6" value="submit" onclick="return save();">
<script>
function save(){
document.form[0].submit;
}
</script>