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>
Related
Im trying this for so long and i dont know how to fix it. The idea is simple, The user insert the requiered data in the HTML forms, then the inserted data is stored in an array and display all the data with a text. I think the problem is when i try to store the data from the form into the array.
This is what ive done so far
<html>
<header>
<meta charset="UTF-8">
<title>Second Homework</title>
</header>
<body>
<h1>Welcome!</h1>
<p>Please insert the data in the following form: </p>
<form>
<input type="text" id="name"><br>
<input type="text" id="lname"><br>
<input type="text" id="age"><br>
<input type="text" id="city"><br>
<input type="text" id="pet"><br>
<input type="text" id="pet_name"><br>
<button type="button" id="" onclick="data()">Enviar</button>
</form>
<script type="text/javascript">
function data(){
var info=[getElementById("name").innerHTML.value,getElementById("lname").innerHTML.value,
getElementById("age").innerHTML.value,getElementById("city").innerHTML.value,getElementById("pet").innerHTML.value,getElementById("pet_name").innerHTML.value]
document.write("Your name is: "+info[0])
document.write("Your lastname is: "+info[1])
document.write("You are "+info[2]+" years old")
document.write("You live in: "+info[3])
document.write("Do you have pets? "+info[4])
document.write("Your pets name is: "+info[5])
}
</script>
</body>
<footer>
</footer>
</html>
in HTML, form inputs elements must use a name attribute
do this way:
const myForm = document.forms['my-form']
myForm.onsubmit = e =>
{
e.preventDefault() // disable submit
let info = Array.from(new FormData(myForm).entries()).map(([k,v])=>v)
document.write("<br>Your name is: "+info[0])
document.write("<br>Your lastname is: "+info[1])
document.write("<br>You are "+info[2]+" years old")
document.write("<br>You live in: "+info[3])
document.write("<br>Do you have pets? "+info[4])
document.write("<br>Your pets name is: "+info[5])
/* ------------------------------- or
let msg = `
Your name is: ${myForm.name.value}
Your lastname is: ${myForm.lname.value}
You are ${myForm.age.value} years old
You live in ${myForm.city.value}
Do you have pets? ${myForm.pet.value}
Your pets name is: ${myForm.pet_name.value}`
console.log( msg )
------------------------------------- */
}
<h1>Welcome!</h1>
<p>Please insert the data in the following form: </p>
<form name="my-form">
<input type="text" name="name" placeholder="name" ><br>
<input type="text" name="lname" placeholder="last name"><br>
<input type="text" name="age" placeholder="age" ><br>
<input type="text" name="city" placeholder="city" ><br>
<input type="text" name="pet" placeholder="pet" ><br>
<input type="text" name="pet_name" placeholder="pet name" ><br>
<button type="submit">Enviar</button>
</form>
So I'm having trouble with JS and how to correctly collect and pass all values from a text field and hidden field on a button click.
<input autocomplete="off" id="add_109_01000340002001010_id" name="add_109_01000340002001010[id]" type="hidden" value="113000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001010_name" name="add_109_01000340002001010[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001009_id" name="add_109_01000340002001009[id]" type="hidden" value="112000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001009_name" name="add_109_01000340002001009[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001021_id" name="add_109_01000340002001021[id]" type="hidden" value="11405181">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001021_name" name="add_109_01000340002001021[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
Those are text fields and hidden fields with unique ids. They are 'connected'. When you change the value in the text field, the value in the hidden field changes automatically.
When you click on a button, then values that will be written in the text field should be processed in js
function room_group() {
$('.add').bind('click', function() {
var hidden_values = 'something here' // Let's get all values here and pass them to the get request
var values = 'something here' // Let's get all values here and pass them to the get request
$.post('/link/definition', {
val: values,
hidden_val: hidden_values
},
function(response) {
location.reload();
}
);
});
}
The question is how to collect all of those values correctly? Unfortunately, I have no idea...
It depends on how you want to format your values.
You can serialize the values by searching for them with an appropriate selector and then you can create a JSON string as value.
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
console.log(hiddenValues);
console.log(textValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="h1" name="hidden1" />
<input type="hidden" value="h2" name="hidden2" />
<input type="text" value="t1" name="text1" />
<input type="text" value="t2" name="text2" />
Your POST will be something similar to:
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
$.post('/link/definition', {
val: textValues,
hidden_val: hiddenValues
},
function(response) {
location.reload();
}
);
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)
What im trying to do is create a webform that will take the information put into the fields to add to a predefined text. the code I have so far is as follows:
<form action="" method="post">
<input type="reset" value="Clear">
<p>
<input type="text" name="casenumber" value="Case Number" onclick="this.select()" size="25"/>
</p>
<p>
<input type="text" name="name" value="Name" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="dealer code" value="Dealer Code" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="cid" value="CID" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="callback" value="Callback#" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="authentication" value="Dealer Authentication" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="email" value="Email" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="ptn" value="PTN" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="ban" value="BAN" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="banauth" value="Ban Authentication" onclick="this.select()" size="25" />
</p>
<p>
<input type="text" name="type" value="Type of Request" onclick="this.select()" size="25" />
</p>
<p>
Actions Taken:<br/>
<textarea name="actions" rows="5" cols="50"></textarea>
</p>
<p>
<input type="submit" value="Submit" />
</p>
Now I want all of the information entered into these fields to be added to this
SFDC - TSO Case number: input inserted here
Dealer Name: input inserted here
Dealer code: input inserted here
CID: input inserted here
Callback#: input inserted here
Dealer Authentication: input inserted here
Email: input inserted here
PTN#: input inserted here
BAN: input inserted here
BAN Authentication: input inserted here
Type of Request: input inserted here
Actions Taken: input inserted here
Have not been able to find how to do this so any help is appreciated.
Try the following javascript function which is using the placeholder attribute to generate the titles of values for the text generated:
/**
* fId: the form id
* dId: the div id which want to add the text to it
**/
function printToDiv(fId, dId){
f = document.getElementById(fId);
i = f.getElementsByTagName('input');
iTxt = Array();
k = 0;
out = '';
for (j = 0; j < i.length; j++){
if (i[j].type == 'text'){
iTxt[k] = i[j];
k++;
}
}
for (n =0; n < iTxt.length; n++){
out += "<b>"+iTxt[n].placeholder+":</b> "+iTxt[n].value+"<br />\n";
}
div = document.getElementById(dId);
div.innerHTML = out;
}
A generalized DEMO could be found here or here. Ofcourse you can apply any validation for the data by calling any other function inside the regarded function and you can call it by any way you want, for example, from onsubmit event.
I think that you have to use a placeholder.
Look:
http://www.w3schools.com/tags/att_input_placeholder.asp
Exercise:
<form action="" method="POST">
<input type="text" name="X" placeholder="Some text..." />
</form>
If you don't care about language this could be easily done with JavaScript. Just add the class to all your inputs and add a span next to your defined text
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<input id='txtCaseNumber' class="copyValue" placeholder="case number"/>
<input id='txtDealer' class="copyValue" placeholder="Dealer Name"/>
Case Number: <span data-inputId="txtCaseNumber"></span>
Dealer Name: <span data-inputId="txtDealer"></span>
<script>
$(document).ready(function(){
$(".copyValue").blur(function(){
var inputId = $(this).attr('id');
var ident = "span[data-inputId='" + inputId + "']";
$(ident).html($(this).val());
});
});
</script>
</body>
</html>
If I am understanding your question correctly. You could do something like this. But this is not the only way, it is just a way.
Sample HTML:
<div class="container">
<input type="text" value="something"/>
<input type="text" value="something"/>
<input type="submit" value="submit" id="submit"/>
</div>
<div id="output"></div>
JS:
var a = [
"SFDC - TSO Case number:",
"Dealer Name:",
"Dealer code:",
"CID:",
"Callback#:",
"Dealer Authentication:",
"Email:",
"PTN#:",
"BAN:",
"BAN Authentication:",
"Type of Request:",
"Actions Taken:"
];
var values = [];
$("#submit").on('click', function()
{
var form = $('.container');
var inputs = form.find('input').not('.exclude'); // add this class to the inputs you don't want to collect the values of, IE clear and submit
var l = inputs.length;
var html = '';
for(var i = 0; i < l; i++)
{
var value = inputs.eq(i).val();
values.push(value);
}
for(var i = 0, ln = a.length; i < ln; i++)
{
html += '<p>' + a[i] + ' ' + values[i] + '</p>';
}
$('#output').append(html);
});
Note: I used jQuery for this example and cleaned up / changed the HTML a bit.
Demo:
http://jsfiddle.net/prb75qvt/4/
If I understand you correctly, you want to take an text fron an input box and paste it somewhere else. Use this code template :
HTML CODE
(The onchange is optional, I just like to use it because it activates a function when the text changes)
<input id="newText" type="text" onchange="myFunction()">
<p>Your text</p><p id="oldText"></p>
JS CODE
("oldText" is used as a placeholder)
function myFunction() {
var inputText = document.getElementById("newText").value;
document.getElementById("oldText").innerHTML = inputText
}
<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>