How to get the value from multiple unique ids - javascript

I've been working on a form were i can make extra inputfields and selectfields thanks to this site! Al those fields get unique id (3011, 3012, 3013 to a max of 3019) and (rc1, rc2 etc.)
with a removal link.
var i = 2;
var limit = 10;
function createInput () {
if (i == limit) {
alert("You have reached the limit of adding " + i + " inputs");
}
else
var field_area = document.getElementById('301X')
var div = document.createElement("div");
div.id = 'SA '+i;
var input = document.createElement("input");
div.innerHTML = '301'+i ;
input.id = '301'+i;
input.name = '3011';
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
input.value = "";
input.size = '80';
var rcnode = document.getElementById("rc1") // bepaal var van de select menu id relcode
var rcclone = rcnode.cloneNode(true); // bepaal var van de clone van de select
rcclone.id = 'rc'+i; // het nummeren van id clone
div.appendChild(input);
div.appendChild(rcclone);
field_area.appendChild(div);
and it works fine (would not surprise me that it can be beter) Now I want to catch the values. I succeed to cath it from one value with this script:
var x = 1;
function catchInput () {
var said = '301'+x;
var rcid = 'rc'+x;
var Valsaid = document.getElementById(said).value;
var Valrcid = document.getElementById(rcid).value;
alert (said + ' ' + Valsaid + Valrcid);
}
but I want to catch them all. I have been playing around with arrays and the for-loop but I can't figure it out. Any help, point in the right direction much appreciated.
Herman

There are several possibilities :
1) prefix your id's with a common string, then use jQuery (for example) to find all elements with id's starting with this prefix : $('[id^=yourPrefix]')
2) if you want to stick with POJS, "group" these dynamically generated elements by assigning a common class to them. you can then use getElementsByClassName() , which is not available in all browsers though (actually only a problem with IE <= 8)
3) still if you want to stick with POJS but need extended browser support, you can prefix your id's with a common string, then loop on your elements (maybe restricting the set using getElementsByTagName()) and test if the id string starts with this prefix using indexOf() , for example (that's most probably how jQuery implements this functionality)
Hope this helps...

Related

How can i append a child to a div that has a random number as an id?

READ THE EDIT AT THE BOTTOM! :)
I am making a little website where the user can fill in multiple text boxes, and when they come back later, their text boxes come back. (Pretty much a terrible helpdesk system using localstorage).
I have three fields the user can fill out, then when the fields are submitted they should appear below, in a div. Currently i am only able to get the first field to be shown, as i append it to a static div, but i want to append the rest of the fields to the first one. This wouldnt be too hard, but i cant seem to append a child to a div that doesnt have a set ID (without somehow hardcoding it).
I have tried things like
divAId + i.appendChild(divB)
And
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
, but nothing seems to work.
Here is the code in question:
gradStorages = JSON.parse(localStorage.getItem('gradStorages'));
var iFeil = 0;
function feilDivCreate(){
const divF = document.createElement("div");
divF.className = "feilDiv";
divF.id = "feilDivId" + iFeil;
listIdIncrement();
divF.appendChild(document.createTextNode(set1));
textContainer2.appendChild(divF);
iFeil += 1;
}
var iOffer = 0;
var feilIdNumber = "feilId";
function offerDivCreate(){
const divO = document.createElement("div");
divO.className = "offerDiv";
divO.id = "offerDivId" + iOffer;
listIdIncrement();
divO.appendChild(document.createTextNode(set1));
feilIdNumber + iOffer.appendChild(divO);
iOffer += 1;
console.log(feilIdNumber + "TATATATAT");
}
var set1 = "set1 Not Defined";
var set2 = "set2 Not Defined";
var set3 = "set3 Not Defined";
function extract(){
for(let i = 0; i < feilStorages.length; i++){
set1 = feilStorages[i];
set2 = offerStorages[i];
set3 = gradStorages[i];
feilDivCreate();
offerDivCreate();
gradDivCreate(); // same as offerDiv
}
}
(can add more, or make a jsfiddle if needed.)
I need a way to append offerDiv to feilDiv, but its not so simple because feilDiv's id is feilDivId + i where i goes up by one for each new feildiv added.
Any tips for how i can achieve this?
EDIT: Here is a simplified version, showing all the code necessary to understand what im trying to do. https://codepen.io/kossi1337/pen/xxKPRvv
Might be easier to just make a new question with all the new code, but im not too sure if that allowed.. Let me know if i have to change anything about my question :)
In this code:
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
It seems like you are trying to append an element to the Integer value you just created by adding i to some number. You need to grab the parent node, either via document.querySelector or using jQuery, then append to the parent. The browser has no idea what to do when you try to append markup to a number. It expects a DOM location that it will be appended to.
It should be like this:
var divAIdNumber = divAId + i;
var html = "<div class='" + divAIdNumber + "'> Content here </div>";
var element = document.querySelector(".my-element");
element.appendChild(html);

Need help changing appendChild to replaceChild

Is there an easy way to change this from appendChild to replaceChild?
This of course continuously adds more ele. Also for some reason it doesn't put the value inside the DIV or SPAN, seems to put below it.
var para = document.createElement("P");
var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;
para.appendChild(total);
document.getElementById("total_id").appendChild(para);
Its updating this:
<div class="prod_totals">Order Total: $<span id="total_id"></span></div>
you can simply use innerHTML instead of appendChild
document.getElementById("total_id").innerHTML = parseFloat((subT + tax).toFixed(2));
Because you're not inserting any user input values inside the total_id element and also as far as the question mentions, its data is not later passed to the server I think you'll be safe using the innerHTML here. But if for any reasons you'd still like to use replaceChild you could do it like this:
var para = document.createElement("P");
var total = document.createTextNode(parseFloat((subT + tax).toFixed(2))) ;
para.appendChild(total);
var existingText=document.getElementById("total_id").querySelector('p');
if(existingText){
document.getElementById("total_id").replaceChild(existingText, para);
}
else{
document.getElementById("total_id").appendChild(para);
}
There's no need to use .replaceChild here, you can simply check if the element was already created before trying to update it.
Note that you were trying to insert a p element inside a span which is wrong and is not valid HTML markup, you can see in the span documentation that its possible content is only Phrasing content, so you better use another span.
This is how should be your code:
var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
para = document.createElement("span");
}
var total = parseFloat((subT + tax).toFixed(2));
para.innerText = total;
document.getElementById("total_id").appendChild(para);
And here's a Demo:
var para = document.querySelector("#total_id span");
if (!para || para.length == 0) {
para = document.createElement("span");
}
var total = new Date();
para.innerText = total;
document.getElementById("total_id").appendChild(para);
<div class="prod_totals">Order Total: $<span id="total_id"></span></div>

Trying to print dynamic content and one variable is not being accessed at "onclick" event

var noOfPersons;
function printEmptyBoxes() {
noOfPersons = document.getElementById("NumberOfPeople").value;
var dynamicAttach = document.getElementById("dynamic_Content");
for(var i=0;i<noOfPersons;i++) {
var name = document.createElement("input");
var expenditure = document.createElement("input");
var button1 = document.createElement("input");
var button2 = document.createElement("input");
name.setAttribute("type", "text");
name.setAttribute("id", "person"+(i+1)+"");
expenditure.setAttribute("type", "text");
expenditure.setAttribute("id", "Expenditure"+(i+1)+"");
button1.setAttribute("type", "button");
button1.setAttribute("value", "+");
button1.setAttribute("onclick", 'document.getElementById("Expenditure"+(i+1)+"").value += "+"');
button2.setAttribute("type", "button");
button2.setAttribute("value", "=");
// button2.setAttribute("onclick", "x += eva);
dynamicAttach.appendChild(name);
dynamicAttach.appendChild(expenditure);
dynamicAttach.appendChild(button1);
dynamicAttach.appendChild(button2);
var brk = document.createElement("br");
dynamicAttach.appendChild(brk);
}
}
/*
It's showing uncaught reference error unable to access i on "onclick" but my i variable is getting accessed at both of id attributes I have created before that statement("person"+(i+1)+"");
*/
In your case, the code is not exactly the same way you look
'document.getElementById("Expenditure"+(i+1)+"").value += "+"'
I believe what you want is have Expenditure+(i+1) (after calculate i+1) as the ID, but since it is covered by a single quote (before document and at the end), it still treat Expenditure+(i+1) (before calculate i+1) as an actual ID.
The easy way for you to check this error is look at the color of string in your editor, you will easily see that those 2 color are not the same.
So, how to fix?
Simplest way, set the ID as a different variable and use it later on
var expID = "expenditure" + (i+1);
Furthermore, don't use setAttribute for onclick event. Use .onclick() instead
button1.onclick = function_name;
Have a loop through my simple code here:
http://jsfiddle.net/mankinchi/7x6z6hgr/

javascript not changing the text color

I have a function that I want to change the font color of the user entered string if it is equal to a certain word located in an array.. So far when I step through it it says that it changes the font color but it actually never updates it to the screen and I don't know why. Here is what I have so far
function getLastWord() {
var input = document.getElementById("my_text");
//var input = document.getElementById(textArea.value);
//var lineIn = document.getElementById(my_text).innerHTML;
var inputValue = input.value;
var lastWordTyped
var changeColorOfWord;
if (input == null) {
input == " ";
}
//lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
lastWordTyped = inputValue.substr(inputValue.trim().lastIndexOf(" ") + 1);
if (input != null) {
for (var i = 0; i < reservedKeyWords.length; i++) {
if (reservedKeyWords[i] === lastWordTyped) {
lastWordTyped = lastWordTyped.fontcolor("blue");
my_text.replace(inputValue, lastWordTyped);
} else {
}
}
}
}
I see two issues with the code thus far.
You are using 'fontcolor("blue")' parameter on the lastWordTyped. The proper syntax to change color is element.style.color="#CCC".
You will need to wrap the last typed word in a span so you can target it and apply the color to just that word.
string.fontcolor is legacy, and should not be used even though I could see it as a viable option in this case
Essentially, what you are doing is adding font tags around the word:
var txt = 'hello world';
txt = txt.fontcolor('blue');
//txt = '<font color="blue">hello world</font>';
You do not show what you do with the result, but if you actually put it in an HTML element it should work, even though instead of using fontcolor, I'd rather use element.style.color. This would require slightly more work though:
var ele = document.querySelector('#my_text');
ele.style.color = 'blue';
ele.innerHTML = lastWordTyped;
If you still want to go with the .fontcolor method, you could just keep what you have in the question and add
input.innerHTML = my_text;

Update div with jQuery upon entry of data

I have a form with four text input elements. Every time one of them is updated, I want the sum of the four text input boxes to be displayed in a div below without the user pushing a button. Here's what I have so far (I got the idea from here [does this only work with select?]):
var getSum = function() {
var email = $('#emailDown').val();
var internet = $('#internetDown').val();
var server = $('#serverDown').val();
var desktop = $('#pcDown').val();
//TODO:Check for integers (not needed with sliders)
var sum = email + internet + server + desktop;
$('totalHoursDown').html(sum);
}
$('#emailDown').change(getSum(event));
$('#internetDown').change(getSum(event));
$('#serverDown').change(getSum(event));
$('#pcDown').change(getSum(event));
Currently, it's not updating. (Don't worry about validating). I'm new to PHP, so I'm not sure if I should be using it in this instance.
You are missing a # or . in your selector, depending on if totalHoursDown is a class or an ID:
$('totalHoursDown').html(sum);
// Should be this if ID
$('#totalHoursDown').html(sum);
// or this if class
$('.totalHoursDown').html(sum);
Update:
I modified the code by jmar777 a bit to make it work. Try this instead:
$(function(){
var $fields = $('#emailDown, #internetDown, #serverDown, #pcDown'),
$totalHoursDown = $('#totalHoursDown');
$fields.change(function() {
var sum = 0;
$fields.each(function()
{
var val = parseInt($(this).val(), 10);
sum += (isNaN(val)) ? 0 : val;
});
$totalHoursDown.html(sum);
});
});
​Here is a working fiddle as well: http://jsfiddle.net/mSqtD/
Try this:
var $fields = $('#emailDown, #internetDown, #serverDown, #pcDown'),
$totalHoursDown = $('#totalHoursDown');
$fields.change(function() {
var sum = 0;
$fields.each(function() { sum += $(this).val(); });
$totalHoursDown.html(sum);
});
Also, in your example, you had $('totalHoursDown').html(sum);, which I'm assuming was intended to be an ID selector (i.e., $('#totalHoursDown').html(sum);.

Categories