How to clear if there is no result - javascript

I have a map. Whenever I click to state it pulls up the distributors and shows up.
However, if there is no result from the database it leaves the previous one on the page.
What I want is if there is no result for that particular state I would like it to make container empty. How can I do it?
$(document).ready(function() {
$("#SC").click(function() {
if ($("div.SC_info").is(":hidden")) {
$("#repinfo_container div.info_cont").removeClass("active");
$("#repinfo_container div.info_cont").addClass("inactive");
$("div.SC_info").slideDown("fast");
$("div.SC_info").removeClass("inactive");
$("div.SC_info").addClass("active");
$("div.inactive").slideUp("fast");
} else {}
});
});​
Some more details
Look to this picture. http://i.imgur.com/vozKp.png This is an interactive distribution map. The problem is for example in the database I have results(distributors) for CA(California). When I click it pulls up and shows at the bottom. However, if I click LA(state) since there is no result it shows the previous clicked state's results. What I want is if I don't have any results for this state I want it to show that container instead of showing the previous result. I hope now it makes more sense.
Here is the source code of the whole page
pastebin.com/mxyDpZCx

What I want is if there is no result for that particular state I would like it to make container empty.
$("#repinfo_container").empty();

you can do:
$(selector).html('');
A tip:
you should cache your selections to have better performance, like, instead of this:
$("div.SC_info").slideDown("fast");
$("div.SC_info").removeClass("inactive");
$("div.SC_info").addClass("active");
you can have this:
var selection = $("div.SC_info");
selection.slideDown("fast");
selection.removeClass("inactive");
selection.addClass("active");
That way you select the elements once and operate on selection, instead of selecting them three times.

Related

How to create a snappy User Interface with lots of local data?

I have a JSON file with 15000+ items. My JSON file has about 7MB. I'd like to display all results in a table (without pagination) and add a few checkboxes to display or hide the items under certain conditions. To simplify as much as possible, let's say I have a checkbox to display items from Paris only:
The problem is that the UI is not smooth. Clicking on the checkbox takes about one second to refresh the table. It's unacceptable.
I'm using fetch() to download JSON data and then keep it locally. When user clicks on the checkbox, here's what I did:
document.getElementById('paris-only').addEventListener('click', updateTable);
function updateTable() {
const parisOnly = document.getElementById('paris-only').checked;
items.forEach(item => item.visible = !parisOnly || item.city === 'Paris');
refreshTable();
}
function refreshTable() {
[...document.getElementById('items-table').children].forEach((tr, index) => {
tr.classList.toggle('hidden', !items[index].visible);
});
}
.hidden {
display: none;
}
I tried to play with setTimeout(_, 0), but it doesn't help much. It makes the UI freeze less, but it still takes a lot of time to refresh the table.
Is there any strategy available to make such an interface snappy? One of my ideas was to consider <canvas>, which makes drawing many elements quick, but it doesn't seem very natural for the task.
Another option would be to load data with fetch() on scroll, but I'd like to have all data loaded just once if possible.
What else should I consider?
I'd recommend using classes to signify if a given node should be shown or hidden (e.g. every node with name !== 'Paris' is in the notparis class. You can use javascript to initialize these categories (How do I add a class to a given element?) when you fetch the JSON table, and then showing/hiding can use for (tr of document.getElementsByClassName('notparis')) tr.visible = !parisOnly. If these categories overlap (i.e. you want notparis and notcoldweather), you could probably record which classes are currently visible or hidden and use document.getElementsByClassName('notparis notcoldweather') (this may be a bit more complex, but should maintain performance).
Also, changing the items directly instead of using an intermediate list might be more performant.

Show div when click on a different div, and show a different div when clicked again

I currently have made a way so the user can add another text field to the form by pressing on a 'add_another' div, this uses basic JS so when the user presses on the div 'add_another' the div 'author_2' is toggled.
I would like to make it so that when the user presses on the 'add_another' div for a second time it shows 'author_3' div, and when they press 'add_another' again, it then shows 'author_4'. I have put all the CSS and HTML divs in place to support this, I am just trying to adapt my code so it shows one div after another, rather then toggling a single div.
Here is my JS:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('.author_2').toggle();
});
});
</script>
I have tried altering this code, however with no luck.
I haven't added my HTML as it is just 4 divs, 'author_1' 'author_2' ... 3...4
Thankyou for your help
There are two solutions to Your problem.
First one - use static code
It means the max author count is 4 and if user gets to 4, this is it.
If so - You need to store the number of authors already shown.
var authors_shown = 1;
$(document).ready(function() {
$('.add_another').on('click', function(){
authors_shown++;
if (!$('.author_'+authors_shown).is(":visible")) {
$('.author_'+authors_shown).toggle();
}
});
});
But there is also a second - more dynamic option.
What if user wants to input 10 or 20 authors? You don't want to pre render all that html code and hide it. You should clone the div and change its id or if the (HTML) code (for another author) is not too long, you can render it within JS code.
var div = document.getElementById('div_id'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);
If it's a form, then change names of input fields to array as author_firstname[]
Also You can store number of added authors in another hidden field (so you know how long to loop the form fields on the server side.
The second option is a bit more complex and longer, but way more dynamic.
You should make another div when clicked on add_another:
something like this:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('<div><input type="text" name="name[]" /></div>').appendTo('.your_container');
});
});
</script>
as you see, input's name has [] which means you should treat with the inputs as an array.
let me know if you got any further questions
good luck.

jQuery For Loop Image Check and Display

Good afternoon Stack Overflow,
I'm inexperienced when it comes to coding in general and I've been having a problem that's doing my head in!
If you'll allow me to set the scene...
The section of the project I am currently working on involves a user picking items from a warehouse in order to fulfil a shipment and in some cases they have to pick the same item from various locations, when that needs to be done, the small "!" type icon appears next to the item.
The user then can click on the icon and choose which locations they will be retrieving the stock from, they then press confirm on the modal and when it closes it sets the text back to blue and hides the icon.
The part I am having trouble with is that once all the locations have been established, the order needs to be processed and this requires a button to be clicked on, which I only want to appear once all the "!" icons are hidden.
I know there are alot of questions based on for loops and images checks and believe me when I say I've tried hard to figure this out myself and I've tried different approaches:
ShowProcess = false
for (i = 0; i<Picker; i++) {
if ($('#MultiLocIcon'+i).is(':visible')){
ShowProcess = true
}
if (ShowProcess == true) {
$('#ProcessConfirm').show()
};
};
This obviously wouldn't work because its setting the first variable in the list to "true" and will always read it as true, therefore always showing the image, even if the "!" icon still exists in other rows.
I also tried using .each() to test each rows text color of a specific but also had no luck:
var table = $('#RequestedItemsTable');
table.find('tbody > tr').each(function(){
if $('#Desc').css('color') == '#0000FF'){
//do something
I feel like my experience is letting me down as I still have a lot to learn and have a suspicious feeling that the solution is going to be really easy, but then again, its only easy if you know how.
If anyone could take the time to help me with this problem or offer me any advice, I'd be really grateful.
Here is a section of my code which might be useful:
Modal "Confirm" button:
//CONFIRM Button which will submit final picks.
'Confirm': function() {
//Reset the length loop
length = undefined;
//Remove "Multiple Location" icon from the row.
$('#icon'+id).hide();
//Change text colour back to blue to have visual confirmation that item is ready for picking
$('#Desc'+id).css('color', '#0000FF');
$('#QtyReq'+id).css('color', '#0000FF');
$('#QtyinStock'+id).css('color', '#0000FF');
$(this).dialog('close');
The "!" Icon:
<td id= "MultiLocIcon<?=$i;?>"><?if($row->Count_Location > 1)
{?><img src="<?=base_url();?>public/css/images/error.png" alt="LocPick" title="Multiple Locations" style="cursor: pointer;" id= "icon<?=$i;?>" onClick="$.LocPick(<?=$i;?>);"/><?}?></td>
Basically just need to know how my image can show once the loop checks and knows that the "!" icon is hidden from every possible row.
Thank you for your patience.
You'll need to add a second check in your modal logic, perhaps after your .hide():
//Remove "Multiple Location" icon from the row.
$('#icon'+id).hide();
$('img[id^=icon]:visible').length || $('#ProcessConfirm').show();
What this does is combines the :visible pseudo-selector and a regex selector for all img tags with id starting with "icon". This assumes you won't have any other unrelated image tags with an id like "icon*". If the length is 0, it will go ahead and show the #ProcessConfirm element.
simplest solution I would give is to add a class warning to all the table column which has warning icon & then check for visibility of the same.
if($('.warning:visible').length === 0){
//all warning icons are hidden
}
What I would do is based off your HTML, select all the alert icons, and do a :visible psuedo selector on it. This will return all the visible alert icons, if there are none in the array, you know none of them are visible. You will need to identify them with a class, such as .alert:
if( $(".alert:visible").length === 0 ){
// Do your code in here for no visible alert icons!
}
When user clicks confirm on modal you should run a check on how many icons are still visible, and if the amount is 0 then show the button, like this:
// This searchs for every <td> with an id that contains '#MultiLocIcon'
// Then checks if the amount of those which are visible is 0 and do something
if ( $('td[id*=MultiLocIcon]').not(':visible').length === 0 ) {
$('#ProcessConfirm').show()
}

How to refresh DataTables after call to page event?

Here is my scenario ...
I am using pagination with DataTables. My first column is css styled based upon data that is passed in. So, I display the correct colored icon for the property of the item in the table. Everything on page 1 displays correctly. Just doing the basics, everything on further pages does not get displayed because it is removed from the DOM at that time.
So, I did $('#my_id').on('page.dt', function() {perPageFunctionCall();}).dataTable(so on an so forth)}; to call a function which selects the correct colored flag.
When I click on page 2, nothing gets updated. I click on page 1 again and it redisplays the 1st page correctly. I click on page 2 a second time now and it displays everything correctly this time.
So what is causing the display not to update with my new css the 1st trip but to display properly on subsequent trips? Is there someway to refresh the element or the data table after I am done with my css manipulation?
Well it is one of two things:
Either it is
1: I added
.on( 'order.dt', function () { perPageFunctionCall(); } )
.on( 'search.dt', function () { perPageFunctionCall(); } )
in addition to my page function call.
But more likely everyone's favorite reason:
2: Caching
In either case, it does work flawlessly now as expected.
for refresh resp. table :
var path = "/server_processing.php";
var dt = $('#tableid').DataTable();
dt.clear();
dt.draw();
dt.ajax.url(path).load()

Access rendered items

Playing around with Slickgrid. But got some questions that I'm not figurate out.
I have made an Regex filter on two X cells, and it works surprisingly well.
But for every time you filter or make other actions i want to flash all incorrect fields with cellFlash or highlighter.
Atm i have made a formatter with same regex as filter uses but it seems not 100% correct.
The problem when i'm using cellFlash is that it trigger the animation on ALL rows not only the rows thats rendered.
I'm not sure that i'm triggering the flashcell on correct callback/stage, I did it on my filter function i saved all incorrect rows in an array then i loop them throught and trigger flash.
So is it possible to get all items thats rendered in Viewport? Haven't find any information about this. Only data i can get out from getRenderedViewport.. is pxls. getRenderedRange() or getViewport()..
If you need to do processing on each data item in the current slick grid viewport, you can use getRenderedRange() to get the range of data item indexes that are rendered. You could then use that to get each visible data item
function forEachItemInViewport(fn) {
var range = slickGrid.getRenderedRange();
var bottom = range.bottom;
while(bottom--) {
var dataItem = slickGrid.getDataItem(bottom);
fn(dataItem);
}
}
forEachItemInViewport(function (item) {
// do your work on each item in viewport
});

Categories

Resources