Adding a label to a text area which was created using javascript - javascript

If This question has been answered please direct me to the answer
I am working on creating a mobile application which is a form designed based off a form which is used at my job. Part of this form will require the input of numbers which must fall within a specific range of numbers. If the numbers input fall outside that range of numbers, the user will need to input "corrective actions" at the end of the form.
I have a javascript function to "validate" these input fields. I have also been able to get the same function to generate a <textarea> in the correct location, but when I try to get the function to pull the content of the input field's label and add it to the generated text area the function does not work.
The following is a small portion of both the HTML form and the javascript associated with the input fields:
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
The javascript:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementByTagName("label").textContent;
//lable.appendChild(child);
var para = document.createElement("textarea");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
//element.appendChild(lable);
element.appendChild(para);
}
I have tried variations on the .getElementBy javascript method but nothing works and I am truly stumped. I have also commented out part of the "label" code in an attempt to figure out what was going wrong, this is why the lable.appendChild(child); and element.appendChild(lable); are both commented out.

The problem is that you are using getElementByTagName("label"), which is invalid syntax. What you're looking for is getElementsByTagName("label")[0]:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementsByTagName("label")[0].textContent;
//lable.appendChild(child);
var para = document.createElement("textarea");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
//element.appendChild(lable);
element.appendChild(para);
}
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
Hope this helps! :)
EDIT:
The additional problem that you're facing with the commented code is due to you attempting to set child variable as the textContent of the label element, and then append it to the label. Instead, you need to set the child variable as the label itself, and append it to element, rather than lable:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementsByTagName("label")[0];
var para = document.createElement("textarea");
para.setAttribute("id", "textbox");
child.setAttribute("for", "textbox");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
element.appendChild(child);
element.appendChild(para);
}
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
Note that I have also given the new textbox an ID, and given the label a new 'for' field, which correlates to the new textbox.
Hope this helps! :)

Related

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

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

Multiple dynamic input text javascript

Im having trouble creating multiple input texts with javascript.
My point is create a new input text everytime the input before is completed. (parent?)
Ive some code for comboboxs, but this time I need just input text box.
How can I do that ?
I've found this code:
<script type="text/javascript">
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"text\" />";
}
</script>
<input type="button" onmousedown="addInput();" />
<div id="inputs"></div>
But for my problem button is obsolete.
I think my event trigger will be something arround this "when user click in an input text box and it is != blank it creates a new one".
I migth need some ID to identify every input text box.
Cheers.
JSBIn Demo
Guess this helps:
<div id="myDiv">
<input type="text" id="txt_1" onkeydown="newTextBox(this)" />
</div>
<script type="text/javascript">
function newTextBox(element){
if(!element.value){
element.parentNode.removeChild( element.nextElementSibling);
return;
}
else if(element.nextElementSibling)
return;
var newTxt = element.cloneNode();
newTxt.id = 'txt_'+( parseInt( element.id.substring(element.id.indexOf('_')+1)) + 1);
newTxt.value='';
element.parentNode.appendChild(newTxt);
}
</script>
HTML code:
<div id="inputcontainer">
<input type="text" name="input0" id="input0" onkeyup="addInput();" />
</div>
And Javascript:
var currentindex = 0;
function addInput(){
var lastinput = document.getElementById('input'+currentindex);
if(lastinput.value != ''){
var container = document.getElementById('inputcontainer');
var newinput = document.createElement('input');
currentindex++;
newinput.type = "text";
newinput.name = 'input'+currentindex;
newinput.id = 'input'+currentindex;
newinput.onkeyup = addInput;
container.appendChild(newinput);
}
}
This will add a new input to the list only when the last input is not empty.
http://jsfiddle.net/HJbgS/
Have a look at the onchange event on your text input field. You can use it, like you use onmousedown on your button.
See http://www.w3schools.com/jsref/event_onchange.asp for an example.
In your addInput() function you should then check if the input of the previous textfield is != "".

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