Learning Javascript and trying to work out the best way to validate a text and number fields on a form.
I have the following html form:
> <form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br>
<input class="input input1" type="text" id="setName" name="setName" value=" ">*<br>
<label for="setTheme">Set Theme</label><br>
<input class="input input1" type="text" id="setTheme" name="setTheme" value=" "><br>
<label for="setReferenceNumber">Reference Number</label><br>
<input class="input input1" type="number" id="setReferenceNumber" name="setReferenceNumber" value="0">*<br>
<label for="setPieceCount">Piece Count</label><br>
<input class="input input1" type="number" id="setPieceCount" name="setPieceCount" value="0">*<br>
<br>
<input class="input input2" type="button" value="Save Set" onclick="captureLegoSets.captureSets()">
<input class="input input2" type="reset" value="Reset Values">
</form>
And attached Javascript (forgive the numerous console.log statements):
this.captureSets = function(){
let setName = " ";
let setTheme = " ";
let setReferenceNumber = 0;
let setPieceCount = 0;
let formFields = document.querySelectorAll(".input1");
console.log(formFields);
for (let i=0; i < formFields.length; i++) {
console.log(formFields[i]);
console.log(formFields[i].id);
console.log(formFields[i].value);
if ((+document.getElementById(formFields[i].id).value) > 0 | (+document.getElementById(formFields[i].id).length) !== null) {
console.log(formFields[i].id + " = " + formFields[i].value);
if(formFields[i].id === "setName"){
setName = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = +document.getElementById(formFields[i].id).value;
}
console.log(formFields);
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
}
The problem I'm experiencing if that the else statement keeps triggering for the text fields if I only check the .value, but if I check the .length, it doesn't trigger at all.
I know I could probably put together a bunch of if statements to check for null, empty and so on, but I'm assuming this would just be poor coding on my part. Is there a better/more concise way of checking for valid inputs?
First you have provided default values to all your text fields, which let the following if check resulting in true, since you have provided default values as " " ( " " is not a null )
if ((document.getElementById(formFields[i].id).value > 0) || (document.getElementById(formFields[i].id).length !== null))
In the above expression you have used !== instead of !=
You used | not || for or operation
Remove + before document ( I don't understand why you have added those. Please explain
Hence,
remove default values / check for right conditions in the conditional statements,
use a p tag to display all the errors in the bottom. I have provided a simple example of concatenating the errors, you can also use an array to collect the errors. In the best case a separate error text right below each text field is awesome.
HTML
<form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br />
<input
class="input input1"
type="text"
id="setName"
name="setName"
/>*<br />
<label for="setTheme">Set Theme</label><br />
<input
class="input input1"
type="text"
id="setTheme"
name="setTheme"
/><br />
<label for="setReferenceNumber">Reference Number</label><br />
<input
class="input input1"
type="number"
id="setReferenceNumber"
name="setReferenceNumber"
/>*<br />
<label for="setPieceCount">Piece Count</label><br />
<input
class="input input1"
type="number"
id="setPieceCount"
name="setPieceCount"
/>*<br />
<br />
<input
class="input input2"
type="button"
value="Save Set"
onclick="captureSets()"
/>
<input class="input input2" type="reset" value="Reset Values" />
</form>
<p id="error-text"></p>
JS
captureSets = function () {
let setName = "";
let setTheme = "";
let setReferenceNumber = 0;
let setPieceCount = 0;
let errorText = "";
let formFields = document.querySelectorAll(".input1");
for (let i = 0; i < formFields.length; i++) {
if (
(document.getElementById(formFields[i].id).value > 0) ||
(document.getElementById(formFields[i].id).length != null)
) {
if (formFields[i].id === "setName") {
setName = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = document.getElementById(
formFields[i].id
).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = document.getElementById(formFields[i].id).value;
}
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
if (!setName || setName == "") {
errorText += " Fill the name text field <br>";
}
if (!setPieceCount) {
errorText += " Fill the piece count text field <br>";
}
if (!setTheme || setTheme == "") {
errorText += " Fill the theme text field <br>";
}
if (!setReferenceNumber) {
errorText += " Fill the reference number text field <br>";
}
document.getElementById("error-text").innerHTML = errorText;
};
This may or may not help you, but I think, this is easier for you to check this directly by pattern attribute. You just need to put some regex.
An HTML form with an input field that can contain only three letters (no numbers or special characters):
<form>
<label for="country_code">Country code:</label>
<input
type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}"
title="Three letter country code">
</form>
https://www.w3schools.com/tags/att_input_pattern.asp
Related
I have the following html and javascript code for validation on the input fields, this was working with the one input field for first name but since I tried to extend my code by adding a new input field for last name now the form validation has stopped working as follows:
function myFunction() {
let x = document.getElementsByName("first_name").[0]value;
let y = document.getElementsByName("last_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
if (y == '' || y == null) {
text = "Input not valid";
}
document.getElementById("last_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
document.getElementsByName("last_name").focus();
};
})(), true);
</head>
<body>
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<br><br>
<input type="text" name="last_name" placeholder="last name" name class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="myFunction()">
How can I get this back working with the extra input field last name added? Thanks in advance
there are many errors here. you may find them by your own by debugging your console.log
error, at let x = document.getElementsByName("first_name").[0]value;
there are a to many }
eventlisteners need to be on the input and shouldn't be inside the check function
there are empty name attributes on your inputs
fixing it blind it would be something like:
let firstName = document.getElementsByName('first_name')[0];
let lastName = document.getElementsByName('last_name')[0];
function checkValid() {
let x = firstName.value;
let y = lastName.value;
let text;
text = '';
if (x == '' || x == null) {
text = 'Input not valid';
}
document.getElementById('first_name_errors').innerHTML = text;
if (y == '' || y == null) {
text = 'Input not valid';
}
document.getElementById('last_name_errors').innerHTML = text;
}
firstName.addEventListener('invalid', function () {
firstName.focus();
});
lastName.addEventListener('invalid', function () {
lastName.focus();
});
<input type="text" name="first_name" placeholder="first name" class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="checkValid()">
<br><br>
<input type="text" name="last_name" placeholder="last name" class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="checkValid()">
I am making a "subscribe to my newsletter" form and I am using a clothing website as a reference https://www.emibeachwear.com.br/ (You will find the form on the footer of the website)
On the footer there is this input called "data de aniversário" or "birthdate" if you translate it to English.
Using chrome inspect element I saw that it is a Text input. Even though it is a text it still formats as a date.
How do I do that? Should I use javascript? If so, how?
Here is what I have now:
<div class="newsletter" style="background:transparent; color:white;">
<label class="email"> E-MAIL
<input class="caixa" type="email" name="EMAIL" placeholder="E-MAIL" style="border:0;"required />
</label >
<label class="aniversario"> DATA DE ANIVERSÁRIO
<input class="caixa" type="date" placeholder="DATA DE ANIVERSÁRIO" style="border:0;" max-length="10" required />
</label>
<input class="cadastrar caixa" type="submit" value="CADASTRAR" style="border:0;"/>
</div>
Here's one way:
const input = document.querySelector('input');
input.addEventListener("input", function() {
input.value = input.value.replace(/\D/g, "");
var s = input.value.replaceAll("/", "").match(/.{1,2}/g);
if (s != null) {
var len = s.length;
input.value = s.join("/");
if (len > 3) {
var l = input.value.lastIndexOf('/');
input.value = input.value.substring(0, l) + input.value.substring(l + 1);
}
}
})
<input type="text" maxlength="10">
I am currently working with forms and javascript validation.. i have completed most of my code and am on the last step however cant seem to get it working and not sure what ive done wrong.. spent hours on this last part before i looked for help.
basically a user inputs their information into a form and then when they click submit the information get validated, and the inputed info moves onto a confirmation page.. at the moment the input i put in doesnt get validated anymore and is blank in the confirmation page..
First HTML register page
<form id="regform" method="post" action="confirm.html"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize" maxlength="3"
size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
Validation for Javascript
function validate() {
var errMsg = "";
var result = true;
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha characters\n";
result = false;
}
if (!lastname.match(/^[a-zA-Z+$]/)) {
errMsg = errMsg + "Your last name must only contain alpha characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (age < 18) {
errMsg = errMsg + " your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
else {
var tempMsg = checkSpeciesAge(age);
if (tempMsg != "") {
errMsg + tempMsg;
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (partySize < 1) {
errMsg = errMsg + " party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
}
var is1day = document.getElementById("1day").checked;
var is4day = document.getElementById("4day").checked;
var is10day = document.getElementById("10day").checked;
if (!(is1day || is4day || is10day)) {
errMsg = errMsg + "please select at least one trip.\n";
result = false;
}
if (document.getElementById("food").value == "none") {
errMsg = errMsg + "You must select a food preference. \n ";
result = false;
}
var human = document.getElementById("human").checked;
var dwarf = document.getElementById("dwarf").checked;
var elf = document.getElementById("elf").checked;
var hobbit = document.getElementById("hobbit").checked;
if (!(human || dwarf || elf || hobbit)) {
errMsg = errMsg + "please select a spiecies";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
if (result) {
storeBooking(firstname, lastname, age, species, is1day, is4day, is10day);
}
return result;
}
function getSpecies() {
var speciesName = "Unknown";
var speciesArray = document.getElementById("species").getElementsByTagName("input");
for (var i = 0; i < speciesArray.length; i++){
if (speciesArray[i].checked)
speciesName = speciesArray[i].value;
}
return speciesName;
}
function checkSpeciesAge(age) {
var errMsg = "";
var species = getSpecies();
switch(species){
case "human":
if (age > 120) {
errMsg = "you cannot be a Human and over 120. \n";
}
break;
case "dwarf":
case "hobit":
if (age > 150 ){
errMsg = " YOu can not be a " + species + " and over 150 .\n ";
}
break;
case "elf":
break;
default:
errMsg = " we dont allow your kind on our tours. \n";
}
return errMsg;
}
function storeBooking(firstname, lastname, age, species, is1day, is4day, is10day){
var trip= "";
if(is1day) trip ="1day";
if(is4day) trip +=", 4day";
is(is10day) trip += ", 10day";
sessionStorage.trip = trip;
sessionStorage.firstname= firstname;
sessionStorage.lastname= lastname;
sessionStorage.age = age;
sessionStorage.species= species;
sessionStorage.partySize= partySize;
sessionStorage.food = food;
alert ("Trip stored: " + sessionStorage.trip);
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
Confirm HTML
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking" />
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
Javascrips file 2 to bring the info over to the confirmation
function validate(){
var errMsg = "";
var result = true;
return result;
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function getBooking(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
There are a couple of syntax errors that should be clearly visible when you open your browser console:
- errMsg + tempMsg; is not a complete statement,
- is(is10day) trip += ", 10day"; is not valid, and
- storeBooking doesn't have a parameter called partySize
I see a couple of logic errors too:
- checkSpeciesAge will never return an empty string as validate expects, and
- the section of code that attempts to validate partySize has several errors (including that this entire structure is nested inside the age-validation section's else block.)
A few console.log statements could go a long way toward identifying where your variables contain values that you don't expect if there are still bugs to track down after correcting these issues. Good luck!
I tried to fix this, and make some changes in your code. according to your requirement
follow the link of jsfiddle; https://jsfiddle.net/dupinderdhiman/vno15jku/32/
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking"/>
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
<script>
sessionStorage.trip = "4day";
sessionStorage.firstname= "firstname";
sessionStorage.lastname= "lastname";
sessionStorage.age = 21;
sessionStorage.species= "species";
sessionStorage.partySize= 10;
sessionStorage.food = "food";
function validate(){
var errMsg = "";
var result = true;
return result;
}
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function loadDataFromSession(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
loadDataFromSession();
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
</script>
so what is the major change:
Created one function loadDataFromSession which call on init();
remove code from getBooking() add to loadDataFromSession.
now click on submit and your form will be submit
So I have this piece of HTML and JavaScript
function validate() {
const tabs = document.getElementsByClassName("tab");
const input = tabs[currentTab].querySelectorAll("input[type=tel], input[type=text], input[type=time], input[type=number], input[type=email]");
const radio = tabs[currentTab].querySelectorAll("input[type=radio]");
const select = tabs[currentTab].getElementsByTagName("select");
let valid = true;
if (radio.length == 0) {
for (let i = 0; i < input.length; i++) {
if (input[i].value == "") {
valid = false;
break;
}
}
for (let i = 0; i < select.length; i++) {
if (select[i].value == "") {
valid = false;
break;
}
}
} else if (radio[0].name == "phnum" && radio[0].checked) {
if (input[0].value == "" || input[1].value == "") {
valid = false;
}
} else if (radio[1].name == "phnum" && radio[1].checked) {
if (input[0].value == "" || input[1].value == "" || input[2].value == "") {
valid = false;
}
}
if (valid) {
document.getElementById("next").className = "prevNext";
}
}
<span id="radio">
<label for="phnum1" class="radio-container">
<input type="radio" name="phnum" id="phnum1" value="1" onchange="displayPhone(this);">1 Number
<span class="radio"></span>
</label>
<label for="phnum2" class="radio-container">
<input type="radio" name="phnum" id="phnum2" value="2" onchange="displayPhone(this);">2 Numbers
<span class="radio"></span>
</label>
<label for="phnum3" class="radio-container">
<input type="radio" name="phnum" id="phnum3" value="3" onchange="displayPhone(this);">3 Numbers
<span class="radio"></span>
</label>
</span>
</p><br>
<p id="ph1" class="disable">
<label for="phone-number1">Add a Phone Number: </label><input type="tel" name="phone-number1" id="phone-number1" class="input" placeholder="Add A Phone Number" required oninput="validate();">
</p>
<p id="ph2" class="disable">
<label for="phone-number2">Add a Phone Number: </label><input type="tel" name="phone-number2" id="phone-number2" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
<p id="ph3" class="disable">
<label for="phone-number3">Add a Phone Number: </label><input type="tel" name="phone-number3" id="phone-number3" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
that handles the input added by the user to make a button clickable if all necessary data is added. the problem is when i delete inside the input with back arrow key(the one above enter) the button remains active even if the condition for its activation no longer applies.
thank you guys for your time and help i really do appreciate it. :D
One thing I see - you're setting the class name if valid == true via document.getElementById("next").className = "prevNext";.
But nowhere are you removing that class name if valid == false.
That's probably why you aren't seeing the button disappear when you empty out the fields (if I understand your problem correctly).
if (!valid) { document.getElementById("next").className = ""; } is a quick and dirty way to get what you need.
I have a form that has several fields. The first field is called subject. What I want to do is disable the ability for the user to type in the field, but it still show, and the text they enter into three other fields show up with spaces between the variables in the first field. Example: In this scenario: "Second_Field: John" "Third_Field: Doe" "Forth_Field: New part" then on first field, subject, it will show: John Doe New Part
Thanks for any help.
You can try the following:
<!-- HTML -->
<input type="text" id="subject" disabled="disabled">
<input type="text" id="field1">
<input type="text" id="field2">
<input type="text" id="field3">
// JavaScript
var fields = [];
for (var i = 1; i <= 3; i++) {
fields.push(document.getElementById("field" + i).value);
}
document.getElementById("subject").value = fields.join(" ");
Try this:
<script>
function UpdateText()
{
document.getElementById("subject").value =document.getElementById("Field1").value + " " + document.getElementById("Field2").value + " " + document.getElementById("Field3").value;
}
</script>
<input type="text" id="subject" disabled="disabled"/>
<input type="text" id="Field1" onchange="UpdateText()";/>
<input type="text" id="Field2" onchange="UpdateText()";/>
<input type="text" id="Field3" onchange="UpdateText()";/>
HTML:
<form>
<p><input id="subject" name="subject" disabled size="60"></p>
<p><input id="Second_Field" class="part">
<input id="Third_Field" class="part">
<input id="Fourth_Field" class="part"></p>
</form>
JavaScript:
var updateSubject = function() {
var outArray = [];
for (var i=0;i<parts.length;i++) {
if (parts[i].value !== '' ) {
outArray.push(parts[i].value);
}
}
document.getElementById('subject').value = outArray.join(' ');
};
var parts = document.getElementsByClassName('part');
for (var i=0;i<parts.length;i++) {
parts[i].onkeydown = updateSubject;
}