using jQuery mobile css in javascript - javascript

I am retrieving contacts of the phone using phone gap and want to display the names in listview by using jquery mobile. But the css is not being applied while executing this code
This is the code
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="jquery.mobile-1.0.1.min.css" />
<script src="cordova-1.5.0.js" type="text/javascript"></script>
<script src="jquery.js" type="text/javascript"></script>
<script src="contact.js" type="text/javascript"></script>
<script src="jquery.mobile-1.0.1.min.js" type="text/javascript"></script>
<script >
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var contactList = new ContactFindOptions();
contactList.filter="";
contactList.multiple=true;
var fields = ["*"]; //"*" will return all contact fields
navigator.contacts.find(fields, getContactFields, onError, contactList );
}
function getContactFields(contacts) {
//displaying contacts in list view
for (var i=0; i<contacts.length; i++)
{
document.getElementById("temp").innerHTML+='<ul id="get" data-role="listview"><li>'+contacts[i].displayName+'</li></ul>'
}
$('get').listview();
}
function onError(contactError) {
alert('onError!');
}
</script>
This is the function I am using for displaying contact which is not applying the css
//displaying contacts in list view
for (var i=0; i<contacts.length; i++)
{
document.getElementById("temp").innerHTML+='<ul id="get" data-role="listview"><li>'+contacts[i].displayName+'</li></ul>'
}
$('get').listview();
Html body code where the contacts name to be displayed
<div data-role="content" id="temp"></div>
Its displaying like in the following image. The css get applied to the first name only

First you have few errors in your code.
Your way of adding list elements is incorrect. You are adding listview for every element contact element. So first create ul element and then through loop add li elements into it. Also if you are using JQM use it with proper jQuery sintax.
Instead:
document.getElementById("temp").innerHTML+='<ul id="get" data-role="listview"><li>'+contacts[i].displayName+'</li></ul>'
Use:
$('#temp').append(<ul id="get" data-role="listview"></ul>);
$('#temp ul#get').append('<li><a href="#contact">'+contacts[i].displayName+'</a</li>');
This is still not enough.
When listview is populated you must refresh its css like this:
$('ul#get').listview('refresh');
You can find more info about this in the JQM documentation.
This statement is not going to do anything:
$('get').listview();
You need to address it to the real ul element, and because get is its id it should look like this:
$('#get').listview();

Related

Toggle hide/show not working on childs div

I have a script that gets data from a Google Sheet and displays it as a webpage - using JS and Tabletop.js.
There are multiple entries in the Sheet thus multiple entries in the webpage. To organise the Data I have a hide/show button. When the button is clicked on the first entry it works. However when the any of the other buttons are clicked it hides or shows the first entries data, not its own!
How do I hide/show each individual entries data? Below is the code I am working with!
I am new to JavaScript - Thanks in advance!
P.S - I struggled writing the Title to the questions!
<link href="../common/cats-copy.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<style>
#add-info {
display: none
}
</style>
<body>
<div class="container">
<h1>Resturants</h1>
<div id="content"></div>
<script id="cat-template" type="text/x-handlebars-template">
<div class="entry">
<h5>{{establishment_name}}</h5>
<h6>Area: {{area}}</h6>
<h6>Cuisine: {{cuisine}}</h6>
<button id="btn" class="button-primary" onclick="myFunction()">Hide</button>
<div id="add-info">
<h6>Address: {{address}}</h6>
<h6>Google Maps: {{google_maps_location}}</h6>
<h6>Opening Times: {{opening_times}}</h6>
<h6>Rating: {{rating}}</h6>
<h6>Added By: {{added_by}}</h6>
<h6>Date Added: {{date_added}}</h6>
</div>
</div>
</script>
</div>
<!-- Don't need jQuery for Tabletop, but using it for this example -->
<script type="text/javascript" src="handlebars.js"></script>
<script type="text/javascript" src="../../src/tabletop.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var public_spreadsheet_url = 'https://docs.google.com/spreadsheets/d/1h5zYzEcBIA5zUDc9j4BTs8AcJj-21-ykzq6238CnkWc/edit?usp=sharing';
$(document).ready( function() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
parseNumbers: true } );
});
function showInfo(data, tabletop) {
var source = $("#cat-template").html();
var template = Handlebars.compile(source);
$.each( tabletop.sheets("food").all(), function(i, food) {
var html = template(food);
$("#content").append(html);
});
}
</script>
<script>
function myFunction() {
var x = document.getElementById("add-info");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
Are all the entries on your page filled from the given template, meaning they are divs with the class entry? If so, I think your issue is the following: Your entry div has a child div with the id="add-info". And when you click the button, your handler function (myFunction()) tries to get a reference to that div via document.getElementById("add-info"); Now, if you have multiple such entries on a page, you will have multiple divs with id="add-info". But the id attribute of an element must be unique in your whole document. See the description of id or that of getElementById().
So the root cause of your problem is that the same id is used multiple times in the document when it shouldn't be. You get the behavior you're seeing because getElementById() just happens to be returning a reference to the first element it finds on the page, regardless of which button you click. But I believe you're in undefined behavior territory at that point.
One way to solve the problem is to somehow give myFunction() information about which button was clicked, while making each div you'd like to manipulate unique so they can be found easier. For instance, you can use the order of the restaurant on your page as its "index", and use that as the id of the div you'd like to hide/show. And you can also pass this index as an argument when you call your click handler:
...
<button id="btn" class="button-primary" onclick="myFunction('{{index}}')">Hide</button>
<div id="{{index}}">
<!-- The rest of the code here... -->
...
... add the index into your template context, so Handlebars can fill in the {{index}} placeholder:
...
$.each( tabletop.sheets("food").all(), function(i, food) {
food.index = i // Give your context its 'index'
var html = template(food);
$("#content").append(html);
});
...
... and then alter your function slightly to use the given argument instead of always looking for the div with id="add-info":
function myFunction(indexToToggle) {
var x = document.getElementById(indexToToggle);
// rest of the code is same
With this approach, I expect your DOM to end up with divs that have ids that are just numbers ("3", "4", etc.) and your click handler should get called with those as arguments as well.
Also note that your <button> element has id="btn". If you repeat that template on your page, you will have multiple <button>s with the same id. If you start trying to get references to your buttons via id you will have similar issues with them too since the ids won't be unique.

How do I count the number of elements in a sortable div?

I have multiple divs in an HTML document with smaller divs within them that can be sorted among each other. When the document is loaded, a random amount of those smaller divs are appended to #boxtop.
Here's my HTML:
<html>
<body>
<head>
<title></title>
<script link src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="jquery-ui.min.css">
<link rel = "stylesheet" type" type="text/css" href = "style.css">
<script src="jquery-ui.min.js"></script>
<div id = "boxtop" class = "dragInto"></div>
<button type="button" id="button">My Children!!!</button>
<div id = "eqbox"></div>
<div id = "box1" class = "ansBox"></div>
<div id = "box2" class = "ansBox"></div>
<div id = "box3" class = "ansBox"></div>
</head>
</body>
</html>
Here's my relevent jQuery
$(document).ready(function()
{
$("#boxtop").sortable
({
connectWith: ".ansBox"
});
$(".ansBox").sortable
({
connectWith: ".ansBox"
});
});
$(document).ready(function()
{
$("dragInto").droppable
({
accept: ".box"
});
});
var numChild = $("#boxtop").length;
$(document).ready(function()
{
$("#button").click(function()
{
console.log(numChild);
});
});
My question is: How can I get the number of elements in a sorted div. I currently try and print that value to the console using numChild but that prints "1". And if I were to drag a bunch of elements from #boxtop to .box1, how could I get the number of elements inside .box1?
The .length property tells you how many elements belong to the jQuery object you call it on. So given that $("#boxtop") matches one element, $("#boxtop").length will be 1.
To find out how many elements are inside #boxtop you have to select all of its descendants and then check the .length:
// All descendants:
$("#boxtop").find("*").length // or:
$("#boxtop *").length
// Or count immediate children only:
$("#boxtop").children().length
In your case I think checking immediate children is probably what you want. But don't set a global variable like:
var numChild = $("#boxtop").children().length;
...because that will set numChild to the length when the page first opens, before the user has started interacting with it. You need to check $("#boxtop").children().length or $(".box1").children().length at the point where the value is needed.
As an aside, you don't need three separate $(document).ready(...) handlers: combine all of your code into a single ready handler, or if you put your <script> element at the end of the body you don't need a ready handler at all.
You need to catch update or stop event from sortable instance. Detailed document just right there
https://api.jqueryui.com/sortable/#event-stop
https://api.jqueryui.com/sortable/#event-update
Live Demo And Working Code

JQuery partly triggered

I'm a beginner with JQuery and I was trying to create a button that dynamically changes the colors defined in the CSS depending on what color it is right now (just switch between blue / red) and also change the text on the button.
The .draggable() part executes just fine and so does the first and last console.log, so everything but the part within the click event handler works ... but why?
Relevant html code:
<!DOCTYPE html>
<html>
<head>
<title>Meine Website</title>
<meta charset="utf-8">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript">
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"
type="text/javascript">
</script>
<script src="home_jquery.js"></script>
<script src="home_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="home_style_blau.css">
</head>
<body>
<input type="button" id="farbwechsel_button" value="Rot" />
/* rest of html (taschenrechner_box, etc.) */
</body>
Here's the jQuery part:
var blau = true;
$(document).ready(function () {
$('#taschenrechner_box').draggable();
console.log("test1");
$('#farbwechsel_button').click(function() {
console.log("test2");
if (blau == true) {
console.log("blau = " + blau);
$('body').css({"background-color": "8b0000"});
$('#farbwechsel_button').value = "Blau";
blau = false;
}
else {
console.log("blau = " + blau);
$('body').css({"background-color": "lightsteelblue"});
$('#farbwechsel_button').value = "Rot";
blau = true;
}
console.log("test3");
})
console.log("test4");
});
In your HTML you have:
<input type="button" id="farbwechsel_button" value="Rot" />
But in your JS you refer to
$('#farbwechel_button').click(function() {
Note the forgotten s in your JS. So the JS should be:
$('#farbwechsel_button').click(function() {
Edit: you've forgotten the s in al your referrals to the button. Don't forget to add it everywhere. You've also forgotten a ; just before the last console.log() function.
Edit 2: Here's a Fiddle with a working example. It's pretty much self explanatory. In this case you preferably should make use of classes which you toggle on pressing the button.

More then one event in an onclick print event

I have an onclick print event, its working fine but now i have some div's i want to print out, so my question is, how can i make this script working with all id="PrintElement" Or id="PrintElement1" / id="PrintElement2" and so on, so i can add the ID to the div's i want to print out on one paper.
I have this Javascript, thats work with One div called id="PrintElement".
<script type="text/javascript">
//Simple wrapper to pass a jQuery object to your new window
function PrintElement(elem){
Popup($(elem).html());
}
//Creates a new window and populates it with your content
function Popup(data) {
//Create your new window
var w = window.open('', 'Print', 'height=400,width=600');
w.document.write('<html><head><title>Print</title>');
//Include your stylesheet (optional)
w.document.write('<link rel="stylesheet" href="add/css/layout.css" type="text/css" />');
w.document.write('<link rel="stylesheet" href="add/css/main.css" type="text/css" />');
w.document.write('</head><body>');
//Write your content
w.document.write(data);
w.document.write('</body></html>');
w.print();
w.close();
return true;
}
</script>
Then i have a div
<div id="PrintElement">
SOME CODE.....SHORT/LONG
</div>
And to activate the function i have
<a onclick="PrintElement('#PrintElement')">Print</a>
Working fine now i just want it to work with more then one div called id="PrintElement" or if easier i can call the divs ID PrintElement and a number... so it just print out the div's with the ID's
<div id="PrintElement">
SOME CODE.....SHORT/LONG
</div>
<div>
SOME CODE.....SHORT/LONG
</div>
<div id="PrintElement">
SOME CODE.....SHORT/LONG
</div>
<div>
SOME CODE.....SHORT/LONG
<div id="PrintElement">
SOME CODE.....SHORT/LONG
</div>
<div>
SOME CODE.....SHORT/LONG
</div>
</div>
Hope u understand..
You should replace id="PrintElement" with class="PrintElement" in your HTML
And then change your <a onclick="PrintElement('#PrintElement')">Print</a> with <a onclick="PrintElement('.PrintElement')">Print</a>
And then:
function PrintElement(elem){
$(elem).each(function() {
Popup($(this).html());
});
}
This will open a new window for every PrintElement though...
You can collect data with a var and then call Popup at the end of the loop.
EDIT: The code above is using jQuery... so you'll need the library.
EDIT2: If you want to collect data and open only one popup
function PrintElement(elem){
var data = '';
$(elem).each(function() {
data = data + $(this).html();
});
Popup(data);
}
Without jQuery, first move the code that enumerates target IDs to a function, don't embed it in the HTML:
<a onclick="PrintElements()">Print</a>
And in JS:
function PrintElements() {
printElement('#PrintElement1')
printElement('#PrintElement2')
}
There's a better approach, however. You can use classes (<div class="PrintElement">) in your HTML to mark print targets and then pick them up from PrintElements using document.getElementsByClassName.
function PrintElements() {
targets = document.getElementsByClassName('PritnElement')
[].forEach.call(targets, function(x) {
PrintElement(x)
})
}

Google Custom Search on submit

I would like to customize my search form. I am using Google Search Service and have it linked to my domain and so on.
I chose the two column layout in the Control Panel, but however, I want to do something onSubmit of the form.
So I tried to put an actionlistener in jQuery into the form, however does not work.
Then I thought google certainly provides something for that. And yes they do. It is called:
setOnSubmitCallback()
http://code.google.com/apis/websearch/docs/reference.html
Unfortunately I dont get it.
So far I have:
google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
function initialize()
{
var searchControl = new google.search.CustomSearchControl('017998360718714977594:j6sbtr-d6x8');
searchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
searchControl.draw('cse', options);
}
google.setOnLoadCallback(initialize);
So i have two divs:
#cse-search-form for the form and #cse for the results
#cse is in another div #searchResults, that is hidden and here it comes:
I want to open #searchResults in a dialog from jQuery UI.
$("#searchResults").dialog( { minWidth: 750, minHeight: 750 } );
Which will result into:
.setOnSubmitCallback(function() {
$("#searchResults").dialog( { minWidth: 750, minHeight: 750 } );
} );
So my problem now is, where and on what do I have to put the setOnSubmitCallback?
I cannot put it on google.search.Search or CustomSearchControl as it is stated in the documentation. ANd I cannot call it in the onLoadCallback so it is very strange for me. Cannt figure out how to do that.
I hope somebody has some more experience for the google search and could help me out with a solution.
Thank you very much in advance.
NOTE: the code below is using something Google deprecated. Use this instead: http://code.google.com/apis/customsearch/v1/overview.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Hello World - Google Web Search API Sample</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
//<![CDATA[
google.load('search', '1');
google.load("jquery", "1.5.2");
google.load("jqueryui", "1.8.12");
function OnLoad() {
var searchComplete = function(searchControl, searcher){
$('#searchResults').dialog({modal: true, width: 700, height: 400, position: [50, 50]});
for (result in searcher.results) {
var content = searcher.results[result].content;
var title = searcher.results[result].title;
var url = searcher.results[result].url;
$('#searchResults ul')
.append($('<li></li>')
.append($('<a/>').attr('href', url).text(title))
.append($('<p/>').text(content)));
}
};
// called on form submit
newSearch = function(form) {
if (form.input.value) {
// Create a search control
var searchControl = new google.search.SearchControl();
// Add in a set of searchers
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.VideoSearch());
// tell the searchControl to draw itself (without this, the searchComplete won't get called - I'm not sure why)
searchControl.draw();
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setSearchCompleteCallback(this, searchComplete);
searchControl.execute(form.input.value);
}
return false;
}
// create a search form without a clear button
// bind form submission to my custom code
var container = document.getElementById("searchFormContainer");
this.searchForm = new google.search.SearchForm(false, container);
this.searchForm.setOnSubmitCallback(this, newSearch);
}
google.setOnLoadCallback(OnLoad);
//]]>
</script>
</head>
<body>
<div id="searchFormContainer">Loading</div>
<div id="searchResults" title="Search Results">
<ul></ul>
</div>
</body>
</html>

Categories

Resources