Jquery/Jquerymobile populate <select> dynamically - ERROR - javascript

I've a database containing the options to add dynamically, after button click, in a <select> tag.
This is what the HTML looks like, its inside a div with data-role="page" (for jQuerymobile)
<div id="endSessionPageContent" data-role="content">
<div data-role='fieldcontain' id="endSessionForm">
</div>
</div>
Basically, I get some values from a sqlite database, and then I'd like to put them inside the "endSessionForm" div. The data should be displayed both with <inputs> and <select> elements.
The function looks like this (no sql interaction here, for simplicity):
function buildPage(divId){
$("#endSessionForm").empty();
var div = "<div><label>aaa</label><input></input></div>";
div += "<div><label>bbb</label><input></input></div>";
div += "<div><select><option>1</option><option>2</option><option>3</option></select></div>";
$('#endSessionForm').append(div);
$("#endSessionForm").trigger('create');
}
Then after some event, I call the buildPage function (see this jsfiddle for a live example http://jsfiddle.net/xdR43/12/). The trigger(create) is used to force the UI reload:
As you can see, the <select> is not properly created. The jsfiddle page throws this error:
Syntax error, unrecognized expression: :nth-child
while, the same code in my app throws this error:
'undefined' is not an object (evaluating 'this.list[0].appendChild')
What do you think is wrong? Thanks for any help, I hope I gave you all the informations you need. If you need more, ask and I'll add em.
Thanks again, best regards
______EDIT________
this is the entire function:
function buildPage(divId){
$(divId).empty();
for(var i = 0; i < results.rows.length; i++){
var area = results.rows.item(i).area;
var campo = results.rows.item(i).campo;
var campoWOspcs = campo.replace(/ /g,"_");
var valori = results.rows.item(i).valori;
var div = "<div><label for='newCompany_"+campoWOspcs+"'>"+campo+":</label>";
if(valori == ""){ //input
div += "<input type='text' name='"+campoWOspcs+"' id='newCompany_"+campoWOspcs+"' placeholder='"+campo+"'></input>";
}else{ //select
div += "<select name='"+campoWOspcs+"' multiple='multiple' id='newCompany_"+campoWOspcs+"'><option>Select "+campo+"</option>";
var split = valori.split(";");
for(var j = 0; j < (split.length -1); j++ ){
div += "<option>"+split[j]+"</option>";
}
div += "</select>";
}
div += "</div>";
$(divId).append(div);//alert(div);
}
$(divId).append(div);
$(divId).trigger('create');
}

Related

Javascript for loop running out of sequence

I have a confusing problem where a line of code in my function is running before a loop which is stated above it. In my HTML I have:
<textarea id="textBox"></textarea>
<button id="submitButton" onclick="parseData()">submit</button>
<div id="put"></div>
And my JS function is:
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
$("#put").html($("#put").html() + "<table>");
for (var i = 0; i < data.length; i++) {
$("#put").html($("#put").html() + "<tr>"+data[i]+"</tr>");
};
$("#put").html($("#put").html() + "</table>");
return;
};
The resulting html in $("#put") is this:
<table></table>
"SiO2 (%)Al2O3 (%)TiO2 (%)CaO2 (%)MgO2 (%) 8.21.25.31.51.8 45.32.52.60.210.5 65.23.48.70.0662.3 20.11.85.42.540.2 18.91.12.34.810.7"
I'm not sure why the final </table> is being placed before the for loop runs, and I'm not sure why the <tr> tags aren't being added within the for loop. Any pointers?
jQuery automatically closes up tags upon insertion. Try this.
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
var put_html = $("#put").html() + "<table>";
data = data.split(tab);
for (var i = 0; i < data.length; i++) {
put_html += "<tr>"+data[i]+"</tr>";
};
put_html += '</table>';
$("#put").html(put_html);
return;
};
However, I notice that you aren't using <td> elements. You might want to look into fixing that too.
Every time you are adding content into the html() property rather than building the entire content and adding it.
Since you are using jQuery you can bind the event using jQuery rather than adding that directly in the HTML
<textarea id="textBox"></textarea>
<button id="submitButton">submit</button>
<div id="put"></div>
$(function(){
$("#submitButton").click(function(){
parseData();
});
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
// Build your html
$("#put").html('htmlstructure');
return;
}
});
Also you can look for something similar like concatenating the string in an array so that you don't create string isntances each time when you append, since strings are immutable.
Good example

Access Dynamically Created Data Tag in Single Page Application

I have a single page application that is dynamically populating a div with list items that will call a function on click. I am trying to populate the data-tag dynamically and then access that within the appended list item.
The backslash in the $(\#documents) is there because this is a kendoUI-template that is being called by my route function.
The build tree function is being called within an Ajax success function once the data has been retrieved from the server. Any insight or help is appreciated!!!
function buildTreeView(tree, jobCode){
var treeHtml = "<div class='row'><div class='col-xs-12 col-sm-8 col-sm-offset-2'><div class='panel-group'><div class='panel panel-default'><div class='panel-heading'><h3 class='text-center'>View or Download Documents</h3></div><div class='panel-body'><ul class='list-group'>";
for(var i =0;i < tree.length;i++){
if(typeof tree[i] === 'object'){
for(var ind = 0;ind < tree[i].length; ind++){
//another element will be populated here
}
}else{
treeHtml += "<li class='list-group-item viewDoc' data-docName='"+tree[i]+"' data-jobCode='"+jobCode+"'>"+tree[i]+"</li>";
}
}
treeHtml += "</ul></div></div></div></div></div>";
$('\#documents').append(treeHtml);
}
$(document).on("click", ".viewDoc", function(){
var docName = $(this).data('docName');
var jobCode = $(this).data('jobCode');
console.log(docName);
console.log(jobCode);
});
You are not able to access these data because the data attribute "docName" and "jobName" was normalized to lowercase.
eg the html then looks like this:
<li class="list-group-item viewDoc" data-docname="something" data-jobcode="something">something</li>
Look here for better answer:
In any case this will work:
$(document).on("click", ".viewDoc", function(){
var docName = $(this).data('docname');
var jobCode = $(this).data('jobcode');
console.log(docName);
console.log(jobCode);
});
UPDATE: added jsfiddle
Change your function so it sets data using .data(key,value). See https://api.jquery.com/data/
function buildTreeView(tree, jobCode){
$('\#documents').append("<div class='row'><div class='col-xs-12 col-sm-8 col-sm-offset-2'><div class='panel-group'><div class='panel panel-default'><div class='panel-heading'><h3 class='text-center'>View or Download Documents</h3></div><div class='panel-body'><ul class='list-group'></ul></div></div></div></div></div>");
for(var i =0;i < tree.length;i++){
if(typeof tree[i] === 'object'){
for(var ind = 0;ind < tree[i].length; ind++){
//another element will be populated here
}
}else{
var li = $('\#documents').find('ul:last()').append("<li class='list-group-item viewDoc'>"+tree[i]+"</li>");
$(li).data("docName",tree[i]);
$(li).data("jobCode",jobCode);
}
}
// ---- EDITED ----//
var li = $('\#documents').find('ul:last()').append("<li class='list-group-item viewDoc' id='docIndex"+i+"'>"+tree[i]+"</li>");
$('\#docIndex'+i).data({"docName":tree[i], "jobCode":jobCode});

Dynamically creating unique link or button for each result of a database query result

Basically, a list of results from a database query is inserted into a ul. I want the user to be able to click the result they are looking for and then have one of two things happen:
A unique link is created (such as a php GET request) using the ID of
the selected result
A JS function is called via the onClick
attribute, and the ID of the clicked result is sent as an argument.
The code below is what I have done so far - minus the functionality that I listed above.
The list as it is in the HTML:
<ul data-role="listview" id="treesUL" data-inset="true" style="visibility: hidden">
<li id="treesLI">
<div class="resultNames">
<span class="donorName">Donor</span>
for
<span class="honoreeName">Honoree</span>
</div>
<div class="resultInfo">
<span class="treeName">common</span>
on:
<span class="donationDate">Date</span>
</div>
<div class="resultDedication">
<span class="dedicationText">Dedication</span>
</div>
</li>
</ul>
The javascript that edits the list, based on the results of the query which is stored in the myTrees array. This function is called via a XMLHttpRequest object.
function showTreeContent()
{
if (requestObj.readyState == 4) //Request completed
{
//Retrieve the JSON encoded array, which is stored at index-key: media
var text = requestObj.responseText;
//alert(text);
var myTrees = jQuery.parseJSON(text).media;
$('#treesUL').text('');
//Alert the number of rows, for testing purposes
alert(myTrees.length + " results.");
//Loop through the JSON array, and add each element to a <li>, which is then added to the <ul>
for(var i = 0; i < myTrees.length; i++)
{
var tree = myTrees[i];
var li =$('#treesLI').clone();
li.removeAttr('id');
li.appendTo('#treesUL');
//li.find('.treeLink').setAttribute("href", "somelink url");
li.find('.donorName').text(tree['donor']);
li.find('.honoreeName').text(tree['honoree']);
li.find('.dedicationText').text("'" + tree['dedication'] + "'");
if (tree['common'] != '')
li.find('.treeName').text(tree['common']);
else
li.find('.treeName').text("Unknown Species");
li.find('.donationDate').text(tree['date']);
li.data('treeID','tree'+i);
}
}
}
I tried surrounding the contents of the li tag with an a tag, and then editing the href of the a tag, but I was unable to get that to work. I'm using jQuery Mobile for this project also. Let me know if you need any more information - any help is greatly appreciated!
First thing that I see strange is that you are calling $('#treesUL').text(''); that deletes the contents of the ul and than in the loop you request $('#treesLI') which was deleted above.
What i would do is create the HTML as a string and append it to the ul.
Example.
var html = '';
for(var i = 0, length = myTrees.length; i < length; ++i)
{
var tree = myTrees[i];
html += '<li class="treesLI" onClick="somefunction('+ tree.id+')">';
html += '<div class="resultNames"><span class="donorName">' + tree.donor + '</span>';
html += 'for <span class="honoreeName">'+ tree.honoree + '</span></div>';
html +='</li>';
$('#treesUL').append(html);
}
As you can see i added an onClick handler that calls a function that receives a parameter.
You can use that onClick function to make a GET request with $.axaj()
If you don't want to use onClick you can do:
$('#treesUL li').click(function(event){
});
Some other observations:
You can access the properties of an object using the . like this tree.dedication.
You should do your for like this for(var i = 0, length = myTrees.length; i < length; ++i)
it is 2 times faster in IE8

Displaying items after selecting category from drop down in same div in javascript

I have a drop down list and after selecting category it should display items of the category in same div.
I have written a function on "onChange" and it works also. When I click on soups it shows the items of soups then when I click on starters it should only show starters, but it shows soups items and below that it displays starters.
I tried using innerHTML and even document.write functions, but using document.write it refreshes the page and displays only items, my drop down and other stuff from the page is vanished.
Please help. Thanks in advance.
Here is the function.
<body>
<div style="margin:left:80px;">
<select id='menu' style='height:40px;width:160px;' onChange="displayItems()">
<option value='items' selected='selected' disabled>Select Items</option>
<script>
var rasvanti_menu=["Soup","Pasta","Pizza","Sandwich","Snacks","Starters","Bread","Rice","Rice/Noodles","Gravies","Beverages","Extras"];
var rasvanti_soup=["Coriander soup","Cream of Veg soup","Cream of tomato soup","Hot and sour soup","Manchow soup","Palak soup","Sweet corn soup","Veg Clear soup"];
var rasvanti_starters=["Baby Corn Chilli","Baby Corn Finger","Finger Chips","Harabhara Kabab","Manchurian Dry","Mushroom Tikka","Pan Crispy","Paneer 65","Paneer Chilly Dry","Paneer Malai Kabab","Paneer Manchurian Dry"];
for(var i=0;i<=rasvanti_menu.length;i++)
{
document.write("<option value='"+i+"'>"+rasvanti_menu[i]+"</option>");
}
var id = document.createElement("table");
function displayItems() {
var selectedMenu = document.getElementById('menu');
var selectedSoup = selectedMenu.options[selectedMenu.selectedIndex].text;
if (selectedSoup == "Soup") {
for (var s = 0; s < rasvanti_soup.length; s++) {
id.innerHTML += "<tr><td>" + rasvanti_soup[s] + "</td></tr>";
document.getElementById("items_tray").appendChild(id);
}
} else if (selectedSoup == "Starters") {
for (var l = 0; l < rasvanti_starters.length; l++) {
id.innerHTML += "<tr><td>" + rasvanti_starters[l] + "</td></tr>";
document.getElementById("items_tray").appendChild(id);
}
}
}
</select>
<table id="items_tray">
</table>
</div>
</body>
The problem with your code appears to be the fact that you are using a variable called 'id' without defining it? If you post your complete code, people will be able to suggest better solutions.
You are getting this as the new data gets appended to the existing data in the items_tray.
So before appending the data in the items_tray, try removing the innerHTML of the items_tray, something like this -
if(selectedSoup=="Soup"){
document.getElementById("items_tray").innerHTML = "";
for(var s=0;s<rasvanti_soup.length;s++){
id.innerHTML+="<tr><td>"+rasvanti_soup[s]+"</td></tr>";
document.getElementById("items_tray").appendChild(id);
}
}
same goes for the second "if".
Hope this will work.

Fill Array with div elements populated dynamically in codebehind. C#, javascript

I have a report populated as a table with a stringbuilder from the codebehind. The first TD of every row is a checkbox, the id of each checkbox is assigned dynamically:
sb.Append("<td><input type='checkbox' id='chkSelectAll_" + i + "' name='chk_" + i + "' onclick='JavaScript: chkAll_click(this);' /> </td>"
The aspx page uses a master page and
<asp:Content><div id='divMain'></div></asp:Content>
format other than a form to populate. The problem I am running in to is that I am having trouble finding all the elements (or any actually) of the div to work with. Here is the javascript I have been given. (Team project at work, I was just assigned 1 task on the project so changing anything is not an option.)
function divBatchBuild_click() {
debugger
var form = document.forms[0];
var visitList = '';
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i].type == 'checkbox') {
//alert(form.elements[i].id.toString());
if (form.elements[i].checked == true &&
form.elements[i].id != 'chkSelectAll') {
var y = form.elements[i].id;
//alert('id=' + y[1].toString());
visitList = visitList + y[i].toString() + '|';
}
}
}
}
Apparently this worked on a previous project, but when used with this report the process never goes inside the if statement. Any help on what is going wrong is appreciated.
I think you want to first get the div, then get the elements in the div with the checkbox tagname. Something like:
var div = document.getElementById('divMain');
var elements = div.getElementsByTagName('checkbox');
for (i = 0; i < elements.length; i++) {

Categories