I'm using the Multi Page Template (all pages and javascriot in one html file). I just restructure my jQuery mobile app:
Before: all JavaSripts in the html file, example:
<div data-role="page>.....<script></script> </div>
Now: all JavaScripts are outsourced in a own file. But now comes the problem:
I'm searching after addresses at one page. Each result is stored in a history (localStorage). So the user can use the search or click on old history search results.
Since I outsourced the script for this page, the history doesn't work. I will show you the working code and the not working code:
Working code - pre outsourced:
This code works. JavaScript is in page div:
<div data-role="page" id="searchPage" class="bg-light">
<div data-role="content">
<div id="content-search">
<p><input type="text" name="address" id="address" class="stored" value="" /></p>
<p><input type="submit" id="submitAddress" value="Search" data-theme="a" data-corners="false" /></p>
</div>
<div id="searchHistory">
<div class="ui-corner-all custom-corners">
<div class="ui-bar ui-bar-c">
<h3>History:</h3>
</div>
<div class="ui-body ui-body-c">
<div id="lastResults" class="ui-body ui-body-c ui-corner-all"></div>
</div>
</div>
</div>
</div>
<script>
......
// check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null) {
var historyTemp = localStorage.getItem("history");
var oldhistoryarray = historyTemp.split("|");
oldhistoryarray.reverse();
$("#lastResults").empty();
jQuery.each( oldhistoryarray, function( i, val ) {
$("#lastResults").append(
"<ul data-role=\"listview\" data-inset=\"true\" >" +
// store history in localStorage
"<li><a href=\"#mapPage\" onClick=\"getHistory("+i+");\" >"+oldhistoryarray[i]+"</a></li>" +
"</ul>"
);
// max. history
if (i==3) {
return false;
}
});
} else {
// hide search history
console.log("no history");
$("#searchHistory").hide();
}
function getHistory(i){
localStorage.setItem('address', oldhistoryarray[i]);
}
</script>
</div>
Not Working code - JS outsourced in own file:
JavaScript is now in own file (function.js):
index.html:
detail code see above
<div data-role="page" id="searchPage" class="bg-light">
<div data-role="content">
</div>
<script></script>
</div>
function.js:
// check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null) {
var historyTemp = localStorage.getItem("history");
var oldhistoryarray = historyTemp.split("|");
oldhistoryarray.reverse();
$("#lastResults").empty();
jQuery.each( oldhistoryarray, function( i, val ) {
$("#lastResults").append(
"<ul data-role=\"listview\" data-inset=\"true\" >" +
// store history in localStorage
"<li><a href=\"#mapPage\" onClick=\"getHistory("+i+");\" >"+oldhistoryarray[i]+"</a></li>" +
"</ul>"
);
// max. history
if (i==3) {
return false;
}
});
} else {
// hide search history
console.log("no history");
$("#searchHistory").hide();
}
function getHistory(i){
localStorage.setItem('address', oldhistoryarray[i]);
}
if you are not executing your script after the page has finished loading, there's a chance queries like $("#searchHistory") might be returning empty.
Make sure you execute your script in a callback that is called at the onload event.
so I'd suggest something like this (please also check that you initialize your "history")
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script src="function.js"></script>
<script>
$(document).on( "pagecreate", function( event ) {
console.log("page created")
$('#submitAddress').on('click',function(){
makeHistory();
})
});
</script>
</head>
<body>
<div data-role="page" id="searchPage" class="bg-light">
<div data-role="content">
<div id="content-search">
<p><input type="text" name="address" id="address" class="stored" value="" /></p>
<p><input type="submit" id="submitAddress" value="Search" data-theme="a" data-corners="false" /></p>
</div>
<div id="searchHistory">
<div class="ui-corner-all custom-corners">
<div class="ui-bar ui-bar-c">
<h3>History:</h3>
</div>
<div class="ui-body ui-body-c">
<div id="lastResults" class="ui-body ui-body-c ui-corner-all"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
function.js then would be
// check and show previous results in **lastResults** div
function makeHistory()
{
if (localStorage.getItem("history") != null) {
var historyTemp = localStorage.getItem("history");
var oldhistoryarray = historyTemp.split("|");
oldhistoryarray.reverse();
$("#lastResults").empty();
jQuery.each( oldhistoryarray, function( i, val ) {
$("#lastResults").append(
"<ul data-role=\"listview\" data-inset=\"true\" >" +
// store history in localStorage
"<li><a href=\"#mapPage\" onClick=\"getHistory("+i+");\" >"+oldhistoryarray[i]+"</a></li>" +
"</ul>"
);
// max. history
if (i==3) {
return false;
}
});
} else {
// hide search history
console.log("no history");
//and you probably need to initialize your history here, something like
localStorage.setItem("history", "lalala");
$("#searchHistory").hide();
}
}
function getHistory(i){
localStorage.setItem('address', oldhistoryarray[i]);
}
Now the pagecreate event also binds a behaviour to your search button to actually update the history each time it is clicked.
Related
The following code allows me to append new content to the div "users". However, I want to be able remove the appended content if the user clicks button.
The current code removes only the "remove" button when its clicked. However, I need to remove the entire appended code with the class "removeuser", in the beginning of the appended code.
Any help will be appreciated!
<div id="users"></div>
<script>
function adduser() {
count += 1;
$('#users').append('<div id="field'+ count +'" class="removeuser[]"><div
id="left"><div id="fieldname">user #'+ count +' Name:</div><div
id="field"><input id="user_name'+ count +'" name="user_name[]"' + '"
type="text" /></input></div><div id="clear"></div></div><div id="leftleft">
<div id="fieldname">user #'+ count +' Age</div><div id="field"><input
type="number" id="user_age'+ count +'" name="user_age[]"
style="width:50px;" min="0"></input></div><div id="clear"></div><br></div>
<div id="leftleft"><a href="javascript: void(0)" onclick="adduser(); return
false;"><div id="field" class="add"><div
style="position:relative;left:-4px;top:1px;">add another user +</div></div>
</a><br></div> <div id="leftleft"><a href="javascript: void(0)"
onclick="$(this).remove();" ><div id="deluser[]" class="add"><div
style="position:relative;left:-4px;top:1px;">-</div></div></a><br></div>
<div id="clear"></div></div>');
var no = document.getElementById("deluser");
no.onclick = function(){
$('#users .removeuser').$(this).remove();
};
</script>
From what I can tell this is might be the solution you're looking for (note not supported in all browser. See below for transpiled version)...
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count))
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = `
<div>
<a href="javascript: void(0)" onclick="deluser(event); return false;">
<div class="add delete-user" data>
<div style="position:relative;left:-4px;top:1px;">-</div>
</div>
</a>
<br>
</div>
`;
return `
<div class="user-container">
<div id="left">
<div class="fieldname">
user #${count} Name:
</div>
<div class="field">
<input id="user_name${count}" name="user_name[]" type="text" /></input>
</div>
<div id="clear"></div>
</div>
<div>
<div class="fieldname">
user #${count} Age
</div>
<div class="field">
<input type="number" id="user_age${count}" name="user_age[]" style="width:50px;" min="0"></input>
</div>
<div id="clear"></div><br>
</div>
<div>
<a href="javascript: void(0)" onclick="adduser(); return false;">
<div class="field" class="add">
<div style="position:relative;left:-4px;top:1px;">add another user +</div>
</div>
</a>
<br>
</div>
${count > 0 ? deleteButton : ""}
<div class="clear">
</div>
</div>
`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>
There area quite a few things wrong with your initial attempt though and I don't mean to be rude, but you should probably do more work learning the basics of HTML, JS and in this case jQuery. Treehouse is where I started out many years ago and think it is a great introduction to web development (Treehouse - front-end web development). That being said here are the most glaring issues...
Unique ids
id attributes must be unique per HTML document. As in, having id="leftleft" and then on another element in same document having id="leftleft" is invalid.
Missing closing bracket of function block }
HTML template strings
Honestly I don't know how you're able to read that HTML template string, but this is one of the issues front-end frameworks like React and Angular are meant to solve. Writing HTML templates like this will definitely introduce bugs and also drive you insane.
Instead or rewriting your whole program in React or Angular I would suggest using Template Literals and either using Webpack + babel to transpile your code to achieve browser support or for now just visit Babel repl and manually drop in your JS (with template literals) then replace with output code.
This is how the code would look after being transpiled through Babel, which would be supported in all browsers..
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count));
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = "\n <div>\n \n <div class=\"add delete-user\" data>\n <div style=\"position:relative;left:-4px;top:1px;\">-</div>\n </div>\n \n <br>\n </div>\n ";
return "\n <div class=\"user-container\">\n <div id=\"left\">\n <div class=\"fieldname\">\n user #".concat(count, " Name:\n </div>\n <div class=\"field\">\n <input id=\"user_name").concat(count, "\" name=\"user_name[]\" type=\"text\" /></input>\n </div>\n <div id=\"clear\"></div>\n </div>\n <div>\n <div class=\"fieldname\">\n user #").concat(count, " Age\n </div>\n <div class=\"field\">\n <input type=\"number\" id=\"user_age").concat(count, "\" name=\"user_age[]\" style=\"width:50px;\" min=\"0\"></input>\n </div>\n <div id=\"clear\"></div><br>\n </div>\n <div>\n \n <div class=\"field\" class=\"add\">\n <div style=\"position:relative;left:-4px;top:1px;\">add another user +</div>\n </div> \n \n <br>\n </div> \n ").concat(count > 0 ? deleteButton : "", "\n <div class=\"clear\">\n </div>\n </div>\n ");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>
use something like this
$( '#users' ).empty();
You need to use following code
var no = $(".deluser"); // add class 'deluser' to each div
no.onclick = function(){
$('#users').empty();
};
I tried to illustrate your approach in another way, I hope it will help you.
var count = 0;
function addUser(i) {
var userBloc = '<li class="list-group-item" id="user'+i+'"> I am the user'+ i +
' <br><button class="btn btn-danger remove" data-count="'+i+'">Remove me</button><hr></li>';
return userBloc;
}
$('#add').click(function(){
$('#blocs').append(addUser(count));
$('#user'+count).fadeIn(activeRemove); //important to active remove event
count++;
});
function activeRemove(){
$.each($('button.remove'), function(i,item){
$(item).click(function(){
$('#user'+$(item).attr('data-count')).remove();
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blocs" class="list-group"></div>
<button id="add">Add a another user</button>
I am not able select the checkboxes second time on the basis of its Id's in textbox, Id's passes from textbox is separated by comma (,) like (1,2,3,..).
First time when page gets load everything works fine for me but then when I uncheck the checkboxes and again tried to check those on anchor tag click it doesn't work. Appreciate any help.
$(document).on("click", "a[id$='btnShowRates']", function (e) {
if ($('input[type=text][id$=rate]').val() != "") {
var arrate = $('input[type=text][id$=rate]').val().split(',');
var targetcheckboxes = $.map(arrate, function (i) { return document.getElementById(i) });
$(targetcheckboxes).prop('checked', true);
}
else { $('[id$=listRates] input[type=checkbox]').prop('checked', false); }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-role="controlgroup">
<a id="btnShowRates" href="#pgRates" data-transition="slideup" data-role="button" runat="server">
<span class="left ad_option_text small_text"><%=MBBE_Revamped.Labels.GetLabel(langID, hotel, "RateCorpCode") %></span>
<input id="rate" type="text" />
</a>
<section id="pgRates" data-role="page" data-theme="a">
<bhead:custHead id="CustHead1" runat="server" />
<header data-role="header" class="mbe_detail_header">
<p class="nospace">Hotel Rates</p>
</header>
<div data-role="content">
<fieldset data-role="controlgroup" id="listRates" data-icon="false" runat="server">
<--! Here comes dynamic checkboxes -->
<div style='position:relative;'>
<input type='checkbox' id='1' data-display-name='Rack/General' />
<label for='1'>Rack/General</label>
<img id='img_1' class='checkboxFixIconLeft' />
</div>
<div style='position:relative;'>
<input type='checkbox' id='4' data-display-name='Government' />
<label for='4'>Government</label>
<img id='img_4' class='checkboxFixIconLeft' />
</div>
<div style='position:relative;'>
<input type='checkbox' id='6' data-display-name='Package' />
<label for='6'>Package</label>
<img id='img_6' class='checkboxFixIconLeft' />
</div>
<!-- End -->
</fieldset>
<div class="btn_container">
<a data-role="button" data-theme="b" data-rel="back">Confirm</a>
</div>
</div>
</section>
</div>
I have found the Issue,It is happening because I do not write a refresh after check the checkbox it is mandatory to add refresh to check and uncheck the Mobile Checkbox through Jquery or Javascript. check below is the refresh function details
refresh()Returns: jQuery (plugin only)
update the checkboxradio.
If you manipulate a checkboxradio via JavaScript, you must call the refresh method on it to update the visual styling.
So My modified jquery function is -
$(document).on("click", "a[id$='btnShowRates']", function (e) {
if ($('input[type=text][id$=rate]').val() != "") {
var arrate = $('input[type=text][id$=rate]').val().split(',');
var targetcheckboxes = $.map(arrate, function (i) { return document.getElementById(i) });
$(targetcheckboxes).prop('checked', true).checkboxradio('refresh');
for (var i in targetcheckboxes) {
setCustomChecked(true, $(document).find('input[type="checkbox"]:checked'));
}
}
else { $('[id$=listRates] input[type=checkbox]').prop('checked', false).checkboxradio('refresh'); }
});
For some reason, i have this two functions in my javascript, and both seems to work.
The first one, is when user click on one of two divs, it will show the other div, depending on wich was clicked.
The second one, is when the user is on the second div, and clicks on back.
All this is working, but when the user return to the first div, and i click on one of two divs, this isnt going to the second div.
It's closing both divs.
First Div with two options:
<div class="firstQuestion">
<div class="male" onclick="secondQuestion(this);"></div>
<div class="female" onclick="secondQuestion(this);"></div>
</div>
Second div, with back button:
<div class="secondQuestion">
<form class="formAconselhamento" id="male">
<input type="button" id="save_value_male" class="back" name="save_value" onclick="comeBack(this); return false;"/>
<input type="button" id="save_value_male" class="next" name="save_value" />
</form>
</div>
Javascript functions:
function secondQuestion(divID)
{
var clicado = $("#"+$(divID).attr('class'));
$(".firstQuestion").hide();
$("#"+$(divID).attr('class')).show();
}
function comeBack(divID)
{
var backButton = $(divID).attr('id');
if ( backButton == 'save_value_female' || backButton == 'save_value_male' )
{
$(".secondQuestion").hide();
$(".firstQuestion").show();
}
}
How can i resolve my issue?
In comeBack function you hide <div class="secondQuestion"> instead of <form class="formAconselhamento" id="male">
Try something like:
function comeBack(divID)
{
var backButton = $(divID).attr('id');
if ( backButton == 'save_value_female' || backButton == 'save_value_male' )
{
$(divID).closest("form").hide();
$(".firstQuestion").show();
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.maincat{background: #eef;}.subcat{background: #abc;}
</style>
</head>
<body>
<div class="maincat">
<div class="type" rel='one'>first</div>
<div class="type" rel='two'>second</div>
<div class="type" rel='three'>third</div>
</div>
<div class="subcat" style="display: none">
back
<div id="one">
first content
</div>
<div id="two">
second content
</div>
<div id="three">
third content
</div>
</div>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(".type").click(function(){
$(".maincat").hide();
$("#" + $(this).attr('rel')).show().siblings().hide();
$('.subcat').show();$('.back').show();
});
$(".back").click(function(){
$('.subcat').children().hide();$(".maincat").show();
});
</script>
</body>
</html>
Hello I have code like this:
<body>
<div id="page">
<div id="header">declaration</div>
<div id="content">
<div id="option">
<span class='names'>
show chapter 1.1.1 content
</span>1.1.1 Chapter name<br />
<span class='names'>
<a href='#'>show chapter 1.1.1.1 content</a>
</span>1.1.1.1 Chapter name<br />
</div>
</div>
<div id="footer">declaration</div>
</div>
</body>
When user click on the show link, webpage open a HTML file and to print a content of the choosed chapter from file. (it is saved in content.html file, and content has id with name of chapter)
File example:
<div id="s1"><h1>1 Chapter</h1>
<div id="s1.1"><h1>1.1 Chapter</h1>
<div id="content1.1">
data
</div>
<div id="s1.1.1"><h1>1.1.1 Chapter</h1>
<div id="content1.1.1">
data
</div>
</div>
</div>
</div>
</div>
When user click on the "show chapter 1.1.1 content" webpage generate this code:
<body>
<div id="page">
<div id="header">declaration</div>
<div id="content">
<div id="s1.1.1"><h1>1.1.1 Chapter</h1>
<div id="content1.1.1">
data
</div>
</div>
</div>
</div>
<div id="footer">declaration</div>
</body>
I was trying this code but it is not working and I do not know how to open html file and parsed only some with with specific id
<script type="text/jscript" language="javascript">
var ul = document.querySelector('#option');
ul.onclick = function (e) {
var evt = e || window.event;
var target = evt.target || evt.srcElement;
var p = document.querySelector('#content');
p.innerHTML = 'Clicked on ' + target.innerHTML;
return false;
};
</script>
I'm not sure exactly what you're trying to do, but the code below makes things look a little cleaner.
<script type="text/jscript" language="javascript">
setTimeout(function () {
var spanNames = document.querySelectorAll('.names'),
content = document.querySelector('#content');
for (var i = 0; i < spanNames.length; i++) {
spanNames[i].onclick = function () {
content.innerHTML = 'Clicked on ' + this.querySelector('a').innerHTML;
return false;
};
};
}, 1000);
</script>
If you're trying to retrieve a html file on a remote server and add its content to a DOM element then you're missing a lot of code, as in the AJAX call.
I have written this code to retrieve values from DB and to put it in listitem its working fine here is my html code: I have already added all plugins.
<html>
<head>
$('#showcollapsed li').live('click',function(event)
{ var txt = $(this).text();
window.localStorage.setItem("clickedValueofList",txt);
$.mobile.changePage('#viewInformation',null,true,true);
getDataofSelectedListItem();
});
Here is my code but its not working fine.
$('#list1').on('click','li',function()
{
$(this).hide();
$('#list1').siblings('#editTextBox').show().val($(this).text()).focus();
});
$('#editTextBox').focusout(function()
{
//$('#list1').listview('refresh');
$(this).hide();
$(this).siblings('#list1').show().text($(this).val());
});
</head>
<body>
<div data-role="page" id="viewUser" data-theme="d">
<div data-role="header" data-theme="e" class="ui-bar ui-bar-e">
BACK
<h3>STUDENT INFO</h3>
</div>
<div data-role="content">
SHOW
<div data-role="collapsible-set" id="showinfodiv" data-theme="b" data-content-theme="d">
<div data-role="collapsible" id="showcollapsed" data-collapsed-icon ="plus" data-iconpos="left">
<h3>user names</h3>
<ul id="list" content-editable="true" data-role="listview" data-filter="true" data-filter-placeholder="Search Student Name..." data-filter-theme="e"></ul>
<li content-editable="true">fdfdfd</li>
</div>
</div>
</div>
</div>
<div data-role="page" id="viewInformation" data-theme="d" data-add-back-btn="true" data-back-btn-text = "back">
<div data-role="header" id="headerid" class="ui-bar ui-bar-b">
<h3></h3>
</div>
<div data-role="content" id="contentid">
<ul id="list1" data-role="listview" data-theme="e"></ul>
<input type="text" id="editTextBox" style="display:none"/>
SAVE
</div>
</div>
</body>
</html>
Now my next task is to edit dynamic listitem means when user click on 1st list item so that list item should be replaced by TEXTBOX and rest of the unclicked listitem will remain same when user completes his editing now the textbox should be hide and recent edit text should appear in listitem similar is the case for rest of the listitem but user can only edit one list item at a time .getting difficulty to achieve this goal.
.js code:
//gettind data from DB and putting it in listview dynamically its working fine
function getDataofSelectedListItem()
{
alert("getDataofSelectedListI");
clickedListItem = window.localStorage.getItem("clickedValueofList");
console.log("clicked list item"+clickedListItem);
//db = window.openDatabase("loginintro", "1.0", "loginintro", 1000000);
var sqlQuery = 'SELECT * FROM loginTable WHERE username=\''+window.localStorage.getItem("clickedValueofList").trim()+'\';';
console.log("selected list query:"+sqlQuery);
db.transaction(function(tx)
{
tx.executeSql(sqlQuery,[],successCBofListItem,errorCBofListItem);
},errorCB,successCB);
}
function successCBofListItem(tx,results)
{ alert("erer");
if(results != null && results.rows != null && results.rows.length > 0)
{ alert("fdfdf");
$('#list1').append('<li> UserName: '+results.rows.item(0).username+'</li>');
$('#list1').append('<li> Password:' +results.rows.item(0).password+'</li>');
$('#list1').append('<li> Emailid:' +results.rows.item(0).emailid+'</li>');
console.log("username:" + results.rows.item(0).username);
console.log("emailid:" + results.rows.item(0).emailid);
console.log("password:" + results.rows.item(0).password);
}
$('#list1').listview('refresh');
}
function errorCBofListItem()
{
alert("errorCBofListItem");
}
here is my code but its not working fine.
$('#list1').on('click','li',function()
{
$(this).hide();
$('#list1').siblings('#editTextBox').show().val($(this).text()).focus();
});
$('#editTextBox').focusout(function()
{ $(this).hide();
$(this).siblings('#list1').show().text($(this).val());
});