I have created function for creating a div, when u selet the value in dropdown box , based upon the length the number of divs will be created , so the code is
<select onchange="test()" id="selected_opt">
<option value="0" selected>-Select-</option>
<option value="1">Communication</option>
<option value="2">XXXXXXXXXXXXX</option>
</select>
the function test is
function test(){
var result = get_id.options[get_id.selectedIndex].value;
if(result == 1){
var i = 0,
c = model_details_json.communication,
j = c.length,
communications_div = document.getElementById("model_communication");
if(j == 0){
alert('nothing');
}
for (; i<j; i++){
var communication = c[i];
var create_div = document.createElement('div');
create_div.id = 'communication_id'+i;
create_div.name = 'communication';
var create_anchor = document.createElement('a');
create_anchor.innerHTML = communication.communication_name;
communications_div.appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
create_anchor.setAttribute("href", "javascript:void(0);");
create_anchor.setAttribute("onclick","sample('"+communication.communication_name+"','"+create_div.name+"')");
}
}
for example the length is 6 means the six number of divs will be created , so what the problem is when i again click on communication in select dropdown i.e already the six divs have been created , when do it again then agin six divs are created , so totally 12 divs created when u do it again it goes for 6 multiples.......
so what i need is the number of div would not be repeated. and it should be validate whether the user is clicking the same value in dropdown
Check this to remove div elements considering your parent div model_communication.
You need to implement logic by checking if the div exist and stop the loop when you get a message like 'Div is already removed' as shown in the example.
In order to do so create div elements along with id
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
You need to remove all divs before create the new ones. Try adding a class name to it:
var create_div = document.createElement('div');
create_div.className = 'communication_div';
...
Now you can select the divs. Before the for statement add these lines to remove the divs with 'communication_div' class name:
var divs = document.getElementsByClassName('communication_div');
for(var i=0; i<divs.length; i++) {
divs[i].parentNode.removeChild(divs[i]);
}
Every script run will generate new divs and remove old ones.
use js map object to put selected value or length as key into the map then everytime user clicks a value, first check for its existence in the map. If not found in the map, that would mean length is not repeating and divs will be created.
something like:
var selectedValues = new Array();
.......
var result = get_id.options[get_id.selectedIndex].value;
if(selectedValues["val_"+result]) {
return;
}
selectedValues["val_"+result] = true;
you can check if the div is already created or present on page using getElementById('elementId') before creating it.
like in you code
for (; i<j; i++){
if(! document.getElementById('communication_id'+i)){ // do if element is not present on page
var communication = c[i];
var create_div = document.createElement('div');
create_div.id = 'communication_id'+i;
create_div.name = 'communication';
var create_anchor = document.createElement('a');
create_anchor.innerHTML = communication.communication_name;
communications_div.appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
create_anchor.setAttribute("href", "javascript:void(0);");
create_anchor.setAttribute("onclick",
"sample('"+communication.communication_name+"','"+create_div.name+"')");
}
}
Use replaceChild() instead of appendChild() on the Element object.
Related
I am in the middle of creating an animated icon for everyday use. Selecting one element by id works fine, but using multiple elements in one code doesn't work. How can I make multiple elements work?
the link is my code.
url : https://codepen.io/choimorae/project/editor/XVyLdV enter code here
--> The first document icon can be animated well, but the second document icon cannot be animated.
You loop through the list of elements with the class name of .ico_snap_doc_obj. That looks fine, but when you assign $wrap and $doc_obj it seams like it is just the first element with the class name .ico-doc-wrap you select (and in the second case it should be the second element).
let $doc_obj = document.querySelectorAll(".ico_snap_doc_obj");
let doc_obj_length = $doc_obj.length;
for(var i=0; i<doc_obj_length; i++){
$doc_obj[i].addEventListener("load", function(){
let $wrap = Snap.select(".ico-doc-wrap");
$doc_obj = Snap.select(".ico_snap_doc_obj");
Try to solve this by selecting the elemenst based on their id (like id="ico_snap_doc_wrap") and then give the elements a unique id (like id="ico_snap_doc_wrap_2").
let $doc_obj = document.querySelectorAll(".ico_snap_doc_obj");
let doc_obj_length = $doc_obj.length;
for(var i=0; i<doc_obj_length; i++){
$doc_obj[i].addEventListener("load", function(){
let $wrap = Snap.select("#ico-doc-wrap_" + i);
$doc_obj = Snap.select("#ico_snap_doc_obj_" + i);
So, here you would have two elements, one with the id ico-doc-wrap_0 and one with the id ico-doc-wrap_1.
I'm working on an Ionic-app.
On one of my pages i'm adding elements dynamically to a div-element.
The elements are added but i can't see them on the page.
Just after clicking F5 and running the controller-code again i can see them.
Here's the code for adding the elements:
if ($scope.eigenschaften != null) {
//TODO Eigenschaften in Loop durchgehen und auf panel_dynamic Controls erzeugen
var panel_dynamic = document.getElementById('panel_dynamic');
if (panel_dynamic.hasChildNodes()) {
panel_dynamic.removeChild(panel_dynamic.childNodes[0]);
}
var content = document.createElement('div');
for (n = 0; n <= $scope.eigenschaften.length - 1; n++) {
// Creates a new div with controls
var line = document.createElement('div');
var para = document.createElement('p');
// Creates a div-row
var div_row = document.createElement('div');
div_row.setAttribute('class', 'row');
// Creates a div-col with label
var div_col_label = document.createElement('div');
div_col_label.setAttribute('class', 'col');
div_col_label.appendChild(CreateLabel('font-size:16px;font-weight:bold;', $scope.eigenschaften[n].name));
div_row.appendChild(div_col_label);
// Creates a div-col with control
var div_col_control = document.createElement('div');
div_col_control.setAttribute('class', 'col');
div_col_control.appendChild(CreateTextbox());
div_row.appendChild(div_col_control);
// Adds the div-row to the para
para.appendChild(div_row);
// Adds the new para to the line
line.appendChild(para);
// Adds the new line to the content
content.appendChild(line);
}
// Adds the content-div to panel_dynamic
panel_dynamic.appendChild(content);
}
"eigenschaften" is an array with the data.
It looks like you aren't triggering change detection. You should add the elements using an ng-repeat in your template that's bound to an array or some other iterable on the model instead. Then everytime you add something new to the iterable, it will get added in the view.
Unfortunately i used the id for my container-div "panel_dynamic" even in another template. And JavaScript was getting the other div by getElementById. Now i have changed the ids and it works.
I have some <select> that needs to be populated with dynamic values, coming from an array. My code is pretty simple, the HTML is made by just some empty HTML <select> with the same class (.js-select).
The JS is quite simple:
var $select = $(".js-select");
var ioSensors = [1,2,3]; // The data I want to display in the select
var $optionTpl = $("<option></option>");
for( i=0 ; i<ioSensors.length ; i++ ){
//also show a leading "None" option
if(i === 0){
$optionTpl.attr('value','').text('None').appendTo($select);
}
$optionTpl.attr('value', ioSensors[i]-1).text(ioSensors[i]).appendTo($select);
}
With this code I'm having all my <select> correctly updated, but the last one is populated only with the last value of the Array, not showing even the "None" option.
Can anyone help me understand where the problem is and why is it behaving like that? Thanks!
I've made a pen Here
var $optionTpl = $("<option></option>"); creates an element once, then inside the loop you just keep moving that same element and just giving it a new value.
Create multiple elements inside the loop instead
var $select = $(".js-select");
var ioSensors = [1,2,3];
for( var i = 0; i < ioSensors.length; i++ ){
var $optionTpl = $("<option></option>");
if(i === 0){
$optionTpl.val('').text('None').appendTo($select);
}
$optionTpl.val(ioSensors[i]-1).text(ioSensors[i]).appendTo($select);
}
As others have already suggested, the reason it doesn't work is because you create a single element and keep moving it around. Move the creation of the element inside the loop, for example as follows:
var $select = $(".js-select");
var ioSensors = [1,2,3]; // The data I want to display in the select
for( i=0 ; i<ioSensors.length ; i++ ){
//also show a leading "None" option
if(i === 0){
$("<option></option>").attr('value','').text('None').appendTo($select);
}
$("<option></option>").attr('value', ioSensors[i]-1).text(ioSensors[i]).appendTo($select);
}
If you're wondering why your code seem to work for all the <select>s beside the last, according to the documentation when the target of an append is more than one element, jquery will clone the element for the first N-1 targets, and just move the element for the last:
If an element selected this way is inserted into a single
location elsewhere in the DOM, it will be moved into the
target (not cloned):
...
Important: If there is more than one target element, however,
cloned copies of the inserted element will be created for each
target except for the last one.
You need to clone the element to have multiple elements
var $select = $(".js-select");
var ioSensors = [1, 2, 3]; // The data I want to display in the select
var $optionTpl = $("<option></option>");
for (i = 0; i < ioSensors.length; i++) {
//also show a leading "None" option
if (i === 0) {
$optionTpl.clone().val('').text('None').appendTo($select);
}
$optionTpl.clone().val(ioSensors[i] - 1).text(ioSensors[i]).appendTo($select);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="js-select"></select>
You can also write the same like
var $select = $(".js-select");
var ioSensors = [1, 2, 3]; // The data I want to display in the select
var $optionTpl = $("<option></option>");
$("<option />", {
value: '',
text: 'None'
}).appendTo($select);
ioSensors.forEach(function(item) {
$("<option />", {
value: item - 1,
text: item
}).appendTo($select);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="js-select"></select>
Here is a simple solution (pen of the solution):
var ioSensors = [1,2,3];
$(".js-select").each(function(){
for(var i=0;i<ioSensors.length;i++) {
if(i === 0){
$("<option value=\"\">None</option>").appendTo($(this));
}
$("<option value=\"" + ioSensors[i] + "\">" + ioSensors[i] + "</option>").appendTo($(this));
}
});
I created a small script that counts images that I uploaded/inserted to my html source code. After I inserted images script creates div containers for those images. If I gave three images, then script will create three divs with class name etc. I have css rule with that class name. This was create before any images were in that container. Everything works but I just can't append those newly images to newly created divs. Is there a way using JavaScript only?
Here is a code:
if (document.getElementsByClassName("Multimedia")[0].getElementsByTagName("IMG")) {
total_number_of_images = document.getElementsByClassName("Multimedia")[0].getElementsByTagName("IMG").length;
for (i = 0; i < total_number_of_images; i = i + 1) {
document.getElementsByTagName("IMG")[i].className = "Image_clip";
child = document.getElementsByTagName("IMG")[i];
image_container = document.createElement("DIV");
image_container.className = "Image_container_div";
document.getElementsByClassName("Multimedia")[0].appendChild(image_container);
document.getElementsByTagName("IMG")[i].style.opacity = "0.8";
}
}
I tried somthenig like this:
image_container.appendChild(child);
But then I can get only two images into container... my third is out and also without className. Without this code, I get className for every image
You should cache the reference to elements rather than querying DOM in loops.
If I understood correctly, Your code should look something like the following for wrapping each image in a container <div>:
var container = document.getElementsByClassName("multimedia")[0];
// if there is only one match, use an id instead ------------^ ?
var images = container.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
var img = images[i];
img.className = "imageClip";
img.style.opacity = "0.8"; // Why not define this in imageClip class ..?
imageContainer = document.createElement("div");
imageContainer.className = "imageContainer";
imageContainer.appendChild(img);
container.appendChild(imageContainer);
}
This I get on Yahoo answer. Posted by YaYox: http://jsfiddle.net/ffxad4bq/4
function myFunction() {
var multimedia = document.getElementsByClassName("Multimedia")[0]
var imgs = multimedia.getElementsByTagName("IMG");
for (var i = 0; i < imgs.length; i++) {
imgs[0].className = "Image_clip";
imgs[0].style.opacity = "0.3";
multimedia.innerHTML += '<div class="Image_container_div">'+imgs[0].outerHTML+'</div>';
imgs[0].remove()
}
}
I realized what was the problem. I shouldn't itaret through images. Just leave it on zero because, when loops start, code append one image at a time. When second loop starts I don't have any more 3 images, but two, that is why one image always stays out because loop goes three times.
I'm having a little trouble adding an event listener to elements created dynamically.
I have a list of objects that represent matches a player plays in. And a for loop that iterates through them, creating 4 buttons for each match, a +1, a +2, a -1 and an END button.
However, even if they are well created, and appended where they should be, the event listeners are not kept. Here's a sample of my code:
var container = document.getElementById('container');
for (var i = 0; i < matches.length; i++) {
var row = document.createElement("div");
row.className = "row";
var plusOne = document.createElement("a");
plusOne.id = "plusone_ " + matches[i].id;
plusOne.addEventListener('click', function () {
alert('Clicked on plusOne!')
});
...
// adding plus two, minus one and END the same way
// however, END does have an eventListener on click
row.appendChild(plusOne);
container.appendChild(row);
}
If anyone has any idea why?