jQuery mobile listview change select item and highlight it - javascript

In a page,there is a listview,the first item is selected:
var len = results.rows.length,
$list = $("#listAddr");
var $strHTML =" ";
for (var i = 0; i < len; i++) {
$strHTML += '<li ';
if (i == 0) {
$strHTML += ' data-theme="b" ';
}
$strHTML += '> <a href="#" data-ajax="false"';
$strHTML += ' data-id="' + results.rows.item(i).Id + '">' + results.rows.item(i).Name + '</a></li>';
}
$list.html($strHTML);
$list.delegate('li a', 'click',function(e){
// $("#listAddr").attr("li").removeClass("liSel");
$(this).addClass("data-theme='b'");
$("#listAddr").listview("refresh");
//$(this).removeClass("data-theme");
clickAddr($(this).data('id'));
});
When I select the third item,I want the third item to be "data-theme='b'" style and the first item to remove the theme.How to be able to do that?

You can do soemthing as below
$('#listAddr li').bind('click', function () {
$('#listAddr li').attr("data-theme", "c").removeClass("ui-btn-up-b").removeClass('ui-btn-hover-b').addClass("ui-btn-up-c").addClass('ui-btn-hover-c');
$(this).attr("data-theme", "b").removeClass("ui-btn-up-c").removeClass('ui-btn-hover-c').addClass("ui-btn-up-b").addClass('ui-btn-hover-b');
});
Here is an example on Live fiddle

use data() to change the data attribute...
$.removeData($list.find('li'), "theme");
$(this).data("theme",'b');
try this
$list.on('click','li a',function(e){
$.removeData($list.find('li'), "theme");
$(this).data("theme",'b');
$("#listAddr").listview("refresh");
clickAddr($(this).data('id'));
});

Related

How to add a class to an element based on something saved in Local Storage with JQuery?

Basically, I'm making a TODO list, the functions are save and delete records, which are already implemented and mark as important and mark as done, which are the functions that I'm having trouble with.
This is the method that I use to retrieve the items saved in Local Storage as an array.
function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
This is the method that I use to save records in Local Storage
function add() {
var task = "00"+document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
As you can see, I add the records with two 00 at the beginning, the first number is 0 when that item of the TODO list is "undone", and 1 when it is marked as done, the second number is 0 when that item if the TODO list is "not important", and 1 when it is marked as important, for changing those numbers on the local storage, I do this:-
//if the second digit is 0 then the task is not important
function markAsImportant(){
var id = parseInt(this.getAttribute('id'));
var todos = get_todos();
var task = todos[id].replaceAt(1, "1");
console.log(task);
todos.splice(id, 0, task);
todos.splice(id+1, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
That method is already well implemented and working as it should.
Now, knowing what item of the TODO is important and which one is not, I simply want to add a class to the items which second character is a one, and that is what I try to do here:-
function show() {
var todos = get_todos();
var html = '<div class="list">';
for(var i=0; i<todos.length; i++) {
//HERE HERE HERE HERE HERE
if (todos[i].charAt(1) == '1') {
console.log("important");
$('.item').addClass('important');
}
else{
console.log("not important");
}
html += '<div class="item"> <input type="checkbox" class="check" id="' + i + '"> ' +' <div class="title">' + todos[i].substring(2) + '</div> <div class="tools"> <span class="tag" id="' + i + '"> <img class="important-img" src="resources/important.png"> </span> <span class="delete remove " id="' + i + '"> <img src="resources/thrash.png"> </span> </div></div>';
};
html += '</div>';
document.getElementById('todos').innerHTML = html;
var deleteButtons = document.getElementsByClassName('remove');
for (var i=0; i < deleteButtons.length; i++) {
deleteButtons[i].addEventListener('click', remove);
};
var doneButtons = document.getElementsByClassName('check');
for (var i=0; i < doneButtons.length; i++) {
doneButtons[i].addEventListener('click', markAsDone);
};
var importantButtons = document.getElementsByClassName('tag');
for (var i=0; i < importantButtons.length; i++) {
importantButtons[i].addEventListener('click', markAsImportant);
};
var listItems = document.getElementsByClassName('item');
for (var i=0; i < listItems.length; i++) {
console.log(listItems[i]);
$(listItems[i]).attr('id', i);
};
}
But it simply won't add anything at all to the .item tags, how can I make it actually add the class important to the items that I want ?
You are not adding the html to DOM so $(".item") won't work. This should work:
for (var i = 0; i < todos.length; i++) {
html += '<div class="item';
if (todos[i].charAt(1) == '1') {
console.log("important");
html += ' important'; // The space must be there, so change just the "important" bit, but don't remove the space
} else {
console.log("not important");
}
html += '"><input type="checkbox" class="check" id="' + i + '"> ' + ' <div class="title">' + todos[i].substring(2) + '</div> <div class="tools"> <span class="tag" id="' + i + '"> <img class="important-img" src="resources/important.png"> </span> <span class="delete remove " id="' + i + '"> <img src="resources/thrash.png"> </span> </div></div>';
}
Paste this instead your for loop and post the result in comments under this answer.

Image List view with text and URL

I want to display and list with icon and text. List is link to specific URL. I am storing all these in a array but image is not populating from the array. here is a spinet.
var mainPanel = [ {
icon : "images/green/home.png",
title : "Home",
url : "#tilehome-page"
}, {
icon : "images/green/home.png",
title : "Mayor's Conner)",
url : "#mayorsmessage-page"
}, {
icon : "images/green/home.png",
title : "Report A Problem",
url : "#reportaproblem-page"
} ];
function createmenuPnl() {
var items = '';
//ul = $(".mainMenu:empty");
var ulStr = "<ul>";
for (var i = 0; i < mainPanel.length; i++) {
items += '<li><a href="' + mainPanel[i].url + '"> + mainPanel[i].title
+ '</a></li>';
}
ulStr+= items;
ulStr+='</ul>';
console.log('The ulStr formed is:'+ulStr);
$("#cssmenu").append(ulStr);
$("#cssmenu").trigger( "updatelayout" );
}
All I want is to add image icon dynamically in the list
you forget single quote just before mainPanel[i].title.. it should be like this..
items += '<li><a href="' + mainPanel[i].url + '">' + mainPanel[i].title
+ '</a></li>';
Here we go
The problem is in your loop for
for (var i = 0; i < mainPanel.length; i++) {
// after '"> need one '
items += '<li><a href="' + mainPanel[i].url + '">' + mainPanel[i].title
+ '</a></li>';
}

Syntax Error - Unexpected identifier -(final line of code)

I'm getting an unexpected identifier error in chrome for the last line of this code, does anyone know why? thanks (updated to entire code for the page)
It's supposed to display a list of data for the jobs ive got entered into a database
<?php
error_reporting(0);
include('../includes/header.php');
include('connection.php');
?>
<script src="../jqm/demos/js/jquery.js"></script>
<script type="text/javascript">
var db;
$(document).ready(function () {
loadJobRecords();
}
$(document).on("click", "#jobRecord", function () {
getJobById($(this).data("key"));
});
});
function loadJobRecords() {
db.transaction(function (txs) {
txs.executeSql('SELECT * FROM jobs', [], function (txs, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
var JobRecord = results.rows.item(i);
var individualJob = '';
individualJob = '<li><a href="#detailinfo" id="jobRecord" data-key="' + jobRecord.ID + '" >';
individualJob += '<h3>' + jobRecord.Title + '</h3>';
individualJob += '<p>Testing</p>';
individualJob += '</a></li>';
$('#listofjobs ul').append(individualJob);
$('#listofjobs ul:visible').listview('refresh');
}
});
});
}
function getJobById(id) {
db.transaction(function (txs) {
txs.executeSql('SELECT * FROM jobs WHERE id="' + ID + '"', [], function (txs, results) '){
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
var jobRecord = results.rows.item(i);
var individualjob = '';
individualjob += '<h3>' + jobRecord.Title + '</h3>';
individualjob += '<p>' + jobRecord.Description + '</p>';
individualjob += '<p>' + jobRecord.Username + '</p>';
$('#jobSummary').html(individualJob);
}
});
});
}
</script>
<div class="content container">
<div daa-role="page" id="jobsdatabase">
<section>
<div data-role="content" id="listofjobs">
<ul data-role="listview" data-filter="true" data-inset="true">
</ul>
</section>
</div>
</div>
</div>
<?php include('../includes/footer.php'); ?>
Maybe the jquery selector doesn't find a match?
Try going to the console in chrome and running:
$('#listofjobs ul:visible').length
Is the value greater than 0?
Change to this
var db;
$(document).ready(function () {
loadJobRecords();
$(document).on("click", "#jobRecord", function () {
getJobById($(this).data("key"));
});
});
function loadJobRecords() { ...
You have a quote ' and bracket at the end of this line, just after results - remove them
txs.executeSql('SELECT * FROM jobs WHERE id="' + ID + '"', [], function (txs, results) '){
change to
txs.executeSql('SELECT * FROM jobs WHERE id="' + ID + '"', [], function (txs, results){

css has to apply only one seat <li> ( restrict multiple select)

bus reservation
The following code generate multilpe <li> and when the user click seats, the selected seats css will change. but i want to restrict the multiple selection. the user has to be allow to select only one seat, if he select second <li> (seat) , then the first one has to go unselect
DEMO : http://demo.techbrij.com/780/seat-reservation-jquery-demo.php
CODE : http://techbrij.com/seat-reservation-with-jquery
$(function () {
var settings = {
rows: 6,
cols: 6,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 30,
seatHeight: 30,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1); // Seat No eg : seatNo = 0+0*0+1 (1)
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString(); // Class each seat class Name=seat row-0 col-0
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li onclick="gettable('+ seatNo+')" class="' + className +" table"+seatNo+ '">'
+'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
First remove the class from all elements, then add it to the selected one.
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$('.' + settings.seatCss).removeClass(settings.selectingSeatCss);
$(this).addClass(settings.selectingSeatCss);
}
});
Change the else part to:
else{
$(this).toggleClass(settings.selectingSeatCss);
$(".settings.selectingSeatCss").not(this).removeClass('settings.selectingSeatCss');
}
try changing the code in click() event with this one.
$('.' + settings.seatCss).click(function () {
$(this).addClass(settings.selectedSeatCss).siblings(this).removeClass(settings.selectedSeatCss);
});
working Demo. Hope it helps you.

How to Add Handler Id to Options value loaded by jQuery

I am trying to load a select options by using jQuery from 3 arrays to one select list on click which so far works fine for me at here
But I have an issue here.if you look at the values I have same value on three list so I have to upgrade them by adding also the id of the clicked button to the value some thing like this:
<option value="regi1NNN">NNN</option>
instead of
<option value="NNN">NNN</option>
depends on what button clicked.
Here is my code:
$(document).ready(function () {
var opt1 = ["AAAA", "BBBB", "NNN", "JJJJJ"];
var opt2 = ["KKKK", "FFFF", "NNN", "TTTTT"];
var opt3 = ["MMM", "NNN", "OOOO", "PPPPP"];
$("#regi1").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt1.length; i++) {
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
}
$('#items').append(option);
});
$("#regi2").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt2.length; i++) {
option += '<option value="' + opt2[i] + '">' + opt2[i] + '</option>';
}
$('#items').append(option);
});
$("#regi3").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt3.length; i++) {
option += '<option value="' + opt3[i] + '">' + opt3[i] + '</option>';
}
$('#items').append(option);
});
});
When you create your options like so:
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
Simply add the id of the clicked element as a prefix:
option += '<option value="' + this.id + opt1[i] + '">' + opt1[i] + '</option>';
Working example: http://jsfiddle.net/g8euy/ This way when you combine all your click handlers into one function (which you should, since you have three functions that do the same thing) you'll be all set.
UPDATE: I rewrote your code to only use a single funciton. Example here: http://jsfiddle.net/n2tBC/1/
I added a class and a data attribute to your buttons:
<div class="container">
<div class="well">
<div class="btn-group">
<button type="button" class="btn btn-default listy" id="regi1" data-vals="opt1">Left</button>
<button type="button" class="btn btn-default listy" id="regi2" data-vals="opt2">Middle</button>
<button type="button" class="btn btn-default listy" id="regi3" data-vals="opt3">Right</button>
</div>
<br />
<br />
<select id="items"></select>
</div>
</div>
And then the script combines your value lists into an object, and there's a single function that gets the data based on the data-val of the clicked button:
$(document).ready(function () {
var myVals = {
opt1: ["AAAA", "BBBB", "NNN", "JJJJJ"],
opt2: ["KKKK", "FFFF", "NNN", "TTTTT"],
opt3: ["MMM", "NNN", "OOOO", "PPPPP"]
}
$(".listy").click(function () {
$('#items option').remove();
var clickedButton = $(this);
var valueList = myVals[clickedButton.data('vals')];
var option = '';
for (i = 0; i < valueList.length; i++) {
option += '<option value="' + this.id + valueList[i] + '">' + valueList[i] + '</option>';
}
$('#items').append(option);
});
});
Now when you add more buttons, you don't add more code.

Categories