How to rewrite this Javascript code using Jquery? - javascript

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>";
})

Related

Javascript chinese variable being passed to bash script as question mark

I have this javascript function here, the routeno variable will pass a Chinese value
routeno: 粤ZX123港
function getRouteLegNoList()
{
var data = "host="+lphost
+ "&user="+user
+ "&gateway="+gateway
+ "&routedate="+routedate.value
+ "&routeno="+routeno.value
+ "&action=GETROUTELEGNOLIST";
alert(lphost+'|'+user+'|'+gateway+'|'+routedate.value+'|'+routeno.value);
callAjax("../restartAndMoveDeclaration.cgi?"+data, "GET", "",
function(text) {
alert(text);
var html = "<select id=routelegno>";
var count = 0;
var lines = text.split("\n");
for(var i = 0; i < lines.length; i ++)
{
var line = lines[i];
var c;
if(line.indexOf("Data|") == 0) {
count += 1;
c = line.split("|");
html += "<option value=\"" + c[1]
+ "\"";
if(c[1]==origRouteLegNo) {
html += " selected ";
}
html += ">" + c[1] + "</option>";
}
}
html += "</select>";
dvroutelegno.innerHTML = html;
if(count==0){
alert('No Route Legs were found for [' +
gateway + '] [' +
routedate.value + '] [' +
routeno.value + ']');
} else {
if(count==1) {
trroutelegno.style.visibility = 'hidden';
} else {
// More than one, display the select box
trroutelegno.style.visibility = 'visible';
}
}
}
);
}
but when shell script captured the variable it does not read the Chinese character and replaced it as question mark
routeno: ?ZX123?
I've already tried to set different NLS_LANG but encountered the same output
NLS_LANG=AMERICAN_AMERICA.ZHS16GBK
NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Wanting to refactor these nested javascript loops of arrays and the conditional if statements

I have an outer and inner loop that I need to be able to display input text boxes on the outer loop, meanwhile I need to look at the inner loop to exclude value that are in that array. I have tried many different ways and adjustments - this seems to be working - but it looks frickin ugly doesn't it? What can be done to improve readability?
var attName = 'IVS-REC-TYP','a', 'b', 'c', 'd';
var listTEDNoEdit = ['IVS-REC-TYP', 'IVS-TM-STAMP', 'IVS-ADJ-KEY', 'IVS-TCN-FILING-DT', 'IVS-TCN-FILING-ST-CTRY', 'IVS-TCN-SEQ', 'IVS-DT-PROCESSED', 'IVS-ADMIN-CLIN', 'IVS-NBR-LINES', 'IVS-LINE-NBR', 'IVS-DT-PROCESSED', 'IVS-DEERS-DDS', 'IVS-LINE-AMT-ALLOWED'];
// OUTER Loop is attName
// INNER Loop is looking to exclude these values in this array called listTEDNoEdit
for (i = 0; i < tagAttr.length; i++) {
var attName = tagAttr[i].localName;
for (index2 = 0; index2 < listTEDNoEdit.length; index2++) {
if (attName === listTEDNoEdit[index2]) {
tagAttrText += "<li>" + attName + " = " + attText + "</li>";
break;
} else {
var tedEx = listTEDNoEdit.indexOf(attName);
if (tedEx === -1) {
tagAttrText += "<li>" + attName + " = <input type='text' value='" + attText + "'/></li>";
break;
} else {
tagAttrText += "<li>" + attName + " = " + attText + "</li>";
break;
}
break;
}
}
}

Pure Js onclick element doesn't work

I'm having trouble when i run this code under greasemonkey the last position working and run function.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML = document.getElementById('moje_menu').innerHTML + '<p id="' + arry[i] + '">' + arry[i] + '</p>';
document.getElementById(arry[i]).onclick = delete;
}
On 10 position the last working ... WHY ????
When you replace the innerHTML you remove all previous event handlers.
In plain JS you can detect the click in the div but you need to check the event:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
window.onload=function() {
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '">' + arry[i] + '</p>';
}
document.getElementById('moje_menu').onclick=function(e) {
var event = e?e:window.event,tgt = event.target || event.srcElement;
if (tgt.tagName.toLowerCase()=="p") {
console.log(tgt.id);
}
}
}
<div id="moje_menu"></div>
Alternative is inline since you generate the P anyway
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="delete(this)">' + arry[i] + '</p>';
}
You can the modify delete (poor name for a function since delete is a built-in method) to handle the passed paragraph
Example:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="removeP(this)">' + arry[i] + '</p>';
}
<div id="moje_menu"></div>
In jQuery you can easily delegate:
function removeP() {
console.log(this.id);
}
$(function() {
var arry = ["a","b","c"];
var $menu = $('#moje_menu');
for (var i=0; i<arry.length; i++) {
$menu.append($('<p/>',{"id":arry[i], "text":arry[i]}))
}
$menu.on("click","p",removeP);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="moje_menu"></div>
This is my solution i dont like them but works.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i<arry.length; i++) {
// if(arry[i].search('player')==''){
document.getElementById('moje_menu').innerHTML += '<p class="lista_farm" id="'+arry[i]+'">'+arry[i]+'</p>';
//document.getElementById(arry[i]).onclick = usun_farme;
//}
}
var lista_farm = document.getElementsByClassName('lista_farm');
for(var i = 0; i<lista_farm.length; i++){
lista_farm[i].onclick = usun_farme;
}

JavaScript function performed on 6 id's at a time (return after 6 calls ?)

I am wondering if there is a function I can use so that I can seperate data being called into groups of 6.
here is the long form of the code
var currentResults;
function init() {
getProducts();
}
function getProducts() {
$.ajax({
url:"php/products.php",
dataType: "json",
data: { public: true },
success:function(result){
processResults(result);
}
});
}
function processResults(results) {
currentResults = null;
if (!results && !results.products)
return;
currentResults = results.products;
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i]);
}
$(".galleryitem").click(handleThumbnailClick);
}
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if (result.artist)
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallery').append(newDiv);
}
i would like the function to be able to sort the images to groups of 6, something like this... (see areas at bottom with ***'s)
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if ***(!!first 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#galleryfirst').append(newDiv);
if ***(!!second 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallerysecond').append(newDiv);
}
Is doing something like this possible? Or does this whole code need an overhaul?
First, pass the index:
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i], i);
}
Then check it:
function processResult(result, index) {
var newDiv = ...
//check if the index is a multiple of 6
if(index % 6 == 0){
//do something every six results
}
HTH,
-Ted
Since you want to append the new items to different DIVs, the processResults function might be the better place to do this:
function processResults(results) {
var i = 0,
length = results.length,
first = $("#galleryfirst"),
second = $("gallerysecond");
first.append('<div class="imageArtist">' + results[0].artist + '</div>');
for (i; i < 6 && i < length; i++) {
processResult(results[i], first);
}
if (length > 6) {
second.append('<div class="imageArtist">' + results[6].artist + '</div>');
for (i = 6; i < 12 && i < length; i++) {
processResult(results[i], second);
}
}
}
function processResult(product, containerId) {
var newDiv = "...";
// build the HTML for newDiv...
$(containerId).append(newDiv);
}

get text from attribute and format it

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

Categories