Javascript: Problem regarding creating a dropdown list using javascript? - javascript

I'm trying to create a dropdown list from an array on my overlay (div element) using javascript.
In this example,
spcodelist = [u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']
Here are related lines of code:
var pcode_form = document.createElement('form');
div.appendChild(pcode_form);
var pcode_select = document.createElement('select');
pcode_form.appendChild(pcode_select);
var i = 0;
var spcodelist = document.getElementById('spcodelist').value;
spcodelist = spcodelist.replace("[","");
spcodelist = spcodelist.replace("]","");
var spcodearr = new Array();
spcodearr = spcodelist.split(', ');
for (i=0;i<=spcodearr.length;i++){
spcodearr[i] = spcodearr[i].replace(/u'/g,"");
spcodearr[i] = spcodearr[i].replace(/'/g,"");
var pcode_option = document.createElement('option');
pcode_option.text = spcodearr[i];
pcode_option.value = spcodearr[i];
pcode_select.appendChild(pcode_option);
}
With this code, the dropdown list works fine but code after it will not work any more. I don't know what's the problem? How can I solve it? Or is there any better solution? Thank you very much.

I don't know what you are doing wrong, but the following works fine and should work in any browser. I've added a remove button so you can add and remove the select as often as you like.
<script type="text/javascript">
function addSelect(id) {
var div = document.getElementById(id);
var pcode_form = document.createElement('form');
pcode_form.id = 'f0';
div.appendChild(pcode_form);
var pcode_select = document.createElement('select');
pcode_form.appendChild(pcode_select);
var spcodelist = document.getElementById('spcodelist').value;
// Do replaces in one go
spcodelist = spcodelist.replace(/[\[\]\'u ]/g,'');
var spcodearr = spcodelist.split(',');
for (var i=0, iLen=spcodearr.length; i<iLen; i++) {
pcode_select.options[i] = new Option(spcodearr[i],spcodearr[i]);
}
}
</script>
<button onclick="addSelect('d0');">Add select</button>
<button onclick="
var el = document.getElementById('f0');
el.parentNode.removeChild(el);
">Remove form</button>
<div id="d0"></div>
<textarea id="spcodelist" style="display:none">[u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']</textarea>

Related

Can't get child element with DOM

My code looks like this:
function myFunction(result) {
var json = JSON.parse(result)
var jsonKeys = Object.keys(json)
var items = document.getElementById("items");
var adds = items.getElementById("add");
clearA()
var i;
for (i = 0; i < jsonKeys.length; i++) {
var btn = document.createElement("BUTTON");
console.log(jsonKeys[i]);
btn.innerHTML = jsonKeys[i]
btn.setAttribute("id", jsonKeys[i]);
btn.onclick = function() { run(this.id); }
items.appendChild(btn)
}
}
I can get items and use them but when I try to get the child element "add" I get items.getElementById is not a function
This is the html:
<div id="items">
<div id="add">
<input type="submit" value="add" onclick="foo(add)">
</div>
</div>
Change it to:
var items = document.getElementById("items");
var adds = document.getElementById("add");
Since ids are meant to be unique on a document, only document.getElementById exists. You could use items.querySelector('#id'), but this is probably a manifestation of a larger problem where you have similar HTML structure for multiple elements, with duplicated ids. In this case, it is recommended that you switch to classes and use items.querySelector('.classname').

JavaScript checkbox Tree - children automatic checked

folks!
I've a litte problem, this is the situation:
Tree View
I let the tree on basis of the "lvl" create. That means, Bereich ABC is lvl1, Test1.docx is lvl4 and so on. So it's a "fake" Tree. But i have just this lvl information for every object.
I have to check the checkbox if the parent is clicked. that means, if lvl3 is clicked (for example "Originale") the lvl4 and lvl5 have to be checked also.
Do you understand what i mean? I hope so. But i can't make it working. Do you have any ideas?
$('[class^=lvl]').click(function(){
var keepChecking = true;
var currentElement = $(this);
var clickedLevel = getLevel(currentElement);
var checkValue = currentElement.is(':checked');
while (keepChecking) {
currentElement.attr('checked' , checkValue);
// get next element
currentElement = getNextCheckbox(currentElement);
var currentLevel = getLevel(currentElement);
keepChecking = (currentLevel > clickedLevel);
}
});
function getNextCheckbox(checkbox) {
return checkbox.parent().parent().next().children(":first").children(":first");
}
function getLevel(checkbox) {
var currentClass = checkbox.attr('class');
var currentLvl = currentClass.substring(3, currentClass.length);
return parseInt(currentLvl);
}
<TD class="center">
<INPUT TYPE="checkbox" NAME="" class="lvl[LL_REPTAG=PFADLEVEL /] docCheck" VALUE="[LL_REPTAG=DataId /]">
</TD>
I changed your javascript code to this:
function getNextCheckbox(checkbox) {
return checkbox.parent().parent().next().children(":first").children(":first");
}
function getLevel(checkbox) {
var currentClass = checkbox.attr('class');
if (currentClass){
var currentLvl = currentClass.substring(3, currentClass.length);
return parseInt(currentLvl);
}else{
return false;
}
}
$('[class^=lvl]').click(function(){
var currentElement = $(this);
var clickedLevel = getLevel(currentElement);
var checkValue = currentElement.is(':checked');
nextElement = getNextCheckbox(currentElement);
while ( getLevel(nextElement)>clickedLevel) {
currentElement=nextElement;
currentElement.prop('checked' , checkValue);
nextElement = getNextCheckbox(currentElement);
}
});
You can also play with it here: https://jsfiddle.net/1r73vy7z/1/
Enjoy :)

Taking tab example from fiddle ans use in my project

http://jsfiddle.net/738wtmhs/1/
using above example in fiddle in my own project: for the purpose of this exercise I am using DOM methods to create and append the elements.
function GetFeatureProperties(feature) {
//add header to 1st FirstTabContent
var featureHeader = "<center><b> <FONT COLOR='FF6600'> Feature Properties </FONT> </b> </center> </br>";
var FirstTabContent = document.createElement('div');
FirstTabContent.id = "tabs-1";
FirstTabContent.innerHTML = featureHeader;
//Second Tab
var SecondTabContent = document.createElement('div');
SecondTabContent.id = "tabs-2";
var newImage = document.createElement("img");
newImage.src = "http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg";
newImage.width = "100";
newImage.height = "100";
SecondTabContent.appendChild(newImage);
//add li and ul
var DivHolding2Tabs = document.createElement('div');
DivHolding2Tabs.class = "shoptab";
var header2 = document.createElement('h2');
header2.innerHTML = "Feature";
DivHolding2Tabs.appendChild(header2);
var _ul = document.createElement('ul');
var _anchor1 = document.createElement("a");
_anchor1.href = "#tabs-1";
_anchor1.innerHTML = "Info";
var _li1 = document.createElement('li');
_li1.appendChild(_anchor1);
var _anchor2 = document.createElement("a");
_anchor2.href = "#tabs-2";
_anchor2.innerHTML = "Images";
var _li2 = document.createElement('li');
_li2.appendChild(_anchor2);
_ul.appendChild(_li1);
_ul.appendChild(_li2);
DivHolding2Tabs.appendChild(_ul);
DivHolding2Tabs.appendChild(FirstTabContent);
DivHolding2Tabs.appendChild(SecondTabContent);
var jelm = $(DivHolding2Tabs); //convert to jQuery Element
var htmlElm = jelm[0]; //convert to HTML Element
var OuterDiv = document.createElement('div');
OuterDiv.id = "loc-list";
OuterDiv.appendChild(htmlElm);
return OuterDiv.innerHTML;
}
and this looks like the image seen below....if I click on the link 'image' the page jumps a bit but nothing happens and nothing happens when I press 'info' also I have included the CSS in my project so why arnt the tabs showing and yes I am using jquery ui 1.10.3.custom.js
---------------------------------------------------------------------------------------------
UPDATE
<ul id="list"><li><div><h2>Feature</h2><ul><li>Info</li><li>Images</li></ul><div id="tabs-1"><center><b> <font color="FF6600"> Feature Properties </font> </b> </center> <br></div><div id="tabs-2"><img src="http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg" width="100" height="100"></div></div></li></ul>
Also changed from jquery 1.10.3 custom to jquery 1.11.2.custom with all the downloaded tabs selected
If you look at this fiddle, I managed to make it work.
Here's the possible problems
1) I changed return OuterDiv.innerHTML because I needed the <div id="loc-list"> to be part of the code to initialize it. You gave it an id so my guess is you wanted it to be included but by doing innerHTML, you didn't get it.
2) Once your function returns, you need to initialize the tabs with $('#loc-list').tabs();

Changing DOM but not appearing in browser

Using jQuery I am making an ajax call to append data to some input fields, jquery is changing the DOM but the changes are not appearing in the inputs until I click on them.
Here is my jquery code:
var data_track = '';
var data_image = '';
var data_artist = '';
var data_album = '';
var data_duration = '';
var data_mbid = '';
if(data.track.name) {data_track = data.track.name;}else{ data_track = '';}
if(data.track.album) {data_image = data.track.album.image[3]['#text'];}else{ data_image = 'http://placehold.it/250x250';}
if(data.track.artist.name) {data_artist = data.track.artist.name;}else{ data_artist = '';}
if(data.track.album) {data_album = data.track.album.title;}else{ data_album = '';}
if(data.track.duration) {data_duration = data.track.duration;}else{ data_duration = '';}
if(data.track.mbid) {data_mbid = data.track.mbid;}else{ data_mbid = '';}
$('#track-name').val(data_track);
$('#image').val(data_image);
$('#image_preview').attr('src', data_image);
$('#artist').val(data_artist);
$('#album').val(data_album);
$('#duration').val(data_duration);
$('#mbid').val(data_mbid);
$('#results').html('');
It works for me: http://jsfiddle.net/b4revvz6/2/
Check your data object;
There was another problem this code was inside ajax call and when i scored it $('#results').html('');
out of ajax, code working perfectly

How to create a clickable list of divs with sub items using JavaScript

I want to create a list of clickable divs from arrays using Javascript, where the list structure has to be something like this:-
<div id="outerContainer">
<div id="listContainer">
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
</div>
</div>
I want to extract the values of itemId, itemTitle and itemStatus from three arrays itemIdData[ ], itemTitleData[ ] and itemStatusData[ ] respectively, to create the whole list.
Also, when I click on any of the listElements, I want an alert showing the itemId. Can anyone help me with this problem.
If you're using jQuery, then try something like this:
$("#listContainer").on("click", "div", function () {
console.log("jQuery Event Delegation");
alert($(this).find(">:first-child").attr("id"));
});
It's possible to write the same thing without jQuery, but will take further lines of code - I'm conveying the idea of delegation here (there are extensive existing docs and examples on the JQuery site, and here on this site).
NB: the code you're submitted in the question can't(shouldn't) have multiple DOM elements with same IDs (that's what classes are for - for semantically similar elements). Also, trying to emulate a list using divs instead of li elements is perhaps not best practice.
After a bit of experimentation, understood what I was doing wrong and how to get it done.
Here's the code:-
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
for (var i = 0; i < json.length; i++) {
//create the element container and attach it to listContainer.
var listElement = document.createElement("div");
listElement.id = i;
listElement.className = "listItemContainer";
listElement.addEventListener("click", function(e){
var itemId = e.target.children[1].innerHTML;
alert(itemId);
});
listContainer.appendChild(listElement);
//create and attach the subchilds for listElement.
var itemTitle = document.createElement("span");
itemTitle.innerHTML = postTitleData[i];
itemTitle.id = 'title'+i;
itemTitle.className = "itemTitle";
listElement.appendChild(itemTitle);
var itemId = document.createElement("div");
itemId.innerHTML = postIdData[i];
itemId.id = 'id'+i;
itemId.className = "itemId";
listElement.appendChild(itemId);
var itemStatus = document.createElement("span");
itemStatus.innerHTML = postStatusData[i];
itemStatus.id = 'status'+i;
itemStatus.className = "itemStatus";
listElement.appendChild(itemStatus);
}
Tried something like this which isn't quite working!
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
var listElement = document.createElement("div");
listContainer.appendChild(listElement);
listElement.className = "listItemContainer";
for (var i = 0; i < json.length; i++) {
var itemId = document.createElement("div");
itemId.innerHTML = idData[i];
listElement.appendChild(itemId);
itemId.className = "itemId";
var itemTitle = document.createElement("div");
itemTitle.innerHTML = titleData[i];
listElement.appendChild(itemTitle);
itemTitle.className = "itemTitle";
var itemStatus = document.createElement("div");
itemStatus.innerHTML = statusData[i];
listElement.appendChild(itemStatus);
itemStatus.className = "itemStatus";
listElement.appendChild(document.createElement("hr"));
var elementId = 'ListElement'+i;
listElement.id = elementId;
listElement.addEventListener("click", function(){
alert(document.getElementById(elementId).innerHTML);
});
}

Categories

Resources