index not incrementing in input field - javascript

I have a button that creates two input fields on click. I want to add a unique id for each couple of inputs that is created so that I can delete them later. Currently when I add the inputs they all have the same id 0 and the index does not increment, why and how can I make it increment? Here is my code:
createNewPricedRoundShareholder() {
const mainParent = document.getElementById('main-parent');
var index = 0;
const newPlatformNameInput1 = document.createElement("input");
newPlatformNameInput1.id = index + '_first';
newPlatformNameInput1.value = index;
const newPlatformNameInput2 = document.createElement("input");
newPlatformNameInput2.id = index + '_second';
newPlatformNameInput2.value = index;
const deleteButton = document.createElement("button");
deleteButton.innerText = 'delete';
const wrapperParent = document.createElement('div');
wrapperParent.id = index + '_parent';
wrapperParent.appendChild(newPlatformNameInput1);
wrapperParent.appendChild(newPlatformNameInput2);
wrapperParent.appendChild(deleteButton); mainParent.appendChild(wrapperParent);
index++;
}
and my html:
<div id="main-parent"></div>

I know you said you want an ID so you can use it to delete your row later, but you don't actually need it. If you add this code to your function, you can delete the entire row without the need of using an ID. This code will allow you to target the specific button, then the parent of that button and remove it.
deleteButton.addEventListener("click",function(e){
e.preventDefault();
e.target.parentNode.remove();
});

I think that is because you increase the index at the end of your function but you should increase it after creating the first input and before creating the second one
[...]
const newPlatformNameInput1 = document.createElement("input");
newPlatformNameInput1.id = index + '_first';
newPlatformNameInput1.value = index;
index++;
const newPlatformNameInput2 = document.createElement("input");
newPlatformNameInput2.id = index + '_second';
[...]

Related

Get id and value of dynamically created elements

I'm trying to get the ids of dynamically created elements, now these elements are in the form of input fields that can be modified by the user (the user enters the number of players then he gets input fields to type in their names), I'm trying to get their values as well, here is what I'm trying to do:
// Creating the input fields
const x = localStorage.getItem('playersNum');
const parentDiv = document.getElementById('player-list');
for (let i = 0; i < x; i++) {
const newInput = document.createElement("INPUT");
newInput.setAttribute("type", "text");
newInput.setAttribute("class", "form-control");
newInput.setAttribute("id", `player${i}`);
newInput.setAttribute("placeholder", "Player's Name");
parentDiv.appendChild(newInput);
}
// Trying to access them
const players = document.getElementById('player-list').children;
console.log(players.value);
There are a number of ways to go about it:
Add the inputs to an array as you create them
Add a unique class to each player input then use document.querySelectorAll('.className')
Select the inputs based on inputs with ID starting with "player"
E.g. the following just adds "Player i" as the value of each input, but it could do other things.
// Creating the input fields
// const x = localStorage.getItem('playersNum');
let x = 3;
let parentDiv = document.getElementById('player-list');
for (let i = 0; i < x; i++) {
let newInput = document.createElement("INPUT");
newInput.setAttribute("type", "text");
newInput.setAttribute("class", "form-control");
newInput.setAttribute("id", `player${i}`);
newInput.setAttribute("placeholder", "Player's Name");
parentDiv.appendChild(newInput);
parentDiv.appendChild(document.createElement('br'));
}
// Get a static NodeList of inputs with ID starting with "player"
let players = document.querySelectorAll('input[id^=player]');
// Iterate over list, adding a value
players.forEach((player, i) => player.value = 'Player ' + i);
div {border: 1px solid #aaaaaa}
<div id="player-list">
</div>
You can reduce your code somewhat by:
The default type is "text" so no need to set it
Set attributes using property access
Append inputs as they're created
so:
let newInput = parentDiv.appendChild(document.createElement("INPUT"));
newInput.class = 'form-control';
newInput.id = `player${i}`;
newInput.placeholder = 'Player\'s Name';
I'm not a fan of using a place holder as the label, much better to have an actual label and use the placeholder as a hint, so:
<label for="player0">Name player 0:<input id="player0" class="form-control"></label>
or similar.

Target Array Value Directly After Selected One

I'm really sorry for I am aware similar questions have already been asked, but whenever I try to do it myself, none seem to apply or work. Basically when a user clicks on one of the elements, I am trying to get the following variables:
the id of the selected element
an array with all of the values prior to selected + selected one
an array with all of the values post-selected (selected not included)
the id of the element directly following the selected one
Thanks to your help in different posts, I have so far managed to complete the first two ones (in italic), but am unable to achieve the other two.
Would anyone know how to do so please? Thank you all in advance for your help!!
jQuery:
var days = ['#monday','#tuesday','#wednesday','#thursday','#friday','#saturday','#sunday'];
$('.days').on('click', function() {
var day = '#'+this.id;
var index = days.indexOf(day)+1;
var prev = days.slice(0, index);
var next = days.slice(index);
var above = days[index];
});
Should look more like this (though I really don't understand your code logic):
var dayIds = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
$('.days').on('click', function() {
//get selected element id
var dayId = this.id;
//find selected position in array and delete all values after
var dayPos = dayIds.indexOf(dayId);
var daysBelow = dayIds.slice(0, dayPos + 1;
//find position of item directly after selected and get value
var dayAfterPos = dayIds.indexOf(dayId) + 1;
var dayAfter = dayIds[dayAfterPos]; //(not working)
//only keep values following selected one
...
console.log(floorsBelow, floorId);
});
This is how you need to slicing the array. I'm not sure all the requirements you have so I have just taken out a snippet to demonstrate how you can get your values.
var dayIds = new Array('#monday','#tuesday','#wednesday','#thursday','#friday','#saturday','#sunday');
const current = '#thursday';
const currentIndex = dayIds.indexOf(current)+1;
const prev = dayIds.slice(0, currentIndex);
const next = dayIds.slice(currentIndex);
console.log(current); //#thursday
console.log(prev); //[ '#monday', '#tuesday', '#wednesday', '#thursday' ]
console.log(next); // [ '#friday', '#saturday', '#sunday' ]
EDIT:
Added newVar to contain next value
var dayIds = new Array('#monday','#tuesday','#wednesday','#thursday','#friday','#saturday','#sunday');
const current = '#thursday';
const currentIndex = dayIds.indexOf(current)+1;
const prev = dayIds.slice(0, currentIndex);
const next = dayIds.slice(currentIndex);
const newVar = dayIds[currentIndex];
console.log(current); //#thursday
console.log(prev); //[ '#monday', '#tuesday', '#wednesday', '#thursday' ]
console.log(next); // [ '#friday', '#saturday', '#sunday' ]
console.log(newVar); // #friday

Append Array Values To List Items

I'm trying to output an array of items to a list. The problems is when I click submit it's adding all the array items to each list item instead of one each time.
JSFIDDLE:
https://jsfiddle.net/b7Lwbrof/
Thanks!
var itemList = [];
var container = document.getElementById('container');
// On click
document.getElementById('submit').addEventListener("click", function(){
var itemValue = document.getElementById('itemValue').value;
// Push to array
itemList.push(itemValue);
// Append to List
for(i=0; i<itemList.length; i++) {
var items = document.createElement("li");
document.getElementById('container').appendChild(items);
items.innerHTML = itemList[i];
}
})
You don't need loop then, just append the item after it has been push to the itemList.
document.getElementById('submit').addEventListener("click", function(){
var itemValue = document.getElementById('itemValue').value;
// Push to array
itemList.push(itemValue);
// Append to List
var items = document.createElement("li");
document.getElementById('container').appendChild(items);
items.innerHTML = itemList[itemList.length-1];
})
items.innerHTML = itemList[itemList.length - 1] // get the last
and NOT
items.innerHTML = itemList[i]
And remove the loop as #digit said .
Fiddle here

Pushing info from form values to object not working

I am having trouble with getting the values of the form i have created with javascript to push into the object.
im in a project creating an addressbook and im stuck here and dont know what to do. So if anyone can help me with that!
The first part of the code is the object function I have created. And appends the contacts to li's.
The second part of the code is to create a form, and loop a form with 5 input fields.
The third and last part of the code is where I dont know what to do or how to do.
I need to get the values of the form and push is it in to the object (as arguments?) to ( contacts = []; ) but isnt working.
//Contactlist funktion
function Contact(fname, lname, address, email, phone) {
this.fname = fname;
this.lname = lname;
this.address = address;
this.email = email;
this.phone = phone;
}
//The contacts
var contacts = [];
// Appending the objects
function theContacts() {
var body = document.getElementsByTagName('body')[0],
outerUL = document.createElement('ul'),
length = contacts.length;
outerUL.className = 'contactlist';
for (var i = 0; i < length; i++) {
var cont = contacts[i],
li = document.createElement('li'),
ul = document.createElement('ul');
li.className = 'contact'; li.innerHTML = cont.fname + ' ' + cont.lname;
ul.className = 'infos';
for (var key in cont) {
var info = document.createElement('li');
info.className = key;
info.innerHTML = cont[key];
ul.appendChild(info);
}
li.appendChild(ul); outerUL.appendChild(li);
}
body.appendChild(outerUL);
}
and then I have this part...
// Calling the object
function addForms(){
var body = document.getElementsByTagName('body')[0]
var form = document.createElement("form");
var myArray = ['fnameValue', 'lnameValue', 'addressValue', 'emailValue', 'phoneValue'];
var texts = ['First Name: ', 'Last Name: ', 'Address: ', 'Email: ', 'Phone: '];
// Create a loop of 5
for(var i = 0; i < 5; i++){
var input = document.createElement('input');
var newlabel = document.createElement('label');
// newlabel.setAttribute('for', myArray[i]);
newlabel.innerHTML = texts[i];
form.appendChild(newlabel);
input.setAttribute('type','text');
input.setAttribute('id', myArray[i]);
// adds the input's to the form.
form.appendChild(input);
}
// adds the forms to the body
body.appendChild(form);
// Add Contact Button
var addContact = document.createElement('input')
addContact.setAttribute('type', 'button')
addContact.setAttribute('id', 'addContact')
addContact.setAttribute('value', 'Add Contact')
form.appendChild(addContact);
var knapp = document.getElementById('addContact');
knapp.addEventListener('click', addNewContact)
}
This is the part that i am stuck with, and well maybe i need to modify the code above too, idk..
Please help me.
function addNewContact() {
var input1 = document.getElementById('fnameValue').value;
var input2 = document.getElementById('lnameValue').value;
var input3 = document.getElementById('addressValue').value;
var input4 = document.getElementById('emailValue').value;
var input5 = document.getElementById('phoneValue').value;
contacts.push(input1, input2, input3, input4, input5);
}
document.getElementById("newButton").addEventListener("click", addForms);
I got some things sorted out, but there is still some work cut out. Anyway, I got the addNewContact() method working after attaching the event listener directly to the button:
addContact.addEventListener('click', addNewContact, false);
In the addNewContact() method I emptied the contacts array before adding any elements to it, because otherwise after the second 'addContact' button click there'll be twice as many elements in the array.
contacts.length = 0; //this empties the array
contacts.push(input1, input2, input3, input4, input5);
Alternatively, instead of doing the above, I tried directly adding a Contact object into contacts array:
contacts.push( new Contact(input1, input2, input3, input4, input5) );
Finally, like Teemu suggested I removed the infinite loop call in the addNewContact() method
After I did those things, I got theContacts() method working partly, which was called in the addNewContact() method. Fiddle

Loop through listbox and add to textbox in javascript

I have a listbox that I am trying to read through all the data in it and put those values in a textbox. I thought I this would use a for loop but it only runs once and then quits.
var listbox = $('#<%=listBox.ClientID%>');
for (var count = 0 ; count <= $('#<%=listBox.ClientID%>').length; count++) {
var existing = $('#<%=stringTextBox.ClientID%>').val();
var value = listbox[count].value;
document.getElementById("<%=stringTextBox.ClientID%>").value = "," + value + existing
}
First: #<%=listBox.ClientID%> is an selector by ID. The idee of IDs is that there is always at most one element with this ID.
Second: var value = should be something like var value = $(<listboxselector>).get(count).val()

Categories

Resources