This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 3 years ago.
I have here a div
<div id='myDiv'>
</div>
And a button with input type text
<input id='myNumber' type='text'>
<button id=myBtn''>Multiply</button>
my script to add an onclick
<script>
var myDiv = document.getElementById(''myDiv");
var myNumber =
document.getElementById(''myNumber");
var myBtn = document.getElementById(''myBtn");
myBtn.onclick = function(){
}
</script>
How can i insert 5 input type text inside myDiv if the value in myText is 5
You can get the count and use the append() to append the input to #myDIv. See the snippet below.
var myDiv = document.getElementById('myDiv');
var input = document.getElementById('myNumber');
function addInput() {
let count = parseInt(input.value);
if (!isNaN(count)) {
myDiv.innerHTML = "";
for (let i = 0; i < count; i++) {
let input = document.createElement('input');
input.type = "text";
myDiv.append(input);
}
}
}
<div id='myDiv'>
</div>
<input id='myNumber' type='text'>
<button onclick="addInput()">Multiply</button>
You can use onclick() function directly on the button element. Also, check for the negative values to prevent from adding the elements on the div.
function addElement() {
let count = document.getElementById('myNumber').value;;
if (!isNaN(count) && count > 0) {
myDiv.innerHTML = "";
for (let i = 0; i < count; i++) {
let div = document.createElement('input');
myDiv.append(div);
}
}
};
<div id='myDiv'>
</div>
<input id='myNumber' type='text'>
<button id='myBtn' onclick="addElement()">Multiply</button>
Related
I am trying to build a basic mad lib style code using Regex and I am unable to create new input elements and have them behave like the initial one.
I've tried swapping out (doc.replace(regex[i]... for (doc.replace(inputArray[i]... - this works partially, but in the end I am stuck with brackets around the input value.
<!-- HTML
<div id = "doc" contentEditable="true">{input1} {input2}</div>
<div id = "inputs">
<input type = "text" id = "input1"> {input1}
</div>
<br>
<button onclick="generate()">Generate</button>
<button onclick="addInput()">Add Input</button>
</div>
-->
//Global Variables
var inputNumber = 1;
var regex = [/{input1}/g];
var inputArray = ["input1"];
//Generate
function generate(){
for (var i = 0; i < inputArray.length; i++) {
var doc = document.getElementById("doc").innerHTML;
var outputArray = document.getElementById(inputArray[i]).value;
document.getElementById("doc").innerHTML = (doc.replace(regex[i], outputArray))
};
};
//Add Input
function addInput(){
inputNumber++;
var inputs = document.getElementById("inputs");
var newInput = document.createElement("div");
newInput.innerHTML = "<p><input type='text' id='input"+inputNumber+"'> {input"+inputNumber+"}</p>";
inputs.appendChild(newInput);
inputArray.push("input"+inputNumber);
regex.push("/{input"+inputNumber+"}/g")
};
I want {input2} to become the value of the input with the id of 'input2' when the function generate() is called. It just straight up doesn't work.
Here my code snippet for test.
//Global Variables
// RegEx save input
var regexInputs = /\{(input\d+)\}/g;
//Generate
function generate(){
var doc = document.getElementById("doc");
var inputs = doc.innerHTML.matchAll(regexInputs);
var input = inputs.next();
while(input.value){
doc.innerHTML = doc.innerHTML.replace(
input.value[0], document.getElementById(input.value[1]).value);
input = inputs.next();
};
}
function addInput(){
var inputs = document.getElementById("inputs");
var idxInput = inputs.children.length + 1;
var newInput = document.createElement("div");
newInput.innerHTML = "<p><input type='text' id='input"+ idxInput +"'> {input"+ idxInput +"}</p>";
inputs.appendChild(newInput);
}
<div id = "doc" contentEditable="true">{input1} {input2}</div>
<div id = "inputs">
<input type = "text" id = "input1"> {input1}
</div>
<br>
<button onclick="generate()">Generate</button>
<button onclick="addInput()">Add Input</button>
</div>
<script src="script.js" type="text/javascript"></script>
Notes:
The regexInputs is the pattern that match all inputs and store (input\d+), so using matchAll we go througth all matches.
Every match has two index 0 has "{input#}" and 1 has "input#". With this strings we just do replaces.
What I am trying to accomplish is have the user click button one and a text field is created, this button is pushed 3 times and 3 text fields appear. When each text field appears it should the user should then enter text in each text field. Once all text fields are filled by the user, there is a second button that when clicked; should display and sort the manually entered input fields text in a bonafide node list by alphabetical order.
(NOT AN ARRAY) it must be a true nodelist. Keep in mind, each input field is being created upon the push of button #1. Then the user entered information is being displayed and sorted when pushing button #2. A for-loop should be used to retrieve value of each element of the nodelistand store each value into an element of the new listItemValues array.
Appreciate any help.
javascript:
var $ = function (id) {
return document.getElementById(id)
}
var adding = function() {
var newInput = document.createElement("input");
var newBreak = document.createElement("br");
var myparent = $("todolist");
newInput.setAttribute("title", "text");
newInput.setAttribute("class", "listitem");
myparent.appendChild(newInput);
myparent.appendChild(newBreak);
};
var sorting = function() {
var display = "";
var listItemValues = document.getElementsByTagName("input");
for (i = 1; i <= listItemValues.length; i++)
var myItem = $("additem") + i;
var myItemName = (myItem).value;
display += myItemName;
}
window.onload = function() {
$("additem").onclick = adding;
$("sortitems").onclick = sorting;
}
I have made some changes to your code to make it a completely a javascriptsolution.
To reduce the use of the repetitive syntax of document.getElementById and document.createElement. I have 2 Function Declarations:
function id(id) {
return document.getElementById(id);
}
function ce(el) {
return document.createElement(el);
}
Other change is in the Function Expression adding() where I've added: newInput.type = "text"; to setting the input type when you click in the Add Item button.
In the Function Expression sorting() I've declared:
nodeList = document.querySelectorAll("input[type=text]");
The document.querySelectorAll() method returns a list of the
elements within the document (using depth-first pre-order traversal of
the document's nodes) that match the specified group of selectors. The
object returned is a NodeList.
Finally I've made a Function Expression printSortedValues() to print the sorted values in <p id="displayitems"></p>. In this function use the Array.prototype.sort() to sort its values ascending.
var printSortedValues = function(listItemValues) {
listItemValues.sort(); // Sorting the values.
var html = "", i, len = listItemValues.length;
for (i = 0; i < len; i++) {
html += "<span>";
html += listItemValues[i];
html += "</span>";
}
return html; // Return the html content with the sorted values.
};
Something like this:
function id(id) {
return document.getElementById(id);
}
function ce(el) {
return document.createElement(el);
}
var adding = function() {
var newInput = ce("input"), newBreak = ce("br"), myparent = id("todolist");
newInput.setAttribute("title", "Some title...");
newInput.setAttribute("class", "listitem");
newInput.type = "text";
myparent.appendChild(newInput);
myparent.appendChild(newBreak);
};
var sorting = function() {
var listItemValues = [], nodeList = document.querySelectorAll("input[type=text]"), i, len = nodeList.length, node;
for (i = 0; i < len; i++) {
node = nodeList[i];
listItemValues.push(node.value); // Store its values.
}
id("displayitems").innerHTML = printSortedValues(listItemValues);
};
var printSortedValues = function(listItemValues) {
listItemValues.sort(); // Sorting the values.
var html = "", i, len = listItemValues.length;
for (i = 0; i < len; i++) {
html += "<span>";
html += listItemValues[i];
html += "</span>";
}
return html; // Return the html content with the sorted values.
};
window.onload = function() {
var additem = id("additem"), sortitems = id("sortitems");
additem.onclick = adding;
sortitems.onclick = sorting;
};
#displayitems span {
border: solid 1px #ccc;
border-radius: 5px;
display: block;
margin: 2px 0;
padding: 4px;
}
<body>
<h1>ToDo List - Date: <span id="today"> </span></h1>
<div id="todolist">
<p>
<input type="button" id="additem" value="Add Item">
</p>
</div>
<hr>
<div>
<p>
<input type="button" id="sortitems" value="Sort and Display Items">
</p>
<p id="displayitems"></p>
</div>
</body>
Hope this helps.
So what i am trying to do is to have
1.add function to add an input box
2.remove function to remove the last input box in the list
3.sort function to sort the list of input texts by alphabetic order
I think my add function is working, but i am running into problem when i am trying to remove the last input box or trying to sort it.
Any idea or suggestion would be very much appreciated. thanks
<form id="mainform" >
<button onclick="add()">add</button>
<button onclick="remove()">remove</button>
<button onclick="sort()">sort</button>
</form>
<script>
var i = 0;
var count =0;
function add() {
var x= document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("placeholder", "Name");
i += 1;
count=count+1;
document.body.appendChild(x);
}
function remove(){
i -= 1;
count=count-1;
}
function sort(){
var x;
x=count;
var strings=[]
var t;
var i=0;
t=x;
while(t!=0){
strings.push(document.forms["mainform"].elements[i].value);
t=t-1;
i=i+1}
strings=strings.sort()
var j=0;
var msg='';
while(x!=0){
var msg=msg+strings[j]+'\n';
document.forms["mainform"].elements[j].value=strings[j];
j=j+1;
x=x-1;}
}
</script>
Looks like your add function adds the inputs directly to the body, while your sort function is looking for elements in the form['mainform'] element.
Your remove function is just decrementing your iterator without actually affecting the form at all.
That would do the job:
<form id="mainform" >
<input type="button" value="add" onclick="add()"></input>
<input type="button" value="remove" onclick="remove()"></input>
<input type="button" value="sort" onclick="sort()"></input>
</form>
<script>
function add() {
var x= document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("placeholder", "Name");
x.setAttribute("class", "someInput");
document.body.appendChild(x);
}
function remove() {
var childs = document.body.getElementsByClassName("someInput");
if(childs.length > 0) {
document.body.removeChild(childs[childs.length - 1]);
}
}
function sort(){
var hash = {};
var childs = document.body.getElementsByClassName("someInput");
// Map each element to its value
for(var i = 0; i < childs.length; i++) {
var currentElement = childs[i];
hash[currentElement.value] = currentElement;
}
// Remove all added elements
for(var i = 0; i < childs.length; i++) {
var currentElement = childs[i];
document.body.removeChild(currentElement);
}
// Sort by map keys, and add all elements back sorted
Object.keys(hash).sort().forEach(function(v, i) {
document.body.appendChild(hash[v]);
});
}
</script>
Please note that I replaced the button elements with input elements in order to prevent the form from being submitted.
Also pay attention that I marked each inserted textbox with class named "someInput". That will make our life easier when we want to query and get all the inserted textboxes.
I have created a simple application in javascript. The application is that a value is selected from a dropdown list and if the button next to it is clicked then the specified number of texboxes selected in the dropdown are added to the DOM with a a to their right sides.
Here's the HTML:
<form>
<select style="width: 250px;" id="numMembers" <!--onchange="addMembers();" -->>
<option value="0">Add More Members...</option>
<script>
for (var i = 1; i <= 10; i++) {
document.write('<option value=' + i + '>' + i + '</option>');
};
</script>
</select>
<button onclick="addMembers();" type="button">Add</button>
<div style="margin-top: 10px; border: 1px solid #eee; padding: 10px;">
<input type="text" />
<br/>
<input type="text" />
<br/>
<input type="text" />
<br/>
</div>
<div id="extras"></div>
</form>
And here's the script:
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function () {
document.removeChild(this);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
How can I remove the textbox on the left of the anchor tag which is when clicked. For example:
[XXXXXXX] Remove(x)
[XXXXXXX] Remove(x)
If the last "Remove(x)" is clicked then the last textbox should be removed hence the one to the left of it.
How can I do it?
Note: No JQuery solutions please! I could do that even myself :P.
You can pass the id on anchorTag and can pass same id with some addition for input text, like
If you pass the id input1 for a then use the id input1Text for relative text box,
So you when you click on particular link, you will get a with input1 and get relative input text with 'input1Text'.
This would be apply for input2, input3, ... Something like this.
DEMO
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.id = "input"+i+"Text"; //give the id with Text
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
//when you click on this link you will get relative textbox by "input"+i+"Text";
removeHref.id = "input"+i;
removeHref.onclick = function () {
var removeNodeText = document.getElementById(this.id+"Text");
removeNodeText.parentNode.removeChild(removeNodeText);
var removeNodeLink = document.getElementById(this.id);
removeNodeLink.parentNode.removeChild(removeNodeLink);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
Try This
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.id = "text_"+i;
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.id = "href_"+i;
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function(){
var id= this.id.split('_')[1];
console.log(id)
document.getElementById("extras").removeChild(document.getElementById('text_'+id));
document.getElementById("extras").removeChild(this);
}
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
I have created dynamic elements using javascript. These elements are created when i input an int value based on the value i get the number of elements.
My problem is that if i change the int value more elements are added instead i just want to keep the number of elements which has been entered in the int field.
Please help
Javascript i use
<script type="text/javascript">
var inival = 0; // Initialise starting element number
// Call this function to add textbox
function addTextBox() {
for (var i = 1; i <= document.getElementById('unit').value; i++) {
if(document.getElementById("my"+i+"Div") != null){
var child = document.getElementById("my"+i+"Div");
alert(child);
var parent = document.getElementById("area");
alert(parent);
alert(i);
parent.removeChild(child);
}
var newArea = add_New_Element();
var htcontents = "Unit"+i+": <input type='text' name='synchunit"+i+"' id='unit"+i+"'/>";
document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of 'htcontents'
}
}
function add_New_Element() {
inival = inival + 1; // Increment element number by 1
var ni = document.getElementById('area');
var newdiv = document.createElement('div'); // Create dynamic element
var divIdName = 'my' + inival + 'Div';
newdiv.setAttribute('id', divIdName);
ni.appendChild(newdiv);
return divIdName;
}
function removeElement(id){
var child = document.getElementById(id);
alert(child);
var parent = document.getElementById('area');
parent.removeChild(child);
return true;
}
</script>
The way i call it
<tr class="trlist1">
<td style="border:0;">
<input name="projectunit" id="unit" onblur="addTextBox();"/>
</td>
</tr>
<tr>
<td style="border:0;" align="center">
<div id='area'>
</div>
</td>
</tr>
I have solved it myself
just added
function addTextBox() {
document.getElementById("area").innerHTML = '';
for (var i = 1; i <= document.getElementById('unit').value; i++) {
var newArea = add_New_Element();
var htcontents = "Unit"+i+": <input type='text' name='synchunit"+i+"' id='unit"+i+"'/>";
document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of 'htcontents'
}
}
document.getElementById("area").innerHTML = '';
this line just resets the div.