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.
Related
I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.
Please try the jsFiddle with jQuery UI selectmenu and 2 buttons.
With the help of 2 buttons prevGame and nextGame I am able to change the selectedIndex variable tracking the currently selected game number.
The jQuery UI selectmenu doc unfortunately does not explain how to set and get (so that I can update the span currGame) the currently selected item:
Please explain: how to set and get the selected item in jQuery UI selectmenu?
HTML-code:
<form>
<select name="games" id="games"></select>
<button id="prevGame"><</button>
<span id="currGame">Loading...</span>
<button id="nextGame">></button>
</form>
JavaScript-code:
var yourGames = [1, 3, 5];
var hisGames = [8, 10, 12, 14];
var selectedIndex = 0;
$("#games").selectmenu();
// emulate repeating server responses
setInterval(function() {
updateMenu();
}, 5000);
$('#prevGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
updateButtons();
});
$('#nextGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, lastIndex());
updateButtons();
});
function lastIndex() {
return yourGames.length + hisGames.length - 1;
}
function updateButtons() {
$('#currGame').html('selectedIndex=' + selectedIndex); // TODO: change to "Game #"
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
}
function updateMenu() {
var yourGroup = ['<optgroup label="YOUR TURN">'];
for (var i = 0; i < yourGames.length; i++) {
var gameNumber = yourGames[i];
var selectedTag = (i == selectedIndex ? 'selected="selected"' : '');
yourGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
yourGroup.push('</optgroup>');
var hisGroup = ['<optgroup label="HIS TURN">'];
for (var i = 0; i < hisGames.length; i++) {
var gameNumber = hisGames[i];
var selectedTag = (i - yourGames.length == selectedIndex ? 'selected="selected"' : '');
hisGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
hisGroup.push('</optgroup>');
$("#games").selectmenu('destroy')
.empty()
.append(yourGroup.length > 2 ? yourGroup.join('') : '')
.append(hisGroup.length > 2 ? hisGroup.join('') : '')
.selectmenu(); // TODO: select the game at selectIndex
}
UPDATE:
I have prepared a newer jsFiddle using selectmenu("refresh") instead of selectmenu("destroy"), but it still has some issues.
jQuery and jQuery UI provides no way to directly set selected index of a select menu. You can use pure javascript way to set the selected index. Also I assume you want to change the text between buttons every time select menu changes. You can do it like so:
var yourGames = [1, 3, 5];
var hisGames = [8, 10, 12, 14];
var selectedIndex = 0;
setInterval(function() {
updateMenu();
updateCurrentGame();
updateButtons();
}, 5000);
$("#games").selectmenu();
$('#prevGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
updateButtons();
updateCurrentGame();
});
$('#nextGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, lastIndex());
updateButtons();
updateCurrentGame();
});
function lastIndex() {
return yourGames.length + hisGames.length - 1;
}
function updateButtons() {
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
}
// Update the select menu when prev & next buttons are pressed
function updateCurrentGame() {
var selectedText = $($("select#games option")[selectedIndex]).text();
$('#currGame').html(selectedText);
// pure js vay to set selected index
$("#games")[0].selectedIndex = selectedIndex;
$("#games").selectmenu("refresh");
}
// Update the selected index every time the select menu is changed manually
$("#games").on("selectmenuchange", function(e, ui) {
console.log(ui);
selectedIndex = ui.item.index;
var selectedText = ui.item.element.text();
$('#currGame').html(selectedText);
updateButtons();
})
function updateMenu() {
var yourGroup = ['<optgroup label="YOUR TURN">'];
for (var i = 0; i < yourGames.length; i++) {
var gameNumber = yourGames[i];
var selectedTag = (i == selectedIndex ? 'selected="selected"' : '');
yourGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
yourGroup.push('</optgroup>');
var hisGroup = ['<optgroup label="HIS TURN">'];
for (var i = 0; i < hisGames.length; i++) {
var gameNumber = hisGames[i];
var selectedTag = (yourGames.length + i == selectedIndex ? 'selected="selected"' : '');
hisGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
hisGroup.push('</optgroup>');
$("#games").selectmenu('destroy')
.empty()
.append(yourGroup.length > 2 ? yourGroup.join('') : '')
.append(hisGroup.length > 2 ? hisGroup.join('') : '')
.selectmenu();
}
button#prevGame,
span#currGame,
button#nextGame,
button#newGame {
vertical-align: top;
}
select#games {
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.min.css" rel="stylesheet" />
<form>
<select name="games" id="games"></select>
<button id="prevGame"><</button>
<span id="currGame">Loading...</span>
<button id="nextGame">></button>
</form>
This can be done in much better way but the following code provides what you asked for:
var yourGames = [1, 3, 5];
var hisGames = [8, 10, 12, 14];
var selectedIndex = 0;
$("#games").selectmenu();
$('#prevGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
updateMenu();
updateButtons();
});
$('#nextGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, lastIndex());
updateMenu();
updateButtons();
});
function lastIndex() {
return yourGames.length + hisGames.length - 1;
}
function updateButtons() {
var selectedText = $("#games option:selected").text();
$('#currGame').html(selectedText);
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
}
function updateMenu() {
var yourGroup = ['<optgroup label="YOUR TURN">'];
for (var i = 0; i < yourGames.length; i++) {
var gameNumber = yourGames[i];
var selectedTag = (i == selectedIndex ? 'selected="selected"' : '');
yourGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
yourGroup.push('</optgroup>');
var hisGroup = ['<optgroup label="HIS TURN">'];
for (var i = 0; i < hisGames.length; i++) {
var gameNumber = hisGames[i];
var selectedTag = (yourGames.length + i == selectedIndex ? 'selected="selected"' : '');
hisGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
hisGroup.push('</optgroup>');
console.log(yourGroup);
console.log(hisGroup);
$("#games").selectmenu('destroy')
.empty()
.append(yourGroup.length > 2 ? yourGroup.join('') : '')
.append(hisGroup.length > 2 ? hisGroup.join('') : '')
.selectmenu();
}
I also updated your Fiddle so you can play with it.
https://jsfiddle.net/q07uarwr/35/
I gave it a try and got both updating and displaying text. But only thing you need to find next is how to set value once selected index changes to the next <option> group in the drop down.
This is the main change:
function updateButtons() {
var gamesOptions = $('#games option');
$('#currGame').html("<span>" + $(gamesOptions[selectedIndex]).text() + "</span>");
$("#games").val(selectedIndex).change();
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
updateMenu();
}
https://jsfiddle.net/q07uarwr/34/
Ok, I am new to JQuery and I have requirement to do some manipulation on table based on rows.
The table consists of rows which belong to 3 different style classes Brand have category and category have products.
var table = $("table tbody");
table.find(".brand").each(function(i) {
var $tdsBrand = $(this).find("td"),
brand = $tdsBrand.eq(0).text(),
atyBrand = $tdsBrand.eq(1).text(),
alyBrand = $tdsBrand.eq(2).text();
console.log('Brand Row ' + (i + 1) + ':\nBrand Name: ' + brand + '\nActual TY: ' + atyBrand + '\nActual LY: ' + alyBrand);
var brandClass = $(this).attr("class");
console.log('brand class : ' + brandClass);
if (this row has next row as category) {
//if(brand.next($( "tr[class='category']" ))) {
//if ("(.band):has(.category)") {
//if ($(this).parents(".category").length == 1) {
table.find(".category").each(function(i) {
var catClass = $(this).attr("class");
console.log('category class : ' + catClass);
var $tdsCategory = $(this).find("td"),
category = $tdsCategory.eq(0).text(),
atyCategory = $tdsCategory.eq(1).text(),
alyCategory = $tdsCategory.eq(2).text();
console.log('Category Row ' + (i + 1) + ':\nCategory Name: ' + category + '\nActual TY: ' + atyCategory + '\nActual LY: ' + alyCategory);
if (This row has next row as product) {
//if(next($( "tr[class='product']" ))) {
//if ("(.category):has(.product)") {
//if ($(this).parents("product").length == 1) {
table.find(".product").each(function(i) {
var proClass = $(this).attr("class");
console.log('product class : ' + proClass);
var $tds = $(this).find("td"),
product = $tds.eq(0).text(),
aty = $tds.eq(1).text(),
aly = $tds.eq(2).text();
console.log('Product Row ' + (i + 1) + ':\nProduct Name: ' + product + '\nActual TY: ' + aty + '\nActual LY: ' + aly);
});
}
});
}
});
What I want to do is, I have to sum up Actual TY values of products and display them on their category. Then sum up Actual TY of categories (which has been calculated from products for different categories) to their brand.
Please refer http://jsfiddle.net/cfhhz0zr/46/ for clear understanding of my requirement and code which I've tried till now.
Thank you.
Just modified a bit your code and it seems that is doing what you are looking for. See also the http://jsfiddle.net/88prg1dt/
I refactored a bit and renamed some variables to make a bit more sense so should be fairly clear now. If you want to calculate the total for a product / category now should be really super simple.
Here is the JS code:
var $table = $("table tbody");
$table.find(".brand").each(function (brandIndex) {
var $brandRow = $(this);
var $tdsBrand = $(this).find("td");
var brandName = $tdsBrand.eq(0).text();
var atyBrand = $tdsBrand.eq(1).text();
var alyBrand = $tdsBrand.eq(2).text();
console.log('Brand Row ' + (brandIndex + 1) + ':\nBrand Name: ' + brandName + '\nActual TY: ' + atyBrand + '\nActual LY: ' + alyBrand);
var $categoryRows = $brandRow.nextUntil('.brand').filter('.category');
$categoryRows.each(function (categoryIndex) {
var $categoryRow = $(this);
var $tdsCategory = $categoryRow.find("td");
var categoryName = $tdsCategory.eq(0).text();
var atyCategory = $tdsCategory.eq(1).text();
var alyCategory = $tdsCategory.eq(2).text();
console.log('Category Row: ' + (categoryIndex + 1) + ':\nCategory Name: ' + categoryName + '\nActual TY: ' + atyCategory + '\nActual LY: ' + alyCategory);
var $productRows = $categoryRow.nextUntil('.brand, .category').filter('.product');
$productRows.each(function (productIndex) {
var $productRow = $(this);
var $tdProducts = $productRow.find("td");
var productName = $tdProducts.eq(0).text();
var atyProduct = $tdProducts.eq(1).text();
var aly = $tdProducts.eq(2).text();
console.log('Product Row ' + (productIndex + 1) + ':\nProduct Name: ' + productName + '\nActual TY: ' + atyProduct + '\nActual LY: ' + aly);
});
});
});
I played a bit with jQuery nextUntil() method as the documentation:
Description: Get all following siblings of each element up to but not
including the element matched by the selector, DOM node, or jQuery
object passed.
Is this answering your question ?
I am showing number counter in one of my section. When I add new betslips to the container the numbers are displaying correctly. However, when I delete any of the row the counter is not getting updated. For example if there are 3 rows numbered 1, 2 and 3 and if I delete row number 2 the updated values are 1 and 3. Infact the counter should reset to 1 and 2.
Here is my JS code
Adding the betslip rows
function createSingleBetDiv(betInfo) {
var id = betInfo['betType'] + '_' + betInfo['productId'] + '_' + betInfo['mpid'],
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b>' + singleBetNumber + '. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'] + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
Function to remove betslip
function removeSingleBet(id) {
// Remove the div
removeElement(id);
// Decrease the betslip counter
decreaseBetSlipCount();
// Decrease bet singles counter
updateBetSinglesCounter();
}
function decreaseBetSlipCount() {
var length = $("#racingBetSlipCount").text().length,
count = $("#racingBetSlipCount").text().substring(1, length-1),
text;
count = parseInt(count);
if (!isNaN(count)) count--;
if (count == 0) text = noSelections;
else text = count;
$("#racingBetSlipCount").text('(' + text + ')');
}
This could be done using only CSS, e.g:
DEMO jsFiddle
HTML:
<div id="bets">
<div class="bet"> some content</div>
<div class="bet"> some content</div>
<div class="bet"> some content</div>
</div>
CSS:
#bets {
counter-reset: rowNumber;
}
#bets .bet {
counter-increment: rowNumber;
}
#bets .bet::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
All row number will be updated automatically when adding/removing any row.
You can manage to do that with following steps;
Enclose bet no with span,
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '<span>. ' + betInfo['horseName'] + '</b></p>');
and I assume you have aouter div called "your_div"
Call below function after every increase and decrease event
function updateBetNo() {
var counter = 1;
$("#your_div .bet_no").each(function(i, val) {
$(this).text(counter);
counter++;
});
}
Make the betNumber findable:
$(leftDiv).append('<p class="title"><b><span class="singleBetNumber">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
After an insert or delete renumber:
$('.singleBedNumber').each(function(idx, el) {
$(el).html('' + (idx + 1));
});
The first problem I see is that $("#racingBetSlipCount") is likely not selecting what you think it is. Since #racingBetSlipCount is an id selector it will only select one item.
To me you need to wrap the betnumber in something accessible so you can update it without having to parse through the title.
So first you would update the creation of the betTitle:
$(leftDiv).append('<p class="title"><b><span class=\'betNum\'>' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
Then you can loop through each and update the number appropriately.
var count = 1;
$.each($(".betNum"), function(){
$(this).html(count++);
});
I have a div elements with data-seat and data-row property:
<div class='selected' data-seat='1' data-row='1'></div>
<div class='selected' data-seat='2' data-row='1'></div>
<div class='selected' data-seat='3' data-row='1'></div>
<div class='selected' data-seat='1' data-row='2'></div>
<div class='selected' data-seat='2' data-row='2'></div>
I want print friendly message for selected seats:
var selectedPlaceTextFormated ='';
$(".selected").each(function () {
var selectedPlace = $(this);
selectedPlaceTextFormated += "Row " + selectedPlace.attr("data-row") + " (seat " + selectedPlace.attr("data-seat") + ")\n";
});
alert(selectedPlaceTextFormated);
This code works well and shows the following:
Row 1 (seat 1)
Row 1 (seat 2)
Row 1 (seat 3)
Row 2 (seat 1)
Row 2 (seat 2)
But, I want group seats by row, i.e I want the following:
Row 1(seats: 1,2,3)
Row 2(seats: 1,2)
also, order by row number. How can I do this?
Thanks. DEMO
Here is the code
var selectedPlaceTextFormated ='';
var row_array = [];
$(".selected").each(function () {
var selectedPlace = $(this);
if (!row_array[selectedPlace.attr("data-row")]){
row_array[selectedPlace.attr("data-row")] = selectedPlace.attr("data-seat");
}
else row_array[selectedPlace.attr("data-row")] += ','+selectedPlace.attr("data-seat");
});
for (row in row_array){
alert("Row "+ row +"(seat " + row_array[row] + ")\n" );
}
And here the link to the working fiddle: http://jsfiddle.net/3gVHg/
First of all, jQuery is kind enough to automatically grab data- attributes into its data expando object, that means, you can access those data via:
jQueryObject.data('seat');
for instance.
Your actual question could get solved like
var $selected = $('.selected'),
availableRows = [ ],
selectedPlaceTextFormated = '',
currentRow,
currentSeats;
$selected.each(function(_, node) {
if( availableRows.indexOf( currentRow = $(node).data('row') ) === -1 ) {
availableRows.push( currentRow );
}
});
availableRows.forEach(function( row ) {
selectedPlaceTextFormated += 'Row ' + row + '(';
currentSeats = $selected.filter('[data-row=' + row + ']').map(function(_, node) {
return $(this).data('seat');
}).get();
selectedPlaceTextFormated += currentSeats.join(',') + ')\n';
});
jsFiddle: http://jsfiddle.net/gJFJW/3/
You need to use another variable to store the row, and format accordingly.
var selectedPlaceTextFormated ='';
var prevRow = 0;
$(".selected").each(function () {
var selectedPlace = $(this);
var row = selectedPlace.attr("data-row");
var seat = selectedPlace.attr("data-seat");
if(prevRow == row){
selectedPlaceTextFormated += "," + seat;
}
else{
if(selectedPlaceTextFormated != ''){
selectedPlaceTextFormated += ')\n';
}
selectedPlaceTextFormated += "Row " + row + " (seat " + seat;
prevRow = row;
}
});
selectedPlaceTextFormated += ')\n';
alert(selectedPlaceTextFormated);
Check http://jsfiddle.net/nsjithin/R8HHC/
This can be achieved with a few slight modifications to your existing code to use arrays; these arrays are then used to build a string:
var selectedPlaceTextFormated = [];
var textFormatted = '';
$(".selected").each(function(i) {
var selectedPlace = $(this);
var arr = [];
selectedPlaceTextFormated[selectedPlace.attr("data-row")] += "," + selectedPlace.attr("data-seat");
});
selectedPlaceTextFormated.shift();
for (var i = 0; i < selectedPlaceTextFormated.length; i++) {
var arr2 = selectedPlaceTextFormated[i].split(",");
arr2.shift();
textFormatted += "Row " + (i + 1) + " seats: (" + arr2.join(",") + ")\n";
}
alert(textFormatted);
Demo
I'd just do this:
var text = [];
$(".selected").each(function () {
var a = parseInt($(this).data('row'), 10),
b = $(this).data('seat');
text[a] = ((text[a])?text[a]+', ':'')+b;
});
var selectedPlaceTextFormated ='';
$.each(text, function(index, elem) {
if (!this.Window) selectedPlaceTextFormated += "Row " + index + " (seat " + elem + ")\n";
});
alert(selectedPlaceTextFormated);
FIDDLE