Retrieving the value of Dynamically Created elements - javascript

i Have created a HTML form , in this form when i Click on a button it creates input text fields based on a predefined criteria , this works fine .
now when i try and retrieve the value entered in those created text fields using alert i am not able to do so .
i have two questions
What is the best way to retrieve inputs from the dynamically created text fields?
can you tell me why the code i have written does not work
HTML code
<BODY>
<FORM>
<BR/>
<div align = "center">
<br /><br />
<INPUT type="button" value="Click To Enter Values" onclick="getkeywords()"/>
</div>
<div align="center" id="d_div">
<form name="permavalues" id="d_form">
</form>
<br/> <br/>
</div>
</FORM>
THe javascript code that i am using is this :
function getkeywords() {
var index_array = new Array();
var myString = "one and a two and a three = $ and four = $ and five = $";
var splitresult = myString.split(" ");
for(i = 0; i < splitresult.length; i++)
{
if (splitresult[i] == "$" && i > 1 ) //retireving the keywords..
{
add(splitresult[i-2]);
}
}
}
The add function which is called in getkeywords:
function add(s) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", s);
element.setAttribute("name", s);
element.setAttribute("id", s);
var foo = document.getElementById("d_form");
//Append the element in page (in span).
foo.appendChild(element);
alert("Value=" + document.getElemebtById(s).value);
}
I think that i must have a mistake with element.setAtrribute("id",s);

The major problem is you can't put form inside another form. Please remove you HTML code line 2 and line 13.
Another problem is your typo, as IvanL said.
Other code are fine.
Give you fully tested work code as below.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>test</title>
<script language="javascript">
function getkeywords() {
var index_array = new Array();
var myString = "one and a two and a three = $ and four = $ and five = $";
var splitresult = myString.split(" ");
for(i = 0; i < splitresult.length; i++)
{
if (splitresult[i] == "$" && i > 1 ) //retireving the keywords..
{
add(splitresult[i-2]);
}
}
}
function add(s) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", s);
element.setAttribute("name", s);
element.setAttribute("id", s);
var foo = document.getElementById("d_form");
//Append the element in page (in span).
foo.appendChild(element);
alert("Value=" + document.getElementById(s).value);
}
</script>
</head>
<BODY>
<BR/>
<div align = "center">
<br /><br />
<INPUT type="button" value="Click To Enter Values" onclick="getkeywords()"/>
<br><br><br>
<input type="button" value="add" onclick="add('tt')">
</div>
<div align="center" id="d_div">
<form name="permavalues" id="d_form">
</form>
<br/> <br/>
</div>
</body>
</html>

What is the best way to retrieve inputs from the dynamically created
text fields?
I would use JQuery to traverse the form for all text input elements and retrieve their respective values.
Alternatively, you could give each of the text fields a common name like "txt_" and then append an incremental ID to the string (I.E. -- txt_1, txt_2, txt_3, ...) then programmatically iterate over your form fields that match until you've reached a value that represents the total number of available form fields. That value could be a javascript integer.
For example...
$("form input[type='text']").each( function()
{
// gets text value for each field in the form
var textFieldValue = this.value;
// do stuff
});

Have a look on the Jquery code for getting All Input Value.
$(document).ready(function()
{
$('form#d_form input[type="text"]').each(
function()
{
alert($(this).val());
});
});

Related

How to display input values from textfields with array name attributes using javascript

I have created a form which should submit data, but before submission I want the user to have a preview of what they have filled before clicking on the submit button.
The JavaScript function I have put in place, only shows input values from only one of the textfield.
what I expect was that for each textfield I would get its input values displayed.
Currently, I am getting just one value from the textfields with this same id.
How can I adjust my code to show value of each textfield .
// function and element to view input value
function myFunction() {
var Milstonedescription =
document.getElementById("milstanedetails").value;
document.getElementById("Milestonesdescriptionvalue").innerHTML =
Milstonedescription;
}
<input type="text" class="milstone" id="milstanedetails" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<input type="text" class="milstone" id="milstanedetails" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<p class="halffieldcontainer" id="Milestonesdescriptionvalue"></p>
The problem on your code is that you use the same id on multiple input field, thats not possible because id are unique and whatever you will get only the first element with the matching id.
If you want to get your value from each fields you should use getElementsByClassName('className') and looping on, it's seems to correspond to what you want to do.
EDIT :
Yeah last version didn't work properly, i edited and tested that one. Seems to work properly on my side now. ( http://jsfiddle.net/tgo46se2/ )
function myFunction() {
let milstones = document.getElementsByClassName("milstone");
let milstoneDescription = '';
for(let i = 0; i < milstones.length; ++i) {
milstoneDescription += milstones[i].value;
}
document.getElementById("Milestonesdescriptionvalue").innerHTML = milstoneDescription;
}
this could works:
<!doctype html>
<head></head>
<body>
<p id="text"></p>
<input type="text" class="milstone" id="milstanedetails" placeholder="Describe the milestone or task you will complete" oninput="myFunction('milstanedetails','Milestonesdescriptionvalue')" name="milestone[]">
<input type="text" class="milstone" id="milstanedetails2" placeholder="Describe the milestone or task you will complete" oninput="myFunction('milstanedetails2', 'Milestonesdescriptionvalue')" name="milestone[]">
<p class="halffieldcontainer" id="Milestonesdescriptionvalue"></p>
</body>
<script>
// function and element to view input value
function myFunction(idEl, idPrev) {
var Milstonedescription =
document.getElementById(idEl).value;
document.getElementById(idPrev).innerHTML =
Milstonedescription;
}
</script>
</html>
I change the second id because in html id must be unique.
I hope this help
first, you have to make each input id unique because using the same id value for multiple elements is not valid in HTML.
you can achieve what you want by this code:
function myFunction(){
var nodes = document.querySelectorAll("[name='milestone[]']");
var input_value1 = nodes[0].value;
var input_value2 = nodes[1].value;
var text = '';
if(input_value1 && input_value1 !== ''){
text += 'first input value: ' + input_value1;
}
if(input_value2 && input_value2 !== ''){
text += '<br /> second input value: ' + input_value2;
}
document.getElementById("Milestonesdescriptionvalue").innerHTML = text;
}
<input type="text" class="milstone" id="milstanedetails1" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<input type="text" class="milstone" id="milstanedetails2" placeholder="Describe the milestone or task you will complete" oninput="myFunction()" name="milestone[]">
<p class="halffieldcontainer" id="Milestonesdescriptionvalue"></p>
and here is a working snippet.
Get inputs by class attribute.
function myFunction() {
var milstones = document.getElementsByClassName("milstone");
var milstoneDescription = '';
for (var i = 0; i < milstones.length; i++) {
var val = milstones[i].value;
if (typeof val != "undefined")
milstoneDescription += val + ' ';
}
document.getElementById("Milestonesdescriptionvalue").innerHTML = milstoneDescription;
}

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!

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Selecting a value in a select box after the value has been added dynamically

How can I select my newly added value in the select box (dropdown) after the value that was inputted into the textbox and the add button was clicked?
<html>
<head>
<script>
function addref(value) {
var x = document.getElementById("thebox");
var option = document.createElement("option");
option.text = value
x.add(option,x.options[null])
}
</script>
</head>
<body>
<form>
<select id="thebox">
</select>
</form>
<br>
<input type="text" id="theinput"/>
<input type="button" value="Add" name="B1" onclick="addref(document.getElementById('theinput').value)"/>
</body>
</html>
Try this:
x.selectedIndex = x.options.length - 1;
After this you can retrieve the value using
var val = x.value;
or
var val = x[x.selectedIndex].value;
<select> at MDN.
Also, instead of x.add(option,x.options[null]) rather use simply x.add(option). This will add the newly created option at the end of the options. The second argument is supposed to be an integer, which represents an index position where to add a new option.
To get the selected value, use this:
var e = document.getElementById("thebox");
var theValue = e.options[e.selectedIndex].value;
To get the selected text, use this:
var e = document.getElementById("thebox");
var theText = e.options[e.selectedIndex].text;
It does not matter if it was added dynamically.

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 != "".

Categories

Resources