Dynamically Load Div Elements and Assign IDs - javascript

I understand how to dynamically load HTML, I am having trouble understanding how I load it, assign, and keep track of IDs for elements inside the loaded div.
This is my main block
<div id="add-equip-container">
<div id="add-equip-content">
</div>
<button id="add-equipment">Add More Equipment</button>
<button id="submit-equipment">Submit Equipment</button>
</div>
Now, every time add-equipment is clicked, I want to load the following block into add-equip-content.
<div class="add-equip-form">
<input id="?" type="text" placeholder="Equipment Description..."/></br>
<input id="?" type="text" placeholder="Equipment Number"/></br>
<input id="?" type="text" placeholder="Other Stuff..."/></br>
</div>
Each block would be inserted beneath the previous one loaded. I have no idea how to assign and keep track of the various IDs that will be dished out during this operation. I would love a solution that does not involve jQuery. I am trying to lean vanilla JavaScript before I get into frameworks.
I am sure there may be a question or blog or something on this already, but I just don't know the best keywords to search for. Any time I use "Dynamically Load HTML" in the search keywords, all I get is AJAX Tutorial results.
Thanks in advance for any help!

One solution would be not actually load the HTML, but to create it via Javascript. This would be useful in your case as you are adding the same code to the page, only with different ID's. I would write a function like this:
var form_index = 0;
//elem is the element you are appending to.
function addForm(elem) {
//create the container
var form_container = document.createElement("div");
form_container.className = "add-equip-form";
//description input
var desc = document.createElement('input');
desc.id = "equip-desc-" + form_index;
desc.type = "text";
desc.placeholder = "Equipment Description...";
//Equipment number input
var num = document.createElement('input');
num.id = "equip-num-" + form_index;
num.type = "text";
num.placeholder = "Equipment Number";
//Other
var other = document.createElement('input');
other.id = "equip-other-" + form_index;
other.type = "text";
desc.placeholder = "Other Stuff...";
//append inputs
form_container.appendChild(desc);
form_container.appendChild(num);
form_container.appendChild(other);
//append form
elem.appendChild(form_container);
form_index++;
}
Then, to access your created ID's, all you need to know is the index of the containing div within your parent elem. See here for a javascript solution. Once you have the index, getting the form data is as easy as using your index to query based on ID's.

This should do it. You may or may not need to do the elements.push(content) if you don't need to refer back to these elements in an array. Could just iterate a counter instead.
var add_equip_content = document.getElementById('add-equip-content'),
add_equip_btn = document.getElementById('add-equipment'),
elements = [];
add_equip_btn.addEventListener('click', addEquipment, true);
function addEquipment(event){
var content = document.createElement('div'),
html = '';
content.className = 'add-equip-form';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Description..."/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Number"/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Other Stuff..."/></br>';
content.innerHTML = html;
add_equip_content.appendChild(content);
elements.push(content);
}

Related

How do I Separate an Array Value from input to HTML

I'm getting this value from the page source (after the page finished loading), the data is coming from a back-end process that populates a hidden text input on the page. I wish to separate this data and then display it in HTML format.
This is the code from 'View Page Source'
<input name="hiddenUserStats" type="hidden" id="hiddenUserStats" value="
99.0~35.0~8.0~.0~1.0~6.0~3.0~.0~1.0~3.8~1.8~1.0~.0~16.0" />
On the value, I'm assuming that each .0~ separates the true value that I wish to separate and display. Anyone know what would be the best step to separate and display such data? Do I start with separating them in variables?
You can use split() function to separate your stats values.
var value = document.getElementById('hiddenUserStats').getAttribute('value');
var stats = value.split('~');
for (i = 0; i < stats.length; i++)
{
var div = document.createElement('div');
div.innerText = stats[i];
document.body.appendChild(div);
}
<body>
<input name="hiddenUserStats" type="hidden" id="hiddenUserStats" value="
99.0~35.0~8.0~.0~1.0~6.0~3.0~.0~1.0~3.8~1.8~1.0~.0~16.0" />
</body>
Here is another way using native array methods;
document.getElementById('hiddenUserStats')
.getAttribute('value')
.split('~')
.map(function(val, i) {
return '<div>' + i + ': '+ val + '</div>';
})
.forEach(function(el) {
document.body.innerHTML += el;
});

Pull first instance of input and add id via JS

I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Adding code to div clears input val

I have a JS function that adds divs of the class PizzaBox to an empty div called PizzaBoxHolder. Why is it that whenever a new line is created, the user-inputted values in the inputs are replaced with the placeholders? Also, as a side note, should I even be using a place holder for a color input?
function newBox
{
numOfBoxes += 1; //This is a global variable declared elsewhere, other functions use it but only this one modifies it
var pizzaBoxCode = "<div class = 'PizzaBox'>"
+ " <h6>Box number " + numOfBoxes + "</h6>"
+ " <p>Color: <input type = 'color' class = 'boxColor' placeholder = '#000000'/></p>"
+ " <p>Toppings: <input type = 'text' class = 'toppings' placeholder = 'Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>"
+ "</div>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder") //Empty div until this function fills it up
PizzaBoxHolder.innerHTML += pizzaBoxCode;
}
Any help is appreciated. Thanks!
The way you're currently doing it, is resetting the entire innerHTML of your main PizzaBoxHolder element. By resetting the HTML, you're losing the current values. If you change the code to create an element, and then call .appendChild, it'll work as expected. The reason is, you're only appending a node to the current element.
var pizza = document.createElement("div");
pizza.className += "PizzaBox";
pizza.innerHTML = "<h6>Box number " + numOfBoxes + "</h6><p>Color: <input type='color' class='boxColor' placeholder = '#000000'/></p><p>Toppings: <input type='text' class='toppings' placeholder='Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder");
PizzaBoxHolder.appendChild(pizza);
Working fiddle.

How to add and use a Div as a total calculator using Javascript?

I need to make a function which calculates the sum of a users input and compare it to a previously given value, returning the result to the user.
e.g. You previously said you eat 20 meals a week but you have currently listed 5 Dinners, 7 Lunches and 36 Breakfasts. This totals 48 meals.
So far I can read my inputs and add them to a variable as the respondent types it in, showing this in an already existing div. But I need to create a div to show it in for it's actual use. This is where I'm having problems as I can't get this code working.
Note I'm new to JS so some of my code might make no sense. This is everything I've got so far, the bit commented out is what is causing trouble, the rest (assuming I have a div ID'd as 'output') works fine:
<html>
<head>
<script>
var count = 0;
function summer() {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
count = num1+num2+num3;
// if(!document.getElementById("output")) {
// var newDiv = document.createElement('div');
// var divIdName = 'output';
// var myDiv = document.getElementById('buttoner');
// var content = document.createTextNode("")
// newDiv.setAttribute('id',divIdName);
// newDiv.appendChild(content);
// document.body.insertBefore(newDiv, myDiv)
// };
document.getElementById("output").innerHTML = "Your running total = "+count
};
</script>
</head>
<body>
<input type="text" id="number1" onKeyUp="summer()" name="number" />
<input type="text" id="number2" onKeyUp="summer()" name="number" />
<input type="text" id="number3" onKeyUp="summer()" name="number" />
<div id='Buttoner'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button>
</div>
<br>
</body>
</html>
Thanks!
edit: thought it might be worth noting that the 'buttoner' div is left over from a previous stage of experimenting and is now used as a placemarker for inserting the new div.
Your problem seems quite simple to me. If that is really all your HTML, your only problem is you don't have the output div.
You can solve this in some ways. Using pure JavaScript...
var output = document.createElement("div"); // Creates a <div> element
output.innerHTML = "Your running total = " + count;
document.body.appendChild(output); // Add the <div> to the end of the <body>
Another way is to put the output div in the HTML, this way you won't even need to change your script:
<div id="output"></div>
If you want the output not to be visible before the input, you can CSS it a little...
<div id="output" style="display: none;"></div>
And make it visible with Javascript whenever you want.
var output = document.getElementById('output');
output.style.display = 'block'; // or 'inline-block', or 'inline', etc. See what fits you better
As you're beginnning with Javascript, I'd recommend you start in the right path by reading on unobstrusive Javascript. I can update the answer with some unobstrusive JS if you want.
UPDATE: If you want to substitute the button div with the new output div, you can simply change the names from output to button / buttoner / whatever you want.
UPDATE 2: Seems like I didn't understand your question correctly. If you want to store the previous answer, you can do it in a variety of ways as well.
One is to store the current answer in a hidden field. For example...
<input type="hidden" id="prevAnswer" value="0" />
Then, in your Javascript, you can do it like this:
var prevAnswer = document.getElementById("prevAnswer")
var prevAnswerValue = parseFloat(prevAnswer.value) || 0;
output.innerHTML = "You previously said you eat " + prevAnswerValue + " meals a week but you have currently listed " + num1 + " Dinners, " + num2 + " Lunches and " + num3 + " Breakfasts. This totals " + count + " meals.";
prevAnswer.value = count;
So you will always have the Previous Answer whenever you calculate a new one.
Try this fiddle:
http://jsfiddle.net/Q65BT/
var pre =0;
var count = 0;
function summer(a) {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
if(a==1)
{
pre=count;
count = num1+num2+num3;
document.getElementById("output").innerHTML = "You previously said you eat "+pre+" meals a week but you have currently listed "+num1+" Dinners, "+num2+" Lunches and "+num3+" Breakfasts. This totals "+count+" meals.";
}
}
I'm not sure what behavior you are missing. When I uncomment that block, it seems to work fine. The new DIV is being created on the fly if it didn't already exist.
The code is wordier than necessary, but if as you say, you're a beginner, this is not a bad thing. Here's some possible clean-up:
if (!document.getElementById("output")) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'output');
var myDiv = document.getElementById('buttoner');
document.body.insertBefore(newDiv, myDiv)
};

Commands in Javascript code are overwritten by the last one

I have stacked with my javascript code. In my app I am also using jQuery for faster writing some of the parts.
The thing is that after adding functionality to input files only the one added to the last is working. I found that maybe the reason is this same name of function with this same parameters. So to be sure I added to one my function which I want to use and to the other (I mean the first one) alert with simple text.
This is my code:
newRow.innerHTML = "<a href='#' class='editName'>"+ddList.ddElements[ddList.ddEl.id]+'</a>';
newRow.innerHTML += ' X:<input type="text" id="x'+ddList.ddEl.id+'" name="x'+ddList.ddEl.id+'" size=3 value=0>';
var xField = document.getElementById('x'+ddList.ddEl.id);
xField.relatedElement = newRow;
newRow.innerHTML += ' Y:<input type="text" id="y'+ddList.ddEl.id+'" name="y'+ddList.ddEl.id+'" size=3 value=0>';
var yField = document.getElementById('y'+ddList.ddEl.id);
yField.relatedElement = newRow;
$(xField).blur(function(){alert('Handler for X.blur() called.')});
$(yField).blur(function(){ddList.setObjectPosition(yField,obj,'y');});
if(RegExprText.test(ddList.ddEl.id))
{
newRow.innerHTML += '<br>Kolor:';
var element = document.createElement('input');
element.setAttribute('id', 'c'+ddList.ddEl.id);
element.setAttribute('name', 'c'+ddList.ddEl.id);
element.setAttribute('type', 'text');
element.setAttribute('class', 'color');
element.setAttribute('size', '6');
newRow.appendChild(element);
var myPicker = new jscolor.color(element, {});
$(element).blur(function(){ddList.setColor(element,obj);});
}
var links = newRow.getElementsByTagName('a');
var editLink = links[links.length-1];
editLink.relatedElement = newRow;
$(editLink).click(function(){ddList.deleteObject(obj,newRow);});
So when I have got only X and Y input fields then only Y is active. When I have got X, Y and colorPicker then only colorPicker works.
Interesting thing is that always is working last line of code - editLink.
And I have been trying to change
xField.relatedElement = newRow;
on
newRow.addChild(xField);
It doesn't work either.
Thanks for answers in advance.
First you do
xField.relatedElement = newRow;
And then you change
newRow.innerHTML
which will of course be reflected in the relatedElement.
If you want three different DOM elements, you have to make three different DOM elements, and not just one that you assign to three places and whose content you change three times.

Categories

Resources