I would like to add new input form by clicking on a button.
The form that I have and I would like to add:
<input type="number" id="portdiv" name="ports" min="0" max="48" size="1"/>
The button to add the new form:
<input type="button" value="Add another" onClick="addInput('portdiv');"/>
The javascript function:
var counter = 1;
function addInput(divName){
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById(divName).appendChild(textbox);
counter++;
}
This code do not works and I have not any errors on javascript console.
I have have tried different solution for the javascript function:
var textbox = document.createElement('input');
textbox.type = 'text';
document.getElementById(divName).appendChild(textbox);
counter++;
AND
var newFields = document.getElementById(divName).cloneNode(true);
document.getElementById(divName).appendChild(newFields);
counter++;
Nobody of them works. How can be solved?
You are trying to append an input to a input! An input does not have child elements.
You need to append it to the parent element that holds the form elements. By the name of your variable it would be some sort of div element. You can either do it by the name of the div, or use parentNode.
Related
im coding a form with dynamic textfield adding but i cant get num of the elements and their content created dynamically
here is the sample
<input name="mobiles[]" id="mobile"><a onclick="addfield()">add</a>
im using appenchild method for adding new inputs
for accessing mobiles elements i use
document.getElementsByName('mobiles[]').length;
but it returns just 1 and dont count added fields
I think the way you are appending the input fields is wrong. Check the snippet below, and try running it. Hope this helps.
addField = function(){
var wrapper = document.getElementById('wrapper');
var li = document.createElement('li');
var input = document.createElement('input');
input.name = 'mobiles[]';
li.append(input);
wrapper.append(li);
};
updateCount = function(){
// Shows you current count on the page.
count = document.getElementsByName('mobiles[]').length;
document.getElementById('count-wrapper').innerHTML = count;
};
<ul id="wrapper">
<li><input name="mobiles[]"></li>
</ul>
<button onclick="addField()">Add Input</button>
<button onclick="updateCount()">Update Count</button>
<div>
Input Field Count is : <span id="count-wrapper">1</span>
</div>
I am trying to add an input field to a created element. This is my code.
var Images_to_beuploaded_cont = document.getElementById("Images_to_beuploaded_cont");
var carCont = document.createElement('div');
carCont.className += "multipleImageAdding";
Images_to_beuploaded_cont.insertBefore(carCont, Images_to_beuploaded_cont.firstChild);
So, the code above adds the following
<div id="multipleImageAdding"></div>
What I want to do is the code below.
<div id="multipleImageAdding">
<input type="text" name="fname">
</div>
Is this even possible? to add an element to another after it was created?
Is this even possible? to add an element to another after it was created?
Yes, you could add the input element before or after appending the parent container element.
After creating the input element and adding the desired type and name attributes, just use the appendChild() method:
var input = document.createElement('input');
input.type = 'text';
input.name = 'fname';
carCont.appendChild(input);
Snippet:
var Images_to_beuploaded_cont = document.getElementById("Images_to_beuploaded_cont");
var carCont = document.createElement('div');
carCont.className += "multipleImageAdding";
var input = document.createElement('input');
input.type = 'text';
input.name = 'fname';
carCont.appendChild(input);
Images_to_beuploaded_cont.insertBefore(carCont, Images_to_beuploaded_cont.firstChild);
<div id="Images_to_beuploaded_cont"></div>
I'd like to be able to find the number value of the courseAmount input field upon submit, and then generate new input fields (into the hourForm form underneath the initialForm) through the onsubmit method in javascript, and then retrieve the value from each of the generated input fields upon the submission of the hourForm form and place those values into an array.
However, I'm having difficulty with actually generating the input fields with javascript, and I suspect that I'm having difficulty with retrieving the value of the courseAmount input and porting that to my createInput() function, but I'm not exactly sure if that's the issue.
Here's my HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<form id="initialForm" method="post" onsubmit="createInput()" action="">
<label>Number of hours for which you would like to study</label>
<input type="number" name="overallHours" id="overallHours" class="stored" min="1" max="20" step="1" value="1"/>
<label>Number of courses you would like to study for</label>
<input type="number" name="courseAmount" id="courseAmount" class="stored" min="1" max="20" step="1" value="1"/>
<input type="submit" class="submitStudy" value="Submit"/>
</form>
<form id="hourForm" method="post" onsubmit="calcHours">
<label>State the desired time spent working in each course</label>
</form>
</body>
And here's my Javascript:
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var counter = 0;
function createInput() {
var newForm = document.getElementById("hourForm");
document.getElementById("initialForm").style.display = "none";
document.getElementById("hourForm").style.display = "block";
for (i = 0; i <= courseNumberTotal; i++) {
newForm.innerHTML = "<label>Course #" + (counter + 1) + "</label>" + "<input type='number' name='courseHours' class='newInputs' min='1' max='9' step='1' value='1'/>";
counter++;
}
newForm.innerHTML = "<input type='submit' value='submit'/>";
}
Can someone help me figure this Javascript out? My JSFiddle attempts have been futile because JSFiddle does not take kindly to forms reloading the page.
Thank you!
From the mdn page about innerHTML: "Removes all of element's children, parses the content string and assigns the resulting nodes as children of the element." https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
Generally speaking you do not want to use innerHTML at all. There is almost always a better approach. In this case this will be createElement and appendChild.
Furthermore, there is no such thing as "onsubmit" method. What you are calling like that is an HTML attribute which registers a handler for the submit event. http://www.quirksmode.org/js/introevents.html
However using html attributes has its serious drawbacks: http://www.quirksmode.org/js/events_advanced.html
Considering all that, here is what I would do: http://jsfiddle.net/ashnur/rwod4z1d/
HTML:
<form id="initialForm" method="post" action="">
<label>Number of hours for which you would like to study</label>
<input type="number" name="overallHours" id="overallHours" class="stored" min="1" max="20" step="1" value="1" /><hr>
<label>Number of courses you would like to study for</label>
<input type="number" name="courseAmount" id="courseAmount" class="stored" min="1" max="20" step="1" value="1" /><hr>
<input type="submit" class="submitStudy" value="Submit" />
</form>
<form id="hourForm" method="post" >
<label>State the desired time spent working in each course</label><hr>
</form>
js:
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var counter = 0;
var initialForm = document.getElementById("initialForm");
var hourForm = document.getElementById("hourForm");
initialForm.addEventListener('submit', createInput);
hourForm.addEventListener('submit', calcHours);
function calcHours() {}
function createInput(ev) {
ev.preventDefault(); // this is not needed if you are using a bare button and the click event
var newForm = document.getElementById("hourForm");
initialForm.style.display = "none";
hourForm.style.display = "block";
for (i = 0; i <= courseNumberTotal; i++) {
addControl(newForm, "Course #" + (counter + 1));
counter++;
}
var submit = document.createElement('input');
submit.type = 'submit';
submit.value = 'submit';
newForm.appendChild(submit);
}
function addControl(form, labelText) {
var label = document.createElement('label');
var input = document.createElement('input');
var hr = document.createElement('hr');
input.type = 'number';
input.name = 'courseHours';
input.classname = 'newInputs';
input.min = '1';
input.max = '9';
input.step = '1';
input.value = '1';
label.textContent = labelText;
form.appendChild(label);
form.appendChild(input);
form.appendChild(hr);
}
As Tobias correctly pointed out, your form submission event is allowed to continue which results in a page refresh and a "reset" of all plain JavaScript data. Furthermore, you are not capturing your values (notedOverallHours and courseNumberTotal) on form submission (after the user has entered an amount), but rather when your page initializes (before the user has input anything).
So, to go about fixing this, first a tiny modification to your HTML:
...
<form id="initialForm" method="post" action="">
...
Notice that I deleted the onsubmit attribute from your form. We can capture that with an event in JavaScript itself.
Next attach an event listener to your form which prevents it from submitting and calls your createInput() function:
document.getElementById("initialForm").addEventListener('submit', function (e) {
e.preventDefault();
createInput();
});
This will attach an eventListener that listens to the submit event on your initialForm element. The first parameter is the type of event you want to listen for (submit in this case), the second is the callback you want to have fired.
The callback function always gets the event passed in (the e argument). By calling preventDefault on this event we can stop it from bubbling up and actually causing a page refresh.
Next we call the createInput() function which, after some modifications, looks like this:
function createInput() {
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var newForm = document.getElementById("hourForm");
document.getElementById("initialForm").style.display = "none";
document.getElementById("hourForm").style.display = "block";
// Add our elements
for (i = 1; i <= courseNumberTotal; i++) {
var child = document.createElement('li');
child.innerHTML = "<label>Course #" + (i) + "</label>" + "<input type='number' name='courseHours-"+ i+"' class='newInputs' min='1' max='9' step='1' value='1'/>";
newForm.appendChild(child);
}
// Add our button
var button = document.createElement('li');
button.innerHTML = "<input type='submit' value='submit'/>";
newForm.appendChild(button);
}
As you can see, I capture the notedOverallHours and courseNumberTotal variables inside the createInput() function, so they will carry whichever value was set during the form submission event.
Then we iterate over each course number. Instead of replacing the innerHTML, we first create an element (li in our case) and fill that element with a HTML string. Next we append this child element to the parent form.
Inside the loop I have removed the counter variable as you can simply use the value of i inside the loop, no need to create an extra variable. I also appended the name attribute for each child with i, so not to get any name clashes.
At the end of our function we simply create and append a new li element containing the submit button.
You can optimize this further by actually creating the label and input elements with the createElement function and set its attributes and text individually with plain JavaScript setters, instead of dumping everything inside li elements as I've done here to keeps things a bit more simple for now. I`ll leave that up as an exercise :)
I have created a rough JSFiddle with this exact code here.
When the createInput() function is called you are not having the desired results because you are reseting the newForm.innerHTML in each iteration of the loop and then again at the end. Rather than using = you should be using += to append the desired text rather than replace the existing text.
// Replacing the contents of newForm.innerHTML
newForm.innerHTML = "foo";
// Appending to newForm.innderHTML (You want to do this)
newForm.innerHTML += "foo";
Another problem is that when you press submit the page is reloading before createInput() is able to have the desired result. You most likely want to stop the page actually submitting and thus reloading when you press the submit button. To do this you can change the onsubmit attribute for the form to "return createInput()" and then add the line return false; to the end of the createInput() function to indicate to the browser that you do not wish to submit the form.
I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
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"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>
I am trying to add elements to an array via a form. I am using the unshift() method. The code below doesn't work and I would like to know why.
<form>
<input id="input"> </input>
<input type = "button" id="button"> Click me </input>
</form>
<script>
var input = document.getElementById("input").value;
var button = document.getElementById("button");
var myArray = [];
myArray.unshift(input);
button.onclick = function alerted (){
alert(myArray);
};
</script>
Your quoted code runs immediately when the page is loaded. The form field won't have anything in it then, so its value will be ''. When you alert that, the default toString operation on the array will result in '' and the alert will be blank.
You want to run your unshift code in response to a user event, such as the button being clicked, rather than right away. You can do that by setting input to be the element (remove .value from that line) and then moving your line with unshift into the function you're assigning to onclick, adding the .value there:
button.onclick = function alerted (){
myArray.unshift(input.value);
alert(myArray);
};
Other notes:
You never write </input>. Normally you don't close input tags at all. If you're writing XHTML (you probably aren't), you'd put the / within the main input tag like this: <input id="input" />. But again, you're probably not writing XHTML, just HTML.
The value (caption) of an input button goes in its value attribute, not content within opening and closing tags. (You would use opening and closing tags with the button element, not input.)
Taking all of that together, here's a minimalist update: Live copy | source
<form>
<input id="input"><!-- No ending tag -->
<input type = "button" id="button" value="Click me"><!-- No ending tag, move value where it should be -->
</form>
<script>
var input = document.getElementById("input"); // No .value here
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // Moved this line, added the .value
alert(myArray);
};
</script>
DEMO
You need to a) get the value in the click and b) return false if you want the button to not submit. I changed to button. Alternative is <input type="button" value="click me" id="button" />
You may even want to empty and focus the field on click...
<form>
<input id="input" type="text"/>
<button id="button"> Click me </button>
</form>
<script>
var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // get the value
alert(myArray);
return false;
};
</script>
You're not getting the new value in the onclick function.
Try this: http://jsfiddle.net/SeqWN/4/
var button = document.getElementById("button");
var i = document.getElementById("input");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(i.value);
alert(myArray);
};