get text from attribute and format it - javascript

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

Related

Jquery .each not working for first row from the table

I am using jquery .each to loop the values and push in JSON. it is working for all the rows leaving the first row.
for (j = 0; j < parsedResult.length; j++) {
var pack_id = parsedResult[j].pack_id;
var pack_dsc = parsedResult[j].pack_dsc;
var pack_base_amount = parsedResult[j].pack_base_prc;
var pack_tax_amount = parsedResult[j].pack_tax_amt;
var pack_grand_total = parsedResult[j].pack_grand_total;
row += "<span id='single_pack_details'><span id='pack_id' class='hidden'>" + pack_id + "</span><b>Pack description: </b><span id='pack_dsc'>" + pack_dsc + "</span><b>Pack Amount:</b> ₹ <span id='pack_grand_total'>" + pack_grand_total + "</span></div><span class='hidden' id='pack_base_amount'>" + pack_base_amount + "</span><span class='hidden' id='pack_tax_amount'>" + pack_tax_amount + "</span></span>";
}
Below is where i trying to put it in a loop and pushing to pack_details object
$(this).closest("tr").find('#single_pack_details').each(function () {
var obj = {
pack_id: $(this).closest("span").find("#pack_id").text(),
pack_dsc: $(this).closest("span").find("#pack_dsc").text(),
pack_grand_total: $(this).closest("span").find("#pack_grand_total").text(),
pack_base_amount: $(this).closest("span").find("#pack_base_amount").text(),
pack_tax_amount: $(this).closest("span").find("#pack_tax_amount").text()
}
pack_details.push(obj);

How to populate HTML drop down with Text File using JavaScript?

I have been stuck on this problem for a while now, Basically i want to populate the below select with option group and option check boxes. The text file imports to JS just fine, i'm getting the problem trying to populate the drop down. Here is my HTML:
function LoadTxtFile(p) {
var AllTxtdata = '';
var targetFile = p.target.files[0];
if (targetFile) {
// Create file reader
var FileRead = new FileReader();
FileRead.onload = function (e) {
if (FileRead.readyState === 2) {
AllTxtdata = FileRead;
// Split the results into individual lines
var lines = FileRead.result.split('\n').map(function (line) {
return line.trim();
});
var select = $("#MySelect");
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function (line) {
// If line ends it " -" create option group
if (line.endsWith(" -")) {
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id'" + currentGroup + "' label='" + currentGroup + "'>");
// Else if the line is empty close the option group
} else if (line === "") {
select.append("</optgroup>");
// Else add each of the values to the option group
} else {
select.append("<option type='checkbox' id='" + (currentGroup + optionCounter) + "' name'"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
}
}
FileRead.readAsText(targetFile);
}
}
document.getElementById('file').addEventListener('change', LoadTxtFile, false);
<html>
<body>
<select name="MySelect" id="MySelect"/>
</body>
</html>
I believe you are using append incorrectly as you are dealing with partial nodes with the optgroup. I would build the html snippet then append it in one go. This would also bring a performance benefit as multiple DOM manipulations can get expensive.
I'd do something like the following.
function LoadTxtFile(p) {
var AllTxtdata = '';
var htmlString = '';
//Optional Templates. I find them more readable
var optGroupTemplate = "<optgroup id='{{currentGroup}}' label='{{currentGroup}}'>";
var optionTemplate = "<option type='checkbox' id='{{currentGroupCounter}}' name='{{currentGroupCounter}}' value='{{line}}'>{{line}}</option>";
var targetFile = p.target.files[0];
if (targetFile) {
// Create file reader
var FileRead = new FileReader();
FileRead.onload = function (e) {
if (FileRead.readyState === 2) {
AllTxtdata = FileRead;
// Split the results into individual lines
var lines = FileRead.result.split('\n').map(function (line) {
return line.trim();
});
var select = $("#MySelect");
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function (line) {
// If line ends it " -" create option group
if (line.endsWith(" -")) {
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
htmlString += optGroupTemplate.replace("{{currentGroup}}", currentGroup);
// Else if the line is empty close the option group
} else if (line === "") {
htmlString +="</optgroup>";
// Else add each of the values to the option group
} else {
//I'm assuming you want to increment optionCounter
htmlString += optionTemplate.replace("{{currentGroupCounter}}", currentGroup + optionCounter).replace("{{line}}", line);
}
});
select.append(htmlString);
}
}
FileRead.readAsText(targetFile);
}
}
document.getElementById('file').addEventListener('change', LoadTxtFile, false);
NOTE the above is untested and may need some debugging.

Only show objects in array that contain a specific string

I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>

WebDB - For each Column, in Each Row

in webDB, EG: HTML5 SQLLite
How can I do the following:
For i = 0 To RS.Fields.Count -1
Response.Write "Field Name: " & RS.Fields(i).Name & "<br>"
Response.Write "Field Value: " & RS(i) & "<br>"
Next
If, at all...
Or, another question would be, how can I iterate the columns themselves and optimally, retrieve the columns name.
I found the answer
function showQueryResults(tx, r) {
// alert("showing [" + r.rows.length.toString() + "] query results");
var rs = null;
var $tr, $td;
var $t = $("<table border='1' cellpadding='2 cellspacing='0' />");
if (r.rows.length > 0) {
rs = r.rows.item(0);
$tr = $("<tr />");
$.each(rs, function (key, val) {
$tr.append($("<th>" + key + "</th>"));
});
$t.append($tr);
for (var i = 0; i < r.rows.length; i++) {
rs = r.rows.item(i);
$tr = $("<tr />");
$.each(rs, function (key, val) {
$tr.append($("<td>" + rs[key] + "</td>"));
});
$t.append($tr);
$tr = null;
};
};
$("#formHolder").children().remove();
$("#formHolder").append($t).show();
$t = null;
};

How to rewrite this Javascript code using Jquery?

function SelectDistrict(argument)
{
var sel=document.getElementById("city");
sel.style.display = '';
sel.options.length = 0;
sel.options.add(new Option('Please select a location',''));
var i=1;
var tempInt=parseInt(argument);
if (tempInt%10000==0)
{
var place1=document.getElementById('place1');
place1.innerHTML =county[tempInt];
}
sel.options.add(new Option('all',tempInt));
$('#inputcity').hide();
while (i<=52)
{
tempInt+=100;
if (county[tempInt]==undefined)
{
break;
}
else {
op_cir = new Option(county[tempInt], tempInt);
sel.options.add(op_cir);
}
i++;
}
}
You could do something like this:
function SelectDistrict(argument)
{
var sel = $('#city'); // Store the jQuery object to save time
sel.hide().empty().append('<option>Please select a location.</option');
var i = 1;
var tempInt = argument;
if (tempInt % 10000 == 0)
{
$('#place1').html(county[tempInt]);
}
sel.append('<option value="'+tempInt+'">all</option>');
$('#inputcity').hide();
var optionsValue = ''; // Appending strings to each other is faster than modifying the DOM
tempInt += 100;
while ((i <= 52) && (county[tempInt] != undefined)) // Just put the condition here instead of breaking the loop
{
optionsValue += "<option value='" + tempInt + "'>" + county[tempInt] + "</option>";
tempInt += 100;
i++;
}
sel.append(optionsValue);
}
I hope that works for you!
you have to replace every document.getElementById() by $("#elementid") like $("#city");
and place1.innerHTML =county[tempInt]; by $("#place1").text(county[tempInt]);
You can change the while loop to:
$.each(county, function(i, itm) {
optionsValue += "<option value='" + i + "'>" + itm + "</option>";
})

Categories