I need to display the data entered into several text fields using div elements. There should be a dedicated div for each text input.
I have looked around all I have found is how to create dynamic inputs. But none of them explains how to use the created fields to read the info and display the info
function display_array()
{
var e = "<hr/>";
for (var y=0; y<array.length; y++)
{
e += "Element " + y + " = " + array[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
//Counter to maintain number of textboxes and give them unique id for later reference
var intTextBox = 0;
/**
* Function to add textbox element dynamically
* First we incrementing the counter and creating new div element with unique id
* Then adding new textbox element to this div and finally appending this div to main content.
*/
function addElement() {
intTextBox++;
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'div_' + intTextBox);
objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text" id="tb_' + intTextBox + '" name="tb_' + intTextBox + '"/>';
document.getElementById('content').appendChild(objNewDiv);
}
/**
* Function to remove textbox element dynamically
* check if counter is more than zero then remove the div element with the counter id and reduce the counter
* if counter is zero then show alert as no existing textboxes are there
*/
function removeElement() {
if(0 < intTextBox) {
document.getElementById('content').removeChild(document.getElementById('div_' + intTextBox));
intTextBox--;
} else {
alert("No textbox to remove");
}
}
<p>Demo of adding and removing textboxes dynamically using simple JavaScript</p>
<p>
Add
Remove
</p>
<div id="content"></div>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
i give you 3 changes and not sure if that is what you want,see this demo:
https://jsfiddle.net/xianshenglu/ev1f38L3/
first change: add var array,,,,
var array=document.getElementsByClassName('tb');
second,add .value
e += "Element " + y + " = " + array[y].value + "<br/>";
third,add class="tb"
objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text"
id="tb_' + intTextBox + '" class="tb" name="tb_' + intTextBox + '"/>';
I have updated the code to output two separate text fields but to have it display together is not working.
function display_array()
{
var array=document.getElementsByClassName('tb');
var e = "<hr/>";
var array2=document.getElementsByClassName('tb2');
var e2 = "<hr/>";
for (var y=0; y<array.length; y++)
{
e += array[y].value ''+'' e2 += array2[y].value;
// e2 += "Mac " + y + " = " + array2[y].value;
}
document.getElementById("Result").innerHTML = e + 'm' + e2;
//document.getElementById("Result2").innerHTML = e;
}
//Counter to maintain number of textboxes and give them unique id for later reference
var intTextBox = 0;
var intTextBox2 = 0;
/**
* Function to add textbox element dynamically
* First we incrementing the counter and creating new div element with unique id
* Then adding new textbox element to this div and finally appending this div to main content.
*/
function addElement() {
intTextBox++;
intTextBox2++;
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'div_' + intTextBox);
objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text" id="tb_' + intTextBox + '" class="tb" name="tb_' + intTextBox + '"/>';
document.getElementById('content').appendChild(objNewDiv);
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'div_' + intTextBox);
objNewDiv.innerHTML = 'Textbox1 ' + intTextBox + ': <input type="text" id="tb2_' + intTextBox + '" class="tb2" name="tb2_' + intTextBox + '"/>';
document.getElementById('content').appendChild(objNewDiv);
}
<p>Demo of adding and removing textboxes dynamically using simple JavaScript</p>
<p>
Add
Remove
</p>
<div id="content"></div><div id="content2"></div>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
Related
I am working on a Trello Board using Vanilla Javascript and I am receiving an error on making my Cards . I have used Local and Session Storage to store the cards and lists respectively but I can't figure out why this error persists after I click on the Add Card Board Button
function newTask(x){
card_index= parseInt(localStorage.getItem("card_indices")) ;
//card_index = parseInt(sessionStorage.getItem("card_indices"));
list_index = parseInt(sessionStorage.getItem("index"));
document.getElementById('myTasks').innerHTML +=
'<div id = "list_' + list_index + ' " class="list-item animated zoomIn" > <h2 id = "title_' + list_index +'" onClick = "modifyObj.titleEdit('+ list_index +')" class="list-item__h2">'+x+'</h2><span id = "span_del_' + list_index + '" class ="btn title-delete" onClick ="modifyObj.titleDelete(' + list_index + ')">\u00D7</span><hr>'+
'<input id = "card_del_' + card_index + '" type="text" class="myInput" placeholder="Title...">' +
'<div class="btn add-items " id = "div_add_list_" onClick = "myCard.titleForm(' + list_index + ',' + card_index + ')" >Add List Item</div>'
'</div>'
sessionStorage.setItem("index", parseInt(sessionStorage.getItem("index"))+1);
}
var myCard = {
card:function(index, card_index){
var enteredElement = document.getElementById('card_del_' + card_index).value;
var textNode = document.getElementsByClassName('text_' + card_index);
textNode.innerText = enteredElement;
if (enteredElement === ""){
alert("You must write something ");
}
else{
document.getElementById("text_").style.display = "block";
}
},
titleForm: function(index,card_index){
element = document.getElementById('card_del_' + card_index);
text = '<li style="display:none" class="text_'+ card_index +'"> <span class = "btn items" onClick = "myCard.cardClose()">u00D7</span></li>'
element.insertAdjacentHTML('beforeend', text);
myCard.card(index,card_index);
localStorage.setItem("card_indices", parseInt(localStorage.getItem("card_indices"))+1);
// card_index+=1;
}};
I think the intention is clear: Either you press one button or the other to add the item you typed into the input-field to one or the other shopping list.
However, no matter what or if I write something at all, if I press one of the buttons, it will just add "null" to the list.
Why is that?
function sortItem1() {
document.getElementById("addToMarket").addEventListener("click", addToMarketList);
}
function sortItem2() {
document.getElementById("addToOnline").addEventListener("click", addToOnlineList);
}
var gottaBuy = document.getElementById("item");
var listForMarket = " ";
var listForOnlineShop = " ";
function addToMarketList() {
listForMarket = listForMarket + "<li>" + gottaBuy + "</li>";
document.getElementById("marketList").innerHTML = listForMarket;
document.getElementById("item").value = " ";
}
function addToOnlineList() {
listForOnlineShop = listForOnlineShop + "<li>" + gottaBuy + "</li>"
document.getElementById("onlineList").innerHTML = listForOnlineShop;
document.getElementById("item").value = " ";
}
window.addEventListener("load", sortItem1);
window.addEventListener("load", sortItem2);
<h1>What would you like to add?</h1>
<input type="text" id="item" />
<button type="button" id="addToMarket">Markt</button>
<button type="button" id="addToOnline">Online</button>
<h2>Buy at a store:</h2>
<ul id="marketList"></ul>
<h2>Buy online:</h2>
<ul id="onlineList"></ul>
The line var gottaBuy = document.getElementById("item") just assigns the html tag of the input to the variable.
What you want to retrieve is the value of the input and assigning it based on the button clicked. You can do that by assigning a separate variable within each button handlers and appending .value to get the input value like this:
function addToMarketList() {
var gottaBuy = document.getElementById("item").value;
listForMarket = listForMarket + "<li>" + gottaBuy + "</li>";
document.getElementById("marketList").innerHTML = listForMarket;
document.getElementById("item").value = " ";
}
function addToOnlineList() {
var gottaBuy = document.getElementById("item").value;
listForOnlineShop = listForOnlineShop + "<li>" + gottaBuy + "</li>"
document.getElementById("onlineList").innerHTML = listForOnlineShop;
document.getElementById("item").value = " ";
}
jsFiddle: https://jsfiddle.net/AndrewL64/e9t0rszh/1/
You could select the element from inside the click handlers, so you are sure it is already loaded.
And you also most likely want to add the actual value and not the element itself.
function addToMarketList() {
var gottaBuy = document.getElementById("item");
listForMarket = listForMarket + "<li>" + gottaBuy.value + "</li>";
document.getElementById("marketList").innerHTML = listForMarket;
document.getElementById("item").value = " ";
}
function addToOnlineList() {
var gottaBuy = document.getElementById("item");
listForOnlineShop = listForOnlineShop + "<li>" + gottaBuy.value + "</li>"
document.getElementById("onlineList").innerHTML = listForOnlineShop;
document.getElementById("item").value = " ";
}
I've been struggling with this for around an hour now and rewrote it about three different times and I can't for the life of me figure out what the issue is, regardless of what is entered, everything besides for the name field will return a value, however the name will just return undefined. I've gone over this so many times, I've copy+pasted+modified the working ones, there's not a single typo that I can find... What is going on here?
Item Name: <input type="text" id="item_name" placeholder="Enter a price..."/> </br>
Item Price: <input type="text" id="item_price" placeholder="Enter a price..."/> </br>
Item Description: <input type="text" id="item_description" placeholder="Enter a description..."/> </br>
Item Image(link): <input type="text" id="item_image" placeholder="Enter a image link..."/> </br>
rsid: <input type="text" id="rs_item_id" placeholder="Enter a item id..."/> </br>
rsam: <input type="text" id="rs_item_amount" placeholder="Enter a item amount..."/> </br>
<button id="update">Update item</button>
<script>
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
var button = document.getElementById("update");
button.addEventListener("click", function() {
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
</script>
The problem is that because you make them all global variables the name one clashes with the window.name property.
Either using a different variable name, or creating a closure will work
Put name, price, desc, img, rsid, rsam inside event handler.
var button = document.getElementById("update");
button.addEventListener("click", function() {
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
Demo: http://jsbin.com/fivos/1/edit?html,output
I am showing number counter in one of my section. When I add new betslips to the container the numbers are displaying correctly. However, when I delete any of the row the counter is not getting updated. For example if there are 3 rows numbered 1, 2 and 3 and if I delete row number 2 the updated values are 1 and 3. Infact the counter should reset to 1 and 2.
Here is my JS code
Adding the betslip rows
function createSingleBetDiv(betInfo) {
var id = betInfo['betType'] + '_' + betInfo['productId'] + '_' + betInfo['mpid'],
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b>' + singleBetNumber + '. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'] + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
Function to remove betslip
function removeSingleBet(id) {
// Remove the div
removeElement(id);
// Decrease the betslip counter
decreaseBetSlipCount();
// Decrease bet singles counter
updateBetSinglesCounter();
}
function decreaseBetSlipCount() {
var length = $("#racingBetSlipCount").text().length,
count = $("#racingBetSlipCount").text().substring(1, length-1),
text;
count = parseInt(count);
if (!isNaN(count)) count--;
if (count == 0) text = noSelections;
else text = count;
$("#racingBetSlipCount").text('(' + text + ')');
}
This could be done using only CSS, e.g:
DEMO jsFiddle
HTML:
<div id="bets">
<div class="bet"> some content</div>
<div class="bet"> some content</div>
<div class="bet"> some content</div>
</div>
CSS:
#bets {
counter-reset: rowNumber;
}
#bets .bet {
counter-increment: rowNumber;
}
#bets .bet::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
All row number will be updated automatically when adding/removing any row.
You can manage to do that with following steps;
Enclose bet no with span,
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '<span>. ' + betInfo['horseName'] + '</b></p>');
and I assume you have aouter div called "your_div"
Call below function after every increase and decrease event
function updateBetNo() {
var counter = 1;
$("#your_div .bet_no").each(function(i, val) {
$(this).text(counter);
counter++;
});
}
Make the betNumber findable:
$(leftDiv).append('<p class="title"><b><span class="singleBetNumber">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
After an insert or delete renumber:
$('.singleBedNumber').each(function(idx, el) {
$(el).html('' + (idx + 1));
});
The first problem I see is that $("#racingBetSlipCount") is likely not selecting what you think it is. Since #racingBetSlipCount is an id selector it will only select one item.
To me you need to wrap the betnumber in something accessible so you can update it without having to parse through the title.
So first you would update the creation of the betTitle:
$(leftDiv).append('<p class="title"><b><span class=\'betNum\'>' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
Then you can loop through each and update the number appropriately.
var count = 1;
$.each($(".betNum"), function(){
$(this).html(count++);
});
var intFields = 0;
var maxFields = 10;
function addElement() {
"use strict";
var i, intVal, contentID, newTBDiv, message = null;
intVal = document.getElementById('add').value;
contentID = document.getElementById('content');
message = document.getElementById('message');
if (intFields !== 0) {
for (i = 1; i <= intFields; i++) {
contentID.removeChild(document.getElementById('strText' + i));
}
intFields = 0;
}
if (intVal <= maxFields) {
for (i = 1; i <= intVal; i++) {
intFields = i;
newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intFields);
newTBDiv.innerHTML = "<input placeholder='recipient" + intFields + "#email.com' type='text' name='" + intFields + "'/><a href='javascript:removeElement();'><img id='strImg + " + intFields + "' src='images/minus.png' alt='Add A Field'/></a><input type='text' value='" + newTBDiv.id + "'/>";
contentID.appendChild(newTBDiv);
message.innerHTML = "Successfully added " + intFields + " fields.";
}
} else {
for (i = 1; i <= maxFields; i++) {
intFields = i;
newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intFields);
newTBDiv.innerHTML = "<input placeholder='recipient" + intFields + "#email.com' type='text' name='" + intFields + "'/><a href='javascript:removeElement();'><img id='strImg + " + intFields + "' src='images/minus.png' alt='Add A Field'/></a><input type='text' value='" + newTBDiv.id + "'/>";
contentID.appendChild(newTBDiv);
message.innerHTML = "Unable to create more than 10 receipient fields!";
}
}
}
My script here dynamically adds up to 10 fields where users will be able to enter an email address and to the right of the text box i add an image of a minus sign that calls another script. I'm having trouble working out how to assign and keep track of the minus signs. I need to be able to have the minus sign script's recognize the text box it is by and remove it. I can write the remove script easily enough but I'm unsure of how to tell the image which text box to remove. Any help, suggestions, or comments are greatly appreciated.
Thanks,
Nick S.
You can add a class to the field called minus and then check through like that. I would suggest using jquery for this.
To add the class
$("#element").addClass("minus");
To remove all elements with that class
$("body input").each(function (i) {
if($(this).attr("class") == "minus"){
$(this).remove();
}
});
The two best options, imo, would be 1) DOM-traversal, or 2) manipulating ID fragments.
Under the first way, you would pass a reference to the element where the event takes place (the minus sign) and then navigate the DOM from there to the get the appropriate text box (in jQuery you could use $(this).prev(), for example).
Under the second way, you would assign a prefix or a suffix to the ID of the triggering element (the minus sign), and the same prefix or suffix to the target element (the text box). You can then (again) generate the appropriate ID for your target element by simple string manipulation of the ID from the triggering element.
Is that sufficient to get you started?
Try adding a class to the field and the same class to the minus sign.
So add this right after the setAttribute id,
newTBDiv.setAttribute('class', 'field' + intFields);
then just remove any elements that have that class.