Text Box Validation with javascript - javascript

Have text box a and if it is filled in make sure text box b is filled in also when doing a submit and vice a versa if box b is filled in make sure a has data also in it. Can this be looped to check many text boxes that if the row a of text boxes has data check 2nd row of text boxes also have data in the ones that row a has. All the text boxes in row a don't need to be filled in. Thanks.

Your question is a bit hard to understand; it'd be helpful if you could better explain what you actually want. You don't need to have any conditions; just do the following:
<script>
function checkForm() {
if (!isEmpty(document.myForm.checkA.value)
&& !isEmpty(document.myForm.checkB.value))
return true;
else
return false;
}
function isEmpty(text) {
return text.length == 0 || !text.match(/[^\s]/))
}
</script>
<form name="myForm" onSubmit="return checkForm();">
<input name="textA" type="text" />
<input name="textB" type="text" />
<input type="submit" value="Submit!" />
</form>

This should be straightforward if you use an array to hold references to your text boxes. For example (off the top of my head so this is not going to be 100% right), let's say you have 5 across and 3 down:
var col = new Array(5);
var row = new Array(3);
col[0] = document.myForm.checkA1;
col[1] = document.myForm.checkB1;
// etc
row[0] = col;
col = new Array(5);
col[0] = document.myForm.checkA2;
col[1] = document.myForm.checkB2;
// etc
row[1] = col;
col = new Array(5);
col[0] = document.myForm.checkA3;
col[1] = document.myForm.checkB3;
// etc
row[2] = col;
You can now loop over the array in row[0] and if you find, e.g., that row[0][2] has text you just need to verify that row[1][2] also has text.

Related

Trying To Move Input Element to Another Div

I am creating a form that shows one question at a time. I would like to show all questions, though, on a different view when "View Complete Form" is clicked. The problem I am having is showing the questions in said form. There's no issue with the single view questions.
I am able to display the value, on said form but I cannot actually enter anything. That's not what I want.
Ex. in case any one is confused:
(In single view)
Question 1: (input box) Answer 1
(In full view)
Question 1: Answer 1 (All text, no input boxes)
I would like to do:
(In single view)
Question 1: (input box) Answer 1
(In full view)
Question 1: (input box) Answer 1
Like I said, I see how I can get the value (I used answer[i-1] = document.getElementById(i-1).value) then I print the answer BUT WITHOUT THE INPUT BOX.
I realized my mistake so I tried document.getElementById(x) which gives me [object HTMLInputElement]. Again, I just want the input box with the answer already filled in IF it's filled on the single view.
Did some searching on here and tried to use appendTo, descendants and appendChild (object does not support these) but nothing helped.
html
<div id="questionnaire-question">Click 'Start' to begin...</div>
<div id="input-questionnaire">
<input type='text' class='form-control' name='reqEng' id='1' style="display:none" placeholder="Requesting Engineer" required>
</div>
<button id="view-form" onclick="viewForm()">View Complete Form</button>
<form id="full-form" style="display:none">
<div id="full-form-question"></div>
<input type="reset" name="reset" value="Reset Fields">
<input type="submit" name="submit" id="submitQuestionnaire" value="Submit Questionnaire">
</form>
</div>
js
function viewForm() {
for (var x = 0; x < 44; x++) {
//form.appendChild(document.getElementById(x)); // Didn't work
//form.insert(document.getElementById(x).descendants()[x]); // Not supported
//document.getElementById(x).style.display = "block"; // Loop for questions and answers to populate
//document.getElementById(x+1).appendTo(form);
//fullForm.innerHTML += questions[x]+ ": " + answer[x+1] + " <br>";
fullForm.innerHTML += questions[x] + ": " + document.getElementById(x + 1) + " <br>";
}
}
This is what I want (from a previous form. I populated the inputs in an array but found it easier with some functionalities if I had just hard coded it)
https://imgur.com/cgarzSd
This is what I currently have :
https://imgur.com/Uj4FlvZ
Your question could possibly use some clarification, however I am taking a stab at it hoping that we can get you on the right track.
Below is an example of simply moving the input from one div to another:
function viewForm(){
//gets all of the inputs held in the "input-questionnaire" div
var inputs = document.getElementById('input-questionnaire').getElementsByTagName('input');
//loop through the collection of inputs
for(var i = 0;i < inputs.length; i++)
{
//if you want to ensure input is no longer hidden when moved
//inputs[i].style.display = "block";
//move the element to the new div
document.getElementById("full-form-question").appendChild(inputs[i]);
}
//probably want to show the hidden form at this point
document.getElementById("full-form").style.display = "block";
}
Here is another option if you actually want to "copy" the input to the new div:
function viewForm(){
//gets all of the inputs held in the "input-questionnaire" div
var inputs = document.getElementById('input-questionnaire').getElementsByTagName('input');
//loop through the collection of inputs
for(var i = 0;i < inputs.length; i++)
{
//clone the current input
var clone = inputs[i].cloneNode();
//make sure the question is visible?
clone.style.display = "block";
//append the clone to your "full-form-question" div
document.getElementById("full-form-question").appendChild(clone);
}
//probably want to show the hidden form at this point
document.getElementById("full-form").style.display = "block";
}
Hope this helps. Cheers!
Here's a basic example of how you can "move" input elements from one form to another. In reality you're making a copy of it and removing the old one from the previous form.
It looks like the main problem you're having is that you're not defining the form.
Take a look at how you could go about it:
function viewForm() {
const form1 = document.getElementById('form-1')
const form2 = document.getElementById('form-2')
for (var x = 1; x <= 1; x++) {
let input = document.getElementById(x)
form1.remove(input)
form2.append(input);
const span = document.createElement('span');
span.innerText = `${x} is now in form2`
form2.appendChild(span)
}
}
document.getElementById("btnMove").addEventListener('click', viewForm);
<div>
Form 1
<form id="form-1">
<input type='text' class='form-control' name='reqEng' id='1' placeholder="Requesting Engineer" required>
</form>
</div>
<div>
Form 2
<form id="form-2">
</form>
</div>
<input type="button" id="btnMove" value="move input">

Adding form post/submit button to javascript script

I found this code on here (thanks to Xavi López) and it is ideal for what I need to add to my project but I'm in need of some help adding a Form post and submit button in JavaScript. I have no knowledge on this subject and I've tried looking at some example but non of them seem to work. I would be grateful if someone could help me. After the user adds the relevant number of input boxes and adds there data, I would like to have a submit button which will POST the results to another web page (result page)
I have added the solution to the below coding (thank you MTCoster) but I'm now try to find a solution to having the submit button appear only when an entry has been added. I have tried different methods but non will work.
function addFields() {
// Number of inputs to create
var number = document.getElementById('member').value;
// Container <div> where dynamic content will be placed
var container = document.getElementById('container');
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
// Append a node with a random text
container.appendChild(document.createTextNode('Member ' + (i + 1) + ' '));
// Create an <input> element, set its type and name attributes
var input = document.createElement('input');
input.type = 'text';
input.name = 'member' + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement('br'));
}
}
<input type="text" id="member" name="member" value="">Number of Pins: (max. 48)<br>
Add Pinout Entries
<form action="result.asp" method="POST">
<div id="container"></div>
<input type="submit" value="Add Data">
</form>
You’re almost there - all you need to do is wrap your inputs in a <form> element:
function addFields() {
// Number of inputs to create
var number = document.getElementById('member').value;
// Container <div> where dynamic content will be placed
var container = document.getElementById('container');
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
// Append a node with a random text
container.appendChild(document.createTextNode('Member ' + (i + 1) + ' '));
// Create an <input> element, set its type and name attributes
var input = document.createElement('input');
input.type = 'text';
input.name = 'member' + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement('br'));
}
}
<input type="text" id="member" name="member" value="">Number of Pins: (max. 48)<br>
Add Pinout Entries
<form action="/url/to/post/to" method="POST">
<div id="container"></div>
<input type="submit">
</form>
If you’d like the submit button to only appear after at least one input is visible, you could add it at to div#container at the end of addFields(). I’ll leave this as an exercise to the OP, since it’s not much different to how you’re adding the input fields.

How to save the values in existing input fields when adding a new one?

This is what my program's body looks like:
<form id = "input">
<input id = "0" >
</form>
<p onclick = "add()"> Add Another</p>
And on clicking the above The following function is executed:
var inputArea = document.getElementById("input");
next = 1;
function add(){
inputArea.innerHTML+= " <input id = " + next+ ">" ;
Where next is the id of new input field. In this case, since 0 already exists so value of next is 1.
One problem that I am encountering with this is that after adding a new input field, the values in all existing input fields are lost. How to save these values? My attempt is to place this code in function add():
for (i=0;i<next;i++)
{inputs[i] = document.getElementById(i);
inputV[i]= inputs[i].value;
inputs[i].value = inputV[i];}
But this does not works..
var inputArea = document.getElementById("input");
next = 1;
function add(){
inputArea.innerHTML+= " <input id = " + next+ ">" ;
var inputs = new Array();
var inputV = new Array();
for (i=0;i<next;i++)
{inputs[i] = document.getElementById(i);
inputV[i]= inputs[i].value;
inputs[i].value = inputV[i];}
next++;
}
<form id = "input">
<input id = "0" >
</form>
<p onclick = "add()"> Add Another</p>
You may want to dynamically add elements to your DOM tree like so
function add() {
var form = document.getElementById("input");
var input = document.createElement("input");
form.appendChild(input);
}
The problem with what you're doing is that when you write inside an input field, the changes are not represented in the HTML code, only in the memory of the browser. Thus if you add text through to code to form.innerHTML, the browser is going to reinterpret the text inside the form which will be
<input id="0"> <input id="1"> ...
and this will result in two empty input of type text being displayed.
Edit: you can then add your id tag via
function add() {
var form = document.getElementById("input");
var input = document.createElement("input");
input.id = someValue;
form.appendChild(input);
}
N.B. please indent your code in a somewhat logical manner.
The reason this is happening is that the dom, or more specifically inputArea's innerHtml doesnt get changed when you type into a form field. And what youre doing is resetting the innerHTML with a blank input BEFORE youre capturing the values.
so whats going on is you have HTML like this:
<input id='0' />
then type into the form so that it behaves like:
<input id='0' value='foo' />
but thats not what the innerHTML actual is. its still <input id='0' /> because the value is kept in memory not on the dom.
if you want to add new elements to the form, you need to use appendChild instead
so convert
inputArea.innerHTML+= " <input id = " + next+ ">"
to
inputArea.appendChild(document.createElement('input'))

Skip field if empty

I have 4 fields that can be filled in by end user. I would like to send the contents of these in an email but I don't want blank spaces in the email. What I am looking for is a way to ignore those empty field and only return those that have value. I have this piece of code but it only ever returns the last value :
var Textbox = Browser.getValue("myTextBox");
var Field1 = Browser.getValue("myField1");
var Field2 = Browser.getValue("myField2");
var Field3 = Browser.getValue("myField3");
var Field4 = Browser.getValue("myField4));
if (Field1 != "" ){
Browser.setValue(TextBox), (Field1 += "\n" + Textbox));
}
if (Field2 != ""){
Browser.setValue(Textbox), (Field2 += "\n" + Textbox));
}
if (Field3 != ""){
Browser.setValue(Textbox), (Field3 += "\n" + Textbox));
}
if (Field4 != ""){
Browser.setValue(Textbox), (Field4 += "\n" + Textbox));
}
Can anyone help me? I basically need that the Textbox after each statement in updated and used in the next using just Javascript.
Thank you in advance
You seem to be trying to do something like the following. It goes over all the controls in the form and gets all the values that aren't the initial value and writes them to the textarea on new lines.
<script>
// Collect all the non–default values in the form and write
// on new lines to the text area
function consolidateValues(form) {
// Get the textarea to write values to
var textArea = form.myTextBox;
// Get all controls in the form
var control, controls = form.elements;
// Variable to hold the consolidated value
var text = [];
// Collect all the values, skipping the first control
for (var i=1, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.value != control.defaultValue) {
text.push(control.value);
}
}
// write the value to the text area
textArea.value = text.join('\n');
// Stop form from submitting
return false;
}
</script>
<form onsubmit="return consolidateValues(this)">
<textarea name="myTextBox" size="100" rows="10"></textarea>
<br>
<input name="myField1">
<br>
<input name="myField2">
<br>
<input name="myField3">
<br>
<input name="myField4">
<br>
<input type="submit"> <input type="reset">
</form>

Populating a textarea from several textfields

I have several textfields which will populate a text area.
I managed to populate it with a javascript function. On the onblur event of a textfield, the value of the textfield is passed and the textarea is field with this value.
However, my problem is the following:
If I modify a previously filled textfield, the textarea will simply append it again.
What I need is some functionality that if:
1: If I give focus to the textfield which is already been filled and I don't modify it, it will not be appended (I implemented this with an if statement and substring.
2: If I modify a previously filled textfield, the text area DOES NOT append it again at the end of the string BUT it replaces the part of the textarea with just that text field new value.
Take for instance the following 2 textfields:
<input type="text" id="txtName" name="txtName" />
<input type="text" id="txtSurname" name="txtSurname" />
If I fill up these textfields with John and Doe respectively, the textarea value will become:
txtName=John,txtSurname="Doe"
I managed to implement this.
What I need is that if I edit txtName from John to Alex, the textarea value will be as follows:
txtName=Alex,txtSurname=Doe
and not like is currently being displayed, i.e.
txtName=John,txtSurname=Doe,txtName=Alex
Should I achieve this by using an array which will store all the textfields values?
Any help would be greatly appreciated.
Many thanks in advance.
the following code should work for you. I have wrapped the textboxes inside a div. and also registered a onkeyup event on both the textboxes.
The javascript code iterates through each textboxe inside the div, and prints its name and value in the textarea.
HTML
<div id="textBoxContainer">
<input type="text" id="txtName" onkeyup="UpdateTextArea();" name="txtName" />
<input type="text" id="txtSurname" onkeyup="UpdateTextArea();" name="txtSurname" />
</div>
<textarea id="textAreaResult"></textarea>
Javascript
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + ",";
}
textAreaFinalResult.value = finalResult;
}
</script>
Hope this Helps! :)
For the record, I feel like this code is an ugly hack, but it should do the trick...
var fieldName = "txtName"; //your field name
var newValue = "Alex"; //your new value
var value = document.getElementById("my-textarea").value;
value = "," + value; //add a comma so we can ensure we don't replace the wrong value where the fieldname is a substring of another fieldname
if(value.indexOf("," + fieldName + "=") > 0) //see if a value is already defined
{
var index = value.indexOf("," + fieldName + "=") + fieldName.length + 2;
var start = value.substring(0, index); //get the portion before the value
var end = value.substring(index); //get everything else
if(end.indexOf(",") > 0)
{
end = end.substring(end.indexOf(",")); //remove the value by reducing the end to the location of the next comma
}else{
end = ""; //if there isn't another comma it was the last value in the list, so set the new end to nothing
}
value = start + newValue + end;
value = value.substring(1); //remove the starting comma we gave it
document.getElementById("my-textarea").value = value;
}else{
//append it to the end as you are already doing
}

Categories

Resources