Generate JQM Popup Dynamically - javascript

I want to display a JQM PopUp based on the contents of my variable.
I have a variable that contains this.
924-1922, 928-3074, 928-8363
Then I perform .split so I can get the three phone numbers.
secNumber = res.rows.item(i).secondary_num.split(", ");
So my variable secNumber now has an array of three numbers: 924-1922,928-3074,928-8363
Now here is my code for displaying it (I am using for loop for this since there are many entries with phone numbers):
html += ' Tel. No.: ' + res.rows.item(i).tel_num + ' </span> <br> <span style="font-size: 15px;color: #778084;" onclick="window.open(\'tel:02'+secNumber+'\', \'_system\');"> ' + secondary +' </span> ';
The onclick on my last <span> is working. However, it only puts the first number on the phone's dialer. What I want to achieve on my onclick is, after show a popup onclick using this code from JQM website
Actions...
<div data-role="popup" id="popupMenu" data-theme="d">
<ul data-role="listview" data-inset="true" style="min-width:210px;" data-theme="d">
<li data-role="divider" data-theme="e">Choose an action</li>
<li>View details</li>
<li>Edit</li>
<li>Disable</li>
<li>Delete</li>
</ul>
</div>
When I click on my <span> the contents of the listview of the popup will be the contents of my array secNumber, then on the onclick of each element in the listview, I will call window.open to access the phone's dialer.
EDIT
This is my code.
article.emergency = function() {
var secNumber;
var telnum;
var html = '';
appDB.transaction(function(tx) {
tx.executeSql("SELECT * FROM emergency", [], function(tx, res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
function openPopup(index) {
//reset its content
$('#popupMenu').find('ul').html('<li data-role="divider" data-theme="e">Choose an action</li>');
//loop on secondary_num items
$.each(res.rows.item(index).secondary_num.split(", "), function(k, v) {
$('#popupMenu').find('ul').append('<li>' + v + '</li>');
});
//refresh listView
$('#popupMenu').find('ul').listview("refresh");
//open popup
$('#popupMenu').popup("open", {"transition":"slideup"});
}
var secondary = (res.rows.item(i).secondary_num != 'null') ? 'Secondary Number: ' + res.rows.item(i).secondary_num : '';
secNumber = res.rows.item(i).secondary_num.split(", ");
console.log(secNumber);
/*secondary = secondary.replace(/-/g,"");
console.log("Secondary number string : "+secondary);*/
console.log(res.rows.item(i).tel_num);
telnum = res.rows.item(i).tel_num.split(" to");
console.log(telnum);
html += ' Tel. No.: ' + res.rows.item(i).tel_num + ' </span> <br> <span style="font-size: 15px;color: #778084;" onclick="window.open(\'tel:02'+secNumber+'\', \'_system\');"> ' + secondary +' </span> ';
//html += ' Tel. No.: ' + res.rows.item(i).tel_num + ' </span> <br> <span style="font-size: 15px;color: #778084;" onclick="window.open(\'tel:02'+secNumber+'\', \'_system\');"> ' + secondary +' </span> ';
}
$('.list-display').html(html);
}
});
}, article.onErr, article.onSuccess);
}
I hope someone can help me. Thanks.

Supposing your item array has multiple elements and you want to use a unique popup container you'll have to generate dynamically its content (refreshing the listView widget).
Your secondary span should look similar to
<span onclick="window.openPopup(' + index + ');"> ' + secondary +' </span>
and your openPopup function
function openPopup(index) {
//reset its content
$('#popupMenu').find('ul').html('<li data-role="divider" data-theme="e">Choose an action</li>');
//loop on secondary_num items
var secNumber = item[index].secondary_num.split(", ");
for (var i = 0; i < secNumber.length; i++) {
$('#popupMenu').find('ul').append('<li>' + secNumber[i] + '</li>');
}
//refresh listView
$('#popupMenu').find('ul').listview("refresh");
//open popup
$('#popupMenu').popup("open", {"transition":"slideup"});
}
Here you can fine a working example with a simplified structure: http://jsfiddle.net/phtzwxb6/5/
Update fixing your code with a possible solution:
// declared outside
function openPopup(index) {
//reset its content
$('#popupMenu').find('ul').html('<li data-role="divider" data-theme="e">Choose an action</li>');
//loop on secondary_num items
var secNumber = item[index].secondary_num.split(", ");
for (var i = 0; i < secNumber.length; i++) {
$('#popupMenu').find('ul').append('<li>' + secNumber[i] + '</li>');
}
//refresh listView
$('#popupMenu').find('ul').listview("refresh");
//open popup
$('#popupMenu').popup("open", {"transition":"slideup"});
}
//your enclosure...
article.emergency = function() {
var secNumber;
var telnum;
var html = '';
appDB.transaction(function(tx) {
tx.executeSql("SELECT * FROM emergency", [], function(tx, res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
var secondary = (res.rows.item(i).secondary_num != 'null') ? 'Secondary Number: ' + res.rows.item(i).secondary_num : '';
secNumber = res.rows.item(i).secondary_num.split(", ");
telnum = res.rows.item(i).tel_num.split(" to");
html += ' Tel. No.: ' + res.rows.item(i).tel_num + ' </span> <br> <span style="font-size: 15px;color: #778084;" onclick="window.openPopup(' + i + ');"> ' + secondary +' </span> ';
}
$('.list-display').html(html);
}
});
}, article.onErr, article.onSuccess);
}

Related

How to design UI for multiple selection in a drop down list?

I'm setting up a UI for my application. I would like to have some idea about your guy's experiences.
I need to have multiple selections from different sources.
Input (Sources): Companies, Department. Multiple companies, departments allowed.
Output: People who belong to selected items
For example, I can select company1, company2, and select department1, department2 from a dropdown list.
I select one by one property( Select company1, company2, then go to another dropdown to select department1,2...)
In the end, I have company1,2,3 checked, department 1,2,3 checked.
Then the result will tell me user1...n belong to the selected list above.
The problem is nothing if I have only a few company and department but if coming to be complicated if I have multiple (more than 6 companies and departments). I can't come up with any good UI design for this problem.
I expected the output of (selected(checked company1,2,3... + department1,2,3)) -> result person1,2,3 belong to checked items.
Try the following code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Select Company: </p>
<select name="companySelector" multiple>
</select>
<p>Select Department: </p>
<select name="departmentSelector" multiple>
</select>
<p>Persons: </p>
<ul id="persons">
</ul>
<script>
var companySelector = document.querySelector("[name='companySelector']");
var departmentSelector = document.querySelector("[name='departmentSelector']");
var persons = document.getElementById("persons");
var temp, temp2 = 0;
var database = {
company_1: {
c1_department1: ["c1d1person1", "c1d1person2", "c1d1person3", "c1d1person4"],
c1_department2: ["c1d2person1", "c1d2person2", "c1d2person3", "c1d2person4"],
c1_department3: ["c1d3person1", "c1d3person2", "c1d3person3", "c1d3person4"]
},
company_2: {
c2_department1: ["c2d1person1", "c2d1person2", "c2d1person3", "c2d1person4"],
c2_department2: ["c2d2person1", "c2d2person2", "c2d2person3", "c2d2person4"],
c2_department3: ["c2d3person1", "c2d3person2", "c2d3person3", "c2d3person4"]
},
company_3: {
c3_department1: ["c3d1person1", "c3d1person2", "c3d1person3", "c3d1person4"],
c3_department2: ["c3d2person1", "c3d2person2", "c3d2person3", "c3d2person4"],
c3_department3: ["c3d3person1", "c3d3person2", "c3d3person3", "c3d3person4"]
},
company_4: {
c4_department1: ["c4d1person1", "c4d1person2", "c4d1person3", "c4d1person4"],
c4_department2: ["c4d2person1", "c4d2person2", "c4d2person3", "c4d2person4"],
c4_department3: ["c4d3person1", "c4d3person2", "c4d3person3", "c4d3person4"]
},
company_5: {
c5_department1: ["c5d1person1", "c5d1person2", "c5d1person3", "c5d1person4"],
c5_department2: ["c5d2person1", "c5d2person2", "c5d2person3", "c5d2person4"],
c5_department3: ["c5d3person1", "c5d3person2", "c5d3person3", "c5d3person4"]
}
}
for (temp in database) {
companySelector.innerHTML += '<option value="' + temp + '">' + temp.replace(/_/g, " ") + '</option>';
}
companySelector.onchange = function() {
departmentSelector.innerHTML = "";
var selectedCompnies = document.querySelectorAll("[name='companySelector'] option:checked");
for (var i = 0; i < selectedCompnies.length; i++) {
for (temp2 in database[selectedCompnies[i].value]) {
departmentSelector.innerHTML += '<option value="' + temp2 + '" data-company="' + selectedCompnies[i].value + '">' + temp2.replace(/_/g, " ") + '</option>'
}
}
}
departmentSelector.onchange = function() {
persons.innerHTML = "";
var selectedDepartments = document.querySelectorAll("[name='departmentSelector'] option:checked");
for (var i = 0; i < selectedDepartments.length; i++) {
var temp3 = selectedDepartments[i].dataset.company;
var prsonsArray = database[temp3][selectedDepartments[i].value];
for (var x = 0; x < prsonsArray.length; x++) {
persons.innerHTML += "<li>" + prsonsArray[x] + "</li>";
}
}
}
</script>
</body>
</html>
DEMO

Javascript: Different background color for different div's

I have some troubles with javascript app to manage meetings. I have three levels of importance: 'Important', 'Medium', 'No important' and I want change background-color for them. 'Important' - red color, 'Medium' - yellow and 'No important'-green. I try to hold in content variable string from html and then compare this value with if,else if statement, but it still doesn't work. Do you have some advices?
main.js
function fetchMeetings(){
var meetings = JSON.parse(localStorage.getItem('meetings'));
var meetingsResults = document.getElementById('meetingsResults');
// Build output
meetingsResults.innerHTML = '';
for(var i = 0; i < meetings.length; i++){
var date = meetings[i].date;
var person = meetings[i].person;
var purpose = meetings[i].purpose;
var warning = meetings[i].warning;
meetingsResults.innerHTML += '<div class="mettingDiv">'+
'<h3>'+date+'</h3>'+
'<h3>'+person+'</h3>' +
'<h3>'+purpose+'</h3>'+
'<h3 class="importance">'+warning+'</h3>'+
' <a onclick="deleteMeeting(\''+purpose+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</div>';
}
var content= document.getElementsByClassName("importance").innerHTML;
if(content == 'Important'){
$('.mettingDiv').css('background-color', '#c00100');
}
else if(content == 'Medium'){
$('.mettingDiv').css('background-color', '#fbff30');
}
else if(content == 'No important'){
$('.mettingDiv').css('background-color', '#85ff63');
}
}
github
live app
Ok, I tried to add additional class name to div element, but class name is still the same, code:
meetingsResults.innerHTML += '<div id="div1" class="mettingDiv">'+
'<h3>'+date+'</h3>'+
'<h3>'+person+'</h3>' +
'<h3>'+purpose+'</h3>'+
'<h3 class="importance">'+warning+'</h3>'+
' <a onclick="deleteMeeting(\''+purpose+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</div>';
}
var content= document.getElementsByClassName("importance").innerHTML;
var d = document.getElementById("div1");
if(content == 'Important'){
d.className += " important";
}
Try this
meetingsResults.innerHTML += '<div class="mettingDiv ' + warning + '">'+ ...
this will result in <div class="mettingDiv Important"..., <div class="mettingDiv No important" ... and then add CSS
.Important { background-color: #c00100; }
.Medium { background-color: #fbff30; }
.No.important { background-color: #85ff63; }

How to add dynamically created Checkboxes to Bootstrap row

I have added a bootstrap row. Now inside that I want to add checkbox such that checkboxes should display side by side not as line by line as it is now. Here is the HTML.
<div class="row" id="ReportRow">
<div class="col-md-12">
</div>
</div>
and here is the jquery
var Reports = "User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += '<label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label><br\>';
}
$('#ReportRow').html(reportscheckBoxhtml);
Plesae help me to align it properly. Thanks.
Fiddle
Just remove the <br/> from ur code
var Reports = "User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += '<label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label> ';
}
$('#ReportRow > .col-md-12').html(reportscheckBoxhtml);

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

How to make list in jQuery mobile nested list?

Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}

Categories

Resources