accessing form elements with javascript - javascript

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>

Related

Value in "input" filed becomes empty [duplicate]

This question already has answers here:
Stop input from clearing on innerHTML insert
(4 answers)
Closed 8 months ago.
Hi Folks I'm new to JS World.
I am trying to add A <div> dynamically to my HTML with the help of JavaScript.
var counter = 0;
function add_more_animals() {
counter+=1;
html = `<div id="animal${counter}">
<input type="text" name="animalName${counter}">
<input type="text" name="animalType${counter}">
</div>`;
var form = document.getElementById("animals");
form.innerHTML+=html;
}
<div id="animals">
<div id="animal0">
<input type="text" name="animalName0">
<input type="text" name="animalType0">
</div>
</div>
<button type="button" onclick="add_more_animals()">Add animals (+)</button>
The issue I'm facing:
While I populate the fields of animalName0 and animalType0 on UI. After I click on add button so as to insert more animals data, new div is created as per JS logic written in file. But my earlier inputs to animalName0 & animalType0 becomes empty & I have to insert data there all over again.
Can you please help here?
The problem stems from the line form.innerHTML+=html which is shorthand for form.innerHTML = form.innerHTML + html. When it gets the form.innerHTML it is grabbing the HTML only; The text typed into the inputs are not a part of this HTML. When the innerHTML gets set, think form.innerHTML = form.innerHTML + html, brand new HTML elements are created based off of the HTML only, and any state, including typed in text, is lost. Any event listeners will also be lost in this process.
The proper way of adding a new element while leaving adjacent elements in place is to create the new element with document.createElement, and add it with a function like .appendChild, like so
var counter = 0
function add_more_animals() {
counter+=1;
// Create an empty element
const newEl = document.createElement('div')
newEl.id = `catalogue${counter}`
// Add the first input
const nameInput = document.createElement('input')
nameInput.name = `animalName${counter}`
newEl.appendChild(nameInput)
// Now the second one
const typeInput = document.createElement('input')
typeInput.name = `animalType${counter}`
newEl.appendChild(typeInput)
// And finally attach everything to the animals form
document.getElementById("animals").appendChild(newEl)
}
<div id="animals">
<div id="animal0">
<input type="text" name="animalName0">
<input type="text" name="animalType0">
</div>
</div>
<button type="button" onclick="add_more_animals()">Add animals (+)</button>
As you can imagine, this can become verbose if you have a large amount of HTML to add. To make this process easier they came out with template tags which you may prefer using. Use them either like this or like this.

JavaScript- dynamically adding input to a page

i am using JavaScript to add a div on the fly. The div should contain a form input whose 'name' attribute WILL changes in value incrementally.
I have managed to do this- I however have two problems.
First Problem:
The first div that i created is cancelled out by the next dynamically created div.
thus, when i submit the form, the first dynamically created imput form is blank-
but subsequent ones have values on them.
MY CODE :
html
<div id="dynamicDivSection"></div>
<button id="addbutton">add box</button>
<div id="boxes">
<div class="box">
<input type="text" id='dynamic-imput' name="">
</div>
</div>
javascript
var addbutton = document.getElementById("addbutton");
var key = 1;
addbutton.addEventListener("click", function() {
key++;
document.getElementById('dynamic-imput').name = 'ser['+key+'][\'name\']';
var boxes = document.getElementById("boxes");
var head = document.getElementById("dynamicDivSection");
var clone = boxes.firstElementChild.cloneNode(true);
head.appendChild(clone);
});
i suspect that the problem is causing by this:
document.getElementById('dynamic-imput').name =
'ser['+key+'][\'name\']';
i.e when i create the dynamic div it creates several inputs on the page that contain the same Id. if i am correct, then perhaps teh solution is to change the Id of the newly created imput - however, i am not sure how to change the Id of a dynamically created Imput.
Second problem.
i want each dynamically created div to go to the top of the page; i.e to be placed before the earlier created dynamic div- however, at the moment each dynamically created div go directly under the first dynamically created div.
You can insert as the first child with:
parent.insertAdjacentElement('afterbegin', nodeToInsert);
You can get and set attributes such as id with setAttribute and getAttribute. Though I'm not sure why you even need an ID here, it would be simpler not to have one and select the element with a class.
var addbutton = document.getElementById("addbutton");
var key = 1;
addbutton.addEventListener("click", function() {
key++;
document.getElementById('dynamic-imput').name = 'ser['+key+'][\'name\']';
var boxes = document.getElementById("boxes");
var head = document.getElementById("dynamicDivSection");
var clone = boxes.firstElementChild.cloneNode(true);
var clonedInput = clone.firstElementChild;
clonedInput.setAttribute('id', clonedInput.getAttribute('id') + '-' + head.children.length);
head.insertAdjacentElement('afterbegin', clone);
});
<div id="dynamicDivSection"></div>
<button id="addbutton">add box</button>
<div id="boxes">
<div class="box">
<input type="text" id='dynamic-imput' name="">
</div>
</div>

Add user input to a li element

EDITED
I am currently trying to figure out my homework (no, I don't want someone to just do it for me) and I am stuck. I have a simple website where a user types something into a text box and when they click the submit button, the input should show up in a list.
My textbook is asking me to make the function processInput() that takes user input and puts it into the list. My problem is were it asks me to "Set the content of the element with an id equal to the listItem to the value of the element with the id of inputbox." I thought it would be this
document.getElementById("listItem").innerHTML = document.getElementById("inputBox");
But I get an error on this line saying: "Uncaught TypeError: Cannot set property 'innerHTML' of null"
EDIT: Thank you all for the help. I have removed the quotations around listItem and fixed a [object HTMLInputElement] issue, now it works.
The EDITED chunk of code:
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="inputBox" id="placeLabel">
Type here, then click Submit:
</label>
<input type="text" id="inputBox" />
</fieldset>
<fieldset>
<button type="button" id="button">Submit</button>
</fieldset>
</form>
</article>
<script>
// Global variables
var i = 1;
var listItem = "";
// function to process input
function processInput()
{
if(i <= 5)
{
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("inputBox").value;
document.getElementById("inputBox").value = "";
if (i === 5)
{
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions.";
}
i += 1;
}
}
// Backward compatable event listener for submit button
var submitButton = document.getElementById("button");
if(submitButton.addEventListener)
{
submitButton.addEventListener("click", processInput, false);
}
else if(submit.attachEvent)
{
submit.attachEvent("onclick", processInput);
}
</script>
You have to remove quotes from listItem because you declared listItem as variable.
document.getElementById(listItem).innerHTML = document.getElementById("inputBox");
Your problem here is simple -- you're supplying a string "listItem" to getElementById, but the ID listItem doesn't exist.
What you want to do is supply your variable you're already declaring:
listItem = "item" + i;
As this will look like "item6", etc.
All that means for your function is -- take of the quotes, so you're using the variable instead of a string:
document.getElementById(listItem).innerHTML
You need an element listItem. Thats why you get this error.
You don't have an element in your HTML with an id of "listItem" so
document.getElementById("listItem")
is null
In the line
document.getElementById("listItem").innerHTML = document.getElementById("inputBox");
You are literally searching for an element that has the id "listItem" (you're searching for a STRING!)
But you set the variable listItem above, so use that instead:
document.getElementById(listItem).innerHTML = document.getElementById("inputBox");
Once you get that working, you'll notice that you're setting the content (innerHTML) of the list item to the ACTUAL ELEMENT (that's what getElementById() is spitting out). That's not really possible, so a smart browser will tell you what that object is... as a string: [object HTMLInputElement]. Your instructions tell you to set the list item content to the VALUE of that input, not the input itself.

Delete button next to each array's value

I have a HTML-JavaScript script in which the user can insert data to a new array [] by using a form's text field and an insert button.
By pressing insert button, the user inserts the data typed into the array.
I have a function which prints all the values of the array into <p id="demo"></p> and runs itself every 100 milliseconds in order to be updated with the arrays values.
I also have a reset button to delete every array's value when clicked.
What I want to do is add a delete button next to each array's value in order to be easier for the user to delete the wrong value he inserted.
I am using this code to insert values and print them:
HTML:
<div align="center">
<form id="form1">
<input type="text" name="fname" id="fname" placeholder="Type here!">
</form>
<br>
<input type="button" id="Button Insert" onclick="myFunction()" value="Insert">
<input type="button" onclick="myFunction3()" value="Reset">
</div>
<p id="demo" align="center"></p>
JavaScript/JQuery:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
all_values.push(temp_val);
document.getElementById("form1").reset();
}
setInterval(function () {
$("#demo").html(all_values.join("<br>"));
}, 100);
function myFunction3() {
all_values.length = 0;
}
To be more specific I want something like these things: iOS example JSFiddle Example 1 JSFiddle Example 2.
Could you please help me? Thanks in advance.
I'd do it the other way around.
Remove setInterval as it's really bad way to do such things.
Remove white spaces from the id attribute (id="Button-Insert", not id="Button Insert")
Don't use onclick attributes. Instead, register click event handlers with jQuery
// caching is a good practice when you reffer to the same elements multiple times:
var all_values =[], demo = $("#demo"), form = $("#form1")[0], fname = $("#fname");
$('#Button-insert').click(function(){
var temp_val = fname.val();
all_values.push(temp_val);
// create delete button along with the value
demo.append('<p>'+temp_val+' <button value="'+temp_val+'" type="button" class="del-btn">Delete</button></p>');
form.reset();
});
$('#Button-reset').click(function(){
all_values = [];
demo.html('');
});
// event delegation for dynamic elements:
demo.on('click', '.del-btn', function(){
all_values.splice(all_values.indexOf($(this).val()), 1);
$(this).parent().remove();
});
JSFiddle
Simply create the delete buttons at the same time you create the table.
function loadvalues(){
var i, button;
$('#demo').empty();
for(i in all_values){
$('#demo').append(all_values[i]);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
}
Also you don't need to poll, you could simply add each one on demand with a function like this:
function addVal(){
var val = $("#fname").val(), i = all_values.length;
all_values.push(val);
$('#demo').append(val);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
I had some typos, the code works,
Check here:
http://codepen.io/anon/pen/QbvgpW

javascript: adding form on click

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.

Categories