Insert html element into a previously dynamically inserted element? - javascript

Here is my first question here, I've been looking for an small clue on many researches but didn't found any piece of answer, hope it's not a silly thing.
I'll try to be straight: I'm working on a website dealing with xml files (data is stored in an array then displayed and fully editable).
Until now and despite some troubles I figured out, everything works fine.
I loop on my array to get all the required string then create jQuery object (such as $("<input id='xxx' value='yyy' />") that I appendTo a specific div).
At first start, I have an empty #insertXml div (written in my html).
One my xml files parsed and my array ready, I dynamcically create a #content div appended to my #insertXml, then for each index I'll have its key written in a #keyInput" div (dynamic insert, only once), then 1st value in a #lang1 div (still dynamic insert), 2nd in #lang2 div, etc.
lang1, lang2, etc are variables, so it's written:
$("<input .../>").appendTo("#"+langN);
where langN changes on each loop.
Everything works FINE!... at 1st display :/
The trouble is, when I'm using my function that creates new data.
I work first on a modal window, to retrieve user values through the listener function, then pass it to another function that pushes it in my array.
I debugged it, that works, my array is correctly updated.
Then I want to simply refresh my page, so I try, the same way I did previously for my whole data, to append a few inputs.
It works then correctly on my #keyInput div, but NOT on my #lang divs !?!?!
No matter how I try (even forgetting jQuery and using html document.xxx functions), no way.
While debugging, all my variables are OK, it just does nothing when doing the "appendTo", except once for the keyInput div.
I tried then to remove the #content div and relaunch the whole displayInit() method (heavy operation but, just to see) and same damn problem: only the #keyInput is correctly refreshed.
The only thing I've read that may be interesting, is that dynamically created elements (through script) are not registered in the DOM, so it can't be found.
BUT in that case, none of my display attempts should work, so?
In advance, THANK YOU very much for taking care about my nightmare.
Attached: my html + JS function.my DOM
function displayInsert() {
var firstLang = stripXmlExtension(paths[0]); // same keys on every language, so we grab the 1st one
var lastKeyIndex = mapXml[firstLang].key.length - 1;
var keyToInsert = mapXml[firstLang].key[lastKeyIndex]; // == last insertion
var inputKey = "<input size=35 type=text id=k" + lastKeyIndex + " value=" + stripHTML(keyToInsert.replace(/ /g, " ")) + " readonly />";
// while appending tag to the HTML content page, we add a dblclick listener that will morph the input into a textarea when double dblclicked
$(inputKey).css("margin-bottom", "15px").dblclick(function (e) {
e.preventDefault();
tempEditId = $(this).attr('id');
$(".modal-body").html("<textarea cols='65' rows='10' id='txt" + $(this).attr('id') + "'>" + $(this).val() + "</textarea>");
$("#modalEdit #btn-correct").css("display", "none");
$("#modalEdit").modal({backdrop: "static"});
}).appendTo("#keyInput");
for (var i = 0; i < paths.length; i++) {
var lang = stripXmlExtension(paths[i]);
var lastValueIndex = mapXml[lang].value.length - 1;
var valueToInsert = mapXml[lang].value[lastValueIndex]; // == last insertion
var inputValue = "<input size=35 type=text id=" + lang + "---" + lastValueIndex + " value=" + stripHTML(valueToInsert.replace(/ /g, " ")) + " readonly />";
// while appending tag to the HTML content page, we add a dblclick listener that will morph the input into a textarea when double clicked
$(inputValue).css("margin-bottom", "15px").dblclick(function (e) {
e.preventDefault();
tempEditId = $(this).attr('id');
$(".modal-body").html("<textarea cols='65' rows='10' id='txt" + $(this).attr('id') + "'>" + $(this).val() + "</textarea>");
$("#modalEdit #btn-correct").css("display", "none");
$("#modalEdit").modal({backdrop: "static"});
}).appendTo("#" + lang);
}
}

OMG, I'm ashamed.
My problem came from an input generated in a modal window that took the same id that was duplicated...
I was hoping it would be a little more complicated ^^
Solved!

Related

Dynamically creating an HTML link that passes a list to a JavaScript function

I have an HTML link that calls a JavaScript function that in turn makes a NEW link. This new link calls the same JS function when clicked, making another link etc. The function also creates a new div where the next link is added.
function displayChildren(displayLocation, myList) {
innerHtml = "";
for (item in myList) {
name = myList[item];
newDisplayLocation = displayLocation + "/" + name;
innerHtml += "<a href='#' onclick='displayChildren(\"" + newDisplayLocation + "\", " + myList + ");'>" + name + "</a>";
innerHtml += "<div id='" + newDisplayLocation + "'></div>";
}
document.getElementById(displayLocation).innerHTML = innerHtml;
}
{{myList.0}}<br />
<div id="{{myList.0}}"></div>
However, I want to pass this JS function a list as a parameter. The first HTML link made is not dynamically created and therefore can pass that list easily, but subsequent links will not give the JS function the list. The onclick tag will call the JS function and pass other parameters fine, but lists are turned into a string.
So the list [["apple", []]] will turn into apple,. This makes sense because I am putting this entire <a> tag into a string. But I still need that link to pass a list, or just in some way get this JS function a list. Any ideas how to do this?
Additional Information:
I am using this to create a tree structure that will show all of a node's
children when clicked.
The list is changed each time it is passed to the JS function. It actually passes the list of the node's children.
The page is not refreshing.

PHP echo appears to work but doesnt show up in HTML

I am trying to use a php script to generate HTML in order to save lines and what not. I am using jQuery to call my php and then put the result into a specified div as shown below:
function createSidebarRow(div, cellNum, rowName, rowDesc) {
$("#" + div).load("createIndexSidebarRow.php?cellNum=" + cellNum + "&rowName=" + rowName + "&rowDesc=" + rowDesc);
}
However, when this is executed the HTML is not updated on the page, I can see that the code has worked because the browser network activity confirms it. I am trying to figure out what is causing it to not update.
This is the network activity confirming the echo'd HTML.
Sorry for stating the obvious, but the div you are trying to fill up does exist with that particular id right?
If so, try this:
$("#" + div).load("createIndexSidebarRow.php?cellNum=" + cellNum + "&rowName=" + rowName + "&rowDesc=" + rowDesc, function() {
alert('success');
});
If the id does exist (and it's unique) and you get an alert there should be no reason for it not to work.
It might be so, that the div is not yet created in the DOM. (the div that should received the html).
Are you calling createSidebarRow directly on page load?
If so, put the function call in a document ready:
jQuery(document).ready(function(){
createSidebarRow (... );
});
Turns out jQuery doesn't play ball when you include spaces in the POST URL. I removed the space and used %20 instead and all is well now. Thanks for any advice.

get element by id returns null for elements that were dynamically added using javascript

function createInput(id){
count++;
var name = "name" + count;
var text = "#" + id.id;
var newInput = "<input type='text' id='" + name + "' placeholder='' />";
var myTextArea = document.getElementById(id.id);
myTextArea.innerHTML += newInput;
return false;
}
The above function adds an input type to a textarea in a div in my code. Once the input type is displayed dynamically, i try to get it's element id using getElementById but it returns null. May I know what is going wrong here? It seems that the new input type is added but somehow the input type is null.
Also, when i refresh the page, i realize the newly added input type disappears. Any way to force the new dynamic input type to remain in the page?
A dynamically created content is only temporary on the page. When page is refreshed it is again without it. You should recreate it again on a page onload Event or .ready() (store the information in a cookie or HTML5 storage).
I tried to create working example of your code: http://jsfiddle.net/G2PKF/1/.
<div id="area1" onclick="createInput(this)" ></div>
<br/>
<div id="area2" onclick="createInput(this)"></div>
<input type="button" onclick="alert(document.getElementById('name' + count));alert(document.getElementById('name' + count).outerHTML)" value="Access Last Element" />
When a rectangle is clicked an input is added to it. The button allows to display last element added.
Everything works as expected. I don't see any problem with your function.

jquery selector checkboxes

My page is moderately complicated and I'm fairly sure its the jquery acting weird. So i'll add the relevant content first and if anyone needs more info let me know and I'll provide it.
The premise is that there is a div which holds keyword bubbles. These bubbles have a tooltip (qTip plugin) with relevant info that you can select and deselect. Sometimes keywords have overlapping relevant info so when one is deselected all others need to be deselected at the same time. This list of bubbles is built dynamically via ajax and can continue to be added on to the page live.
The problem is that some of the check boxes don't uncheck when I click on them, but if I click on the same one in another tooltip it works... which also now lets the original one work just fine. I have no idea why some work and others dont. I figure it has to do with the way the live onlick function binding and/or selectors are written.
The following function writes the html content of the tooltip based on a json object, so just assume the content is there. The jquery code at the bottom is the function I have bound to the checkboxes.
function constructSpecializationsHTML(data){
var html = '';
for(i = 0; i < data.specializations.length; i++){
if(data.specializations[i].name != ''){
html += "<span class='is-specialization-line'>";
html += "<input class='is-specialization-checkbox' type='checkbox' name='" + data.specializations[i].name + "' checked='" + isSpecializationChecked(data.specializations[i].name) + "'/>";
html += "<span>" + data.specializations[i].name + "</span>";
html += "</span><br />";
} else {
html += "This keyword is not known in our ontology";
}
}
return html;
}
$(document).on("click", ".is-specialization-checkbox", function(){
var $checkboxs = $(".is-specialization-checkbox[name='" + $(this).attr("name") + "']")
$checkboxs.prop("checked", !$checkboxs.prop("checked"));
});
Firstly, when the click event fires the "checked" property has already been changed, meaning that the states of your checkboxes are different.
Changing
!$checkboxs.prop("checked")
To
$(this).prop("checked")
Solves that.
Secondly when you have only displayed one tooltip your select is only returning one checkbox. If you display all the tooltips before checking or unchecking it returns the correct number. My guess is that qTip isn't adding the html for the tooltip to the DOM until it is displayed.
That's why not all your similarly named checkboxes are unchecking though (At least I think that's it!)
$(document).on("click", ".is-specialization-checkbox", function(){
var $checkboxs = $(".is-specialization-checkbox[name='" + $(this).attr("name") + "']")
$checkboxs.not($(this)).prop("checked", false);
});
changed this to $(this) - that way it is the specific checkbox that was clicked that is getting excluded from the deselection.

Making a scrollable List without drop down lists

I want to make a transition page that stands as a break between the Login page & the main page.
The Page contains nothing but The list of names ... So, I don't want to make it to be a drop down list ... I want the page to be filled with a scrollable list.
I tried making a div with some buttons inside it, but it doesn't look good. So, do you have any ideas on how can I make the page looks better, or whether I should use 2 divs inside each other & modify them using CSS?
This is what I made:
JS:
function GetClassesList(data) {
var classes = (typeof data) == 'string' ? eval('(' + data + ')') : data;
$('#ClasssesList').empty();
for (var i = 0; i < classes.length; i++) {
var text = '<button class="BigDiv" value="' + classes[i].Cls_ID + '" >' + classes[i].Cls_Name + '</button>';
$('#ClasssesList').append(text);
}
$("#ClasssesList").bind('click', 'button.BigDiv',CallLink());
}
HTML:
<div id="ClasssesList" ></div>
Thanks a lot.
It seems like your code works fine... If I understand correctly, you could define the height and width of #ClassesList and set the overflow to scroll in the CSS. Then, you can format the buttons to appear however you wanted when you are formatting the html inside of the for loop.
I don't understand exactly what you are looking for though. Maybe if you could clarify a bit.

Categories

Resources