How do I input variables to change label text using javascript - 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().

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">

Call for multiple values to be displayed in textarea

I'm in the process of trying to create a simple input form web page using both HTML and JavaScript but I am stuck. What I am trying to do is to ask for the following and display them in the textarea:
-First Name
-Last Name
-CRN
-Professor Name
So far I am only able to get the First Name to show on the Results box but no luck with the other. Could use some help, thanks in advance.
My CODE looks like this:
// initialize the counter and the array
var numbernames=0;
var names = new Array();
function SortNames() {
// Get the name from the text field
thename=document.theform["firstn"].value
// Add the name to the array
names[numbernames]=thename;
// Increment the counter
numbernames++;
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Here's a complete different, but more readable approach.
I get all inputs of type text.
I get the textarea that is the target.
loop throug all inputs getting it's value.
inside loop, after getting the value, set it to the textarea
Take a look running the snippet below
// initialize the counter and the array
function SortNames() {
var inputs = document.querySelectorAll('input[type="text"]');
var txtArea = document.querySelector('[name="sorted"]');
//loop the text inputs
inputs.forEach(function(elem){
var valueOf = elem.value;
txtArea.value += valueOf + '\n'; //concat the value
});
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit" onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted"></textarea>
</form>
EDIT
If you REALLY want to keep the way you were doing, here's a solution:
1. Push the values from the inputs directly to the array, then set the value inside the textarea.
// initialize the counter and the array
var names = new Array();
function SortNames() {
names.push(document.theform["firstn"].value);
names.push(thename=document.theform["lastn"].value);
names.push(thename=document.theform["crn"].value);
names.push(thename=document.theform["prof"].value);
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Changed the tags to more semantic and functional tags. Used the HTMLFormControlsCollection API to set/get form controls. The output is a Template Literal.
Details Commented in Demo
Demo
// Reference the top form
const reg = document.forms.registration;
// Reference the bottom form
const dis = document.forms.display;
// Collect all inputs from top form
const f = reg.elements;
// When top form is clicked...
reg.onclick = function(event) {
// Collect the data from each input and store it in an Object
const student = {
First: f.first.value,
Last: f.last.value,
CRN: f.crn.value,
Prof: f.prof.value
};
// Call function
displayData(event, student);
}
function displayData(event, student) {
// Reference the textarea
const view = dis.elements.sorted;
// if the element that was clicked had [name=add]...
if (event.target.name === 'add') {
/* Set the textarea's value to a Template Literal with
|| interpolated values from the student Object.
*/
view.value += `
First: ${student.First}
Last.: ${student.Last}
CRN..: ${student.CRN}
Prof.: ${student.Prof}
~~~~~~~~~~~~~~~~~~~`;
// Otherwise quit
} else {
return false;
}
}
input,
label {
font: inherit;
display: inline-block;
}
label {
width: 20%
}
[type=text] {
width: 75%;
}
[type=reset] {
margin: 5px 0 0 85%;
}
<!DOCTYPE html>
<html lang=”en”>
<head>
<title></title>
</head>
<body>
<form id="registration">
<fieldset id='set0'>
<legend>Registration</legend>
<label>First Name: </label>
<input type="text" name="first" size="10" /><br>
<label>Last Name: </label>
<input type="text" name="last" size="10" /><br>
<label>CRN: </label>
<input type="text" name="crn" size="10" /><br>
<label>Professor: </label>
<input type="text" name="prof" size="10" /><br>
<input type="reset" name="add" value="Submit">
</fieldset>
</form>
<form id='display'>
<fieldset id='set1'>
<legend>View Data</legend>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</fieldset>
</form>
</body>
</html>

Cannot validate user input correctly from server?

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.

how do i clone a multiple html input field with jquery

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)

How to validate a form in jsp using javascript before submit

<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>

Categories