I am trying to get a forloop with input elements to run between a form and create a form dynamically with javascript
1: in scenario one , the form in the script is getting closed before the input elements populate.
2: in scenario two , when i put the for loop variable between the form ,the error that comes is undefined .
PLEASE HELP
SCENARIO ONE
<form>
No of Feilds <input type="text" id= "numberoffeilds">
<input type="button" value = "Create Feilds" onclick= "addfeilds1();">
</form>
<div id= "div4" style= "color:gray"></div>
<script>
function addfeilds1()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">';
for(i=0;i<totalfeilds;i++)
{
document.getElementById("div4").innerHTML += '<input type = "text">';
}
document.getElementById("div4").innerHTML += '<input type = "submit" value="submit" name="submit">';
}
</script>
SCENARIO TWO
<form>
No of Feilds <input type="text" id= "numberoffeilds">
<input type="button" value = "Create Feilds" onclick= "addfeilds2();">
</form>
<div id= "div4" style= "color:gray"></div>
<script>
function addfeilds2()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
function forloop()
{
for(i=1 ;i<totalfeilds;i++)
{
document.getElementById("div4").innerHTML += '<input type = "text">';
}
}
var loopvar = forloop();
document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">'+
'<input type = "text">'+
loopvar + // it shows the loop as undefined
'<input type = "text">'+
'<input type = "text">'+
'<input type = "submit" value="submit" name="submit">';
}
</script>
You need to build the HTML elements in a string first and add them to the div as a last step.
Fixed scenario 1:
function addfeilds1()
{
var totalfeilds = document.getElementById("numberoffeilds").value;
var i;
var htmlString = "";
htmlString += '<form action= "issue.html" method = "POST">';
for(i=0;i<totalfeilds;i++)
{
htmlString += '<input type = "text">';
}
htmlString += '<input type = "submit" value="submit" name="submit">';
document.getElementById("div4").innerHTML = htmlString;
}
This prevents the form tag from being closed before it's populated with inputs.
Fixing scenario 2:
function forloop()
{
var htmlString = "";
for(i=1 ;i<totalfeilds;i++)
{
htmlString += '<input type = "text">';
}
return htmlString; // now forloop returns a string that can be added to the element. It no longers returns undefined.
}
Actually scenario 2 was fixing scenario 1, but you didn't include a return in your function. If you expect a function to create some text and concat that into a string you need your function to return a string.
Third example (advanced)
function addfeilds1()
{
var totalFields = parseInt(document.getElementById("numberoffeilds").value); //parse integer from value
if (isNaN(totalFields) || totalFields < 1)
{
//check if the input is valid, if not alert.
alert("Value is not a valid number or lower than 1.");
}
var container = document.getElementById("div4");
//create the form
var form = document.createElement("form");
form.setAttribute("action", "issue.html");
form.setAttribute("method", "POST");
for(var i=0; i<totalFields; ++i)
{
var node = document.createElement("input");
node.setAttribute("name", "field[]"); //this sends a array to the request page containing all input field values.
form.appendChild(node); //add the fields to the form.
}
//create the submit button.
var button = document.createElement("input");
button.setAttribute("type", "submit");
button.setAttribute("value", "submit");
button.setAttribute("name", "submit");
form.appendChild(button);
container.appendChild(form); //append the form to the div.
}
Related
I am trying to load the following options in my html, generated in javascript.
HTML:
<button type="submit" onClick="input(data)">Add</button>
<select id="processSelect" name="process">
</select>
Javascript:
function input(input){
//my code
createOptionsSelectProcess(arrayResponse);
}
function createOptionsSelectProcess(arrayResponse){
var html = '';
var arrayLength = arrayResponse.length;
for (var i = 0; i < arrayLength; i++) {
html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i]
+ '</option>';
}
document.getElementById("processSelect").innerHTML = html;
}
However, the result I have observed in debug is that the options are generated in the select, but they disappear when the execution is finished. Does anyone know what the reason may be?
button type submit will submit the form and refresh the page, use
<button type="button" onClick="input(data)">Add</button>
Also by default button is of type submit so if you don't put it it will still submit the form.
You don't need the function input(input). You can use the event listener submit to submit the form.
document.addEventListener('submit', () => createOptionsSelectProcess(data))
function createOptionsSelectProcess(arrayResponse) {
var html = '';
var arrayLength = arrayResponse.length;
for (var i = 0; i < arrayLength; i++) {
html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i] + '</option>';
}
document.getElementById("processSelect").innerHTML = html;
}
<form>
<button>Add</button>
<select id="processSelect" name="process"></select>
</form>
You could use <button>Add</button> or <input type="submit" value="Add">. They will both submit the form without an onClick attribute.
I have to get 'n' - total number of names from the user and then create n number of fields for getting all the names. I've currently written this as:
HTML code:
<form action="/flight_ticket/book" name="myform" method="post">
.
.
.
Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>
</body>
JS code:
function addFields(){
var number = parseInt(document.getElementById("nooftickets").value);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Name " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
But when I run it on browser, after clicking the "Enter names", I don't see any changes in the browser!
What have I got wrong?
What you are doing is trying to fetch the value of the noofticktes which is defined as a name in the HTML but in your code, you are using document.getElementById('noofticktes').value which is throwing an undefined error as there is no id defined as noofticktes.
So, just change your code on from:
var number = document.getElementById("nooftickets").value;
To this:
var number = document.getElementsByName("nooftickets")[0].value;
you will be able to make your code work.
One small update in your code would be if you are trying to clear/remove all the contents of the element container just use the container.innerHTML='' instead of looping and removing each element.
Here is the updated Snippet of your code.
function addFields() {
debugger;
var number = document.getElementsByName("nooftickets")[0].value;
var container = document.getElementById("container");
container.innerHTML = '';
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Name " + (i + 1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
<form action="/flight_ticket/book" name="myform" method="post">
. . . Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
Enter names
<div id='container' />
</div>
<br/><br/>
</form>
function addFields() {
// body...
var input = '';
var number = document.getElementById('number').value;
for(var i=0;i<number;i++)
{
input +="<input id='number"+i+"' name='number"+i+"'><br>";
}
document.getElementById('container').innerHTML = input;
}
<form action="/flight_ticket/book" name="myform" method="post">
Enter the number of tickets to be booked:
<input name="nooftickets" id="number" type="text"><br/><br/>
Enter names
<div id='container'/>
</div>
<br/><br/>
</form>
When I use this code, I am unable to get it to display the data upon clicking the display button. The code is supposed to save the input upon clicking the next button and display the array upon clicking display and clear the array when clicking clear. How do I go about resolving this?
Whenever I click the buttons nothing happens. I want to display the array inside the text area.
<html>
<head>
<script language = "javascript">
var full_name;
var dob;
var gender;
var memberList= new Array();
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
// Replace the contents of the textarea with the value in str
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
}
</script>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
</head>
<body>
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
</button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
</form>
</body>
</html>
your code is working..remove </button> in your html
I thing you expecting like this: declare the array like var memberList= [];.If you click the clear button Array was empty and textarea also empty.If you need only empty with array.remove document.getElementById("textBox").value=""; in clearlist()
var full_name;
var dob;
var gender;
var full_name;
var memberList= [];
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
document.getElementById("textBox").value="";
}
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()">
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
<input type = "button" value = "CLEAR" onclick ="clearList()">
</form>
you have written "</button>" as closing tag, which is incorrect syntax for input tag.
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"></button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
replace this with the following and your code will work fine.
<input type = "button" value = "NEXT" onclick ="saveMember()"/>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"/>
<input type = "button" value = "CLEAR" onclick ="clearList()"/>
also change these functions for proper functioning
function saveMember() {
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
memberList.push(full_name, dob, gender);
document.getElementById('full_name').value = "";
document.getElementById('dob').value = "";
document.getElementById('gender').value = "";
}
function clearList() {
memberList = [];
document.getElementById("textBox").value = str;
}
I was wondering if there is a way to append to values that are arrays.. for example
<input type="text" id="someID" name="text[]"/>
How do you append to that in javascript?
Normally, I would just get the contents of value then append to it but it's an array here so I'm not sure how to do it
Code for appending for a non-array
var newvalue = 50;
var value = document.getElementById('someID').value;
document.getElementById('someID').value = value+newvalue;
Now, what I need is for PHP to get that array with the value 50 in it
How do I do that?
You can append hidden input with desired value and same name to the form.
HTML:
<form action="" name="numbers-form">
<input type="text" name="numbers[]" value="30" />
<input type="text" name="numbers[]" value="40" />
</form>
JavaScript:
var formArray = (function() {
var form = document.forms['numbers-form'],
inputName = 'numbers[]';
return {
getNumbers: function() {
// NodeList to Array
var nodesArray = Array.prototype.slice.call(form[inputName]);
return nodesArray.map(function(input) {
return input.value;
});
},
addNumber: function(number) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = inputName;
input.value = number;
form.appendChild(input);
},
printNumbers: function() {
console.log(this.getNumbers());
}
};
})();
formArray.printNumbers();
formArray.addNumber(50);
formArray.printNumbers();
formArray.addNumber(60);
formArray.printNumbers();
DEMO
<script type="text/javascript">
var i = 1;
function generateRow() {
var d=document.getElementById("div");
d.innerHTML+="<p><input type='text' name='[Post][textbox1][" + i + "]'>";
i = i + 1;
}
<?php $this->Form->input('textbox1',array(
'type' => 'textbox',
'label' => false,
'required')); ?>
<div id="div"></div>
<input type="button" value="Add" onclick="generateRow()"/>
Html For Textbox1
<div class="input textbox"><input name="data[Post][textbox1]"
required="required"type="textbox" id="PostTextbox1"/></div>
When I click on "Add" button, It generates new text box with name="[Post][textbox1][1]"
I can enter data in that box, but
Issue 1
When I again click on Add button It will reset all textbox and I have to enter those data again
Issue 2
$tbVal = $this->request->data['Post']['textbox1'];
$inn = implode(',',$tbVal);
When I use this code to implode data from textbox, it is showing only first data
Here is a working example based on the first answer and my answer:
<script type="text/javascript">
var i = 1;
function generateRow()
{
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "data[Post][textbox][" + i + "]");
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
i = i + 1;
}
</script>
<form>
<div id="fooBar" class="input textbox">
<input name="data[Post][textbox][0]" required="required" type="textbox" id="PostTextbox1"/>
</div>
<input type="button" value="Add" onclick="generateRow()"/>
<input type="submit" >
</form>
<?php
print_r($_REQUEST);
?>
You have to use DOM manipulation javascript functions to not reset your text values and use proper name for the text boxes
you have reset all data in div document.getElementById("div") there for it reset all data in textbox.
try :
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
on button click
Regarding issue 2
This code:
d.innerHTML+="<p><input type='text' name='[Post][textbox1][" + i + "]'>";
have to be
d.innerHTML+="<p><input type='text' name='data[Post][textbox1][" + i + "]'>";