I'm using this multiple checkbox plugin
http://multiple-select.wenzhixin.net.cn/docs/en/download
I'm using the filtering option
The problem that I have is that if I have only one option whit Select All like this image
when I click on BERMUDA option, in debug raises both
onClick event and onCheckAll event even if I don't click on Select All.
This thing happens only if I only have one entry besides "Select All" entry.
The js code is the following:
$("#" +ddl_ID).multipleSelect({
filter: true,
multiple: true,
"data-multiple-width": 150,
onClick: function (view) {
//aggiungo alla lista di selezionati solo il valore selezionato.
//se esiste già lo elimino
listaSel = $("#"+txtSel_ID).val();
var array = listaSel.replace("[", "").replace("]", "").split(",");
const index = array.indexOf(view.value);
if (index >= 0) //esiste già, lo elimino
array.splice(index, 1);
else //non esiste, lo aggiungo
array.push(view.value);
listaSel = "";
//ricostruisco la stringa
for (var i = 0; i < array.length; i++) {
if (array[i] != "")
listaSel += array[i] + ",";
}
if (listaSel.length > 0)
listaSel = listaSel.substring(0, listaSel.length - 1);
$("#" +txtSel_ID).val("[" + listaSel + "]");
console.log($("#" +txtSel_ID).val());
},
onCheckAll: function (view) {
listaSel = $("#" +txtSel_ID).val(); //attualmente nella ricerca
var listaSelezionata = $("#" +ddl_ID).multipleSelect("getSelects"); //selezionati adesso
var array = listaSel.replace("[", "").replace("]", "").split(",");
for (var i = 0; i < listaSelezionata.length; i++) {
const index = array.indexOf(listaSelezionata[i]);
if (index == -1) //non esiste, lo aggiungo
array.push(listaSelezionata[i]);
}
listaSel = "";
//ricostruisco la stringa
for (var i = 0; i < array.length; i++) {
if (array[i] != "")
listaSel += array[i] + ",";
}
if (listaSel.length > 0)
listaSel = listaSel.substring(0, listaSel.length - 1);
$("#" +txtSel_ID).val("[" + listaSel + "]");
console.log($("#" +txtSel_ID).val());
},
onUncheckAll: function (view) {
listaSel = $("#" +txtSel_ID).val(); //attualmente nella ricerca
var listaSelezionata = $("#" +ddl_ID).find('option').not(':selected'); //selezionati adesso
var array = listaSel.replace("[", "").replace("]", "").split(",");
for (var i = 0; i < listaSelezionata.length; i++) {
const index = array.indexOf(listaSelezionata[i].value);
if (index > -1) // esiste, lo rimuovo
array.splice(index, 1);
}
listaSel = "";
//ricostruisco la stringa
for (var i = 0; i < array.length; i++) {
if (array[i] != "")
listaSel += array[i] + ",";
}
if (listaSel.length > 0)
listaSel = listaSel.substring(0, listaSel.length - 1);
$("#" +txtSel_ID).val("[" + listaSel + "]");
console.log($("#" +txtSel_ID).val());
}
});
//se la listaSel è vuota richiamo per sicurezza l'uncheckall
if (listaSel == undefined || listaSel == "" || listaSel == "[]") {
console.log("lista null");
$("#" +ddl_ID).multipleSelect("uncheckAll");
}
//se no imposto i valori selezionati
else {
$("#" +ddl_ID).multipleSelect("setSelects", JSON.parse(listaSel));
}
}
Can someone help me?
Feels like its the plugin's default behavior but we can tackle it by simply looking at your question as the answer resides there. You mentioned that this issue occurs when only one item left in the multi-select box right? well, that's our cue.
So all you need to do is to place a condition to handle this issue when the length is only equal to one. Judging by your code, I believe we can get the total length by this line of code:
var listaSelezionata = $("#" +ddl_ID).multipleSelect("getSelects"); //selezionati adesso
And we will simply go into onCheckAll event and add a condition that if items are greater than 1 then only perform certain action in oncheckAll event else nothing will happen.
onCheckAll: function (view) {
var listaSelezionata = $("#" +ddl_ID).multipleSelect("getSelects"); //selezionati
if(listaSelezionata.length > 1){
//Do somthing
}
}
Hope it helps :)
Ciao Martina, tutto bene?
I have to admit I don't know the plugin you're using, but reading your question it seems it is a works as intended or side effect of the plugin itself.
To be sure about that you can try to see if an onUncheckAll event is fired when you uncheck BERMUDA and/or to repeat the same test with a search having two results and checking what happens when you select/unselect all the results.
If that is the case I simply suggest you to write your handles keeping in mind this behavior of the plugin.
Hope this helps.
Related
I am using laravel and stuck in a condition. i add counter and a condition that when counter equals to 4 disable the button and no more item added.
this is my code
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
var array = document.getElementsByClassName('compare');
for (var i = 0 ; i < array.length ; i++)
{
array[i].setAttribute('disabled','');
}
}
i want's to disable button after reaching the limit and no more item added from anywhere if the counter equals to 4.
var increment = 0;
$(document).ready(function() {
$(".compare").click(function() {
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" + increment + ")";
if (increment == 4) {
var array = document.getElementsByClassName('compare');
for (var i = 0; i < array.length; i++) {
array[i].setAttribute('disabled', '');
}
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="compare" id="compare">INCREMENT</button>
Not really Laravel related, but you don't need jQuery just to add a counter. Vanilla JS gets the job done:
<button id="btn" onclick="buttonCheck()">Click me</button>
<script>
var counter = 0;
function buttonCheck(){
counter++;
if (counter >= 4)
document.getElementById("btn").setAttribute("disabled", "disabled");
}
</script>
Seeing that you already have jQuery in your code. I'll give an example using jQuery.
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
$(".compare").prop("disabled", true);
//prop() is used to set attribute value of an html element
}
}
}
Most of the time, this would work. But in some cases that it won't, you could manipulate this with CSS.
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
$(".compare").css("pointer-events", "none");
}
}
}
I need to add elements to container on a first click and delete it on a second one. I guess I'm trying to make it super hard while there is a more elegant and clear solution. Fiddle Link
I was thinking of arrays to create a 1st array for clicked elements and the 2nd one for elements that are already in a container. Then filter the first array through the second one and delete those (unmatched) elements from my container.
var click = +$(this).data('clicks') || 0; // Check if contacts cliked first time
if (click % 2 == 1) { // 2nd click
fruits.splice($.inArray(name, fruits), 1); // Remove Name from an array
$(".test .single").each(function (index, elem) {
compArr.push($(this).text());
});
keyArr = fruits.filter(i => compArr.indexOf(i) !== -1);
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here
} else { // 1st click
fruits.push(name);
$('.test textarea').css({
'font-size': '12px',
'border': '0'
}).prop('placeholder', '').before('<span class="single">' + name + '></span>');
$('textarea').val('');
}
$(this).data('clicks', click + 1);
For me, this part doesn't work properly. But I would love to hear any of your suggestions even if the entire logic is wrong. Thanks!
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
}
I've managed to fix it. Added this code:
let deleteSingle = $('.single');
for (let i = 0; i < deleteSingle.length; i++) {
for (let j = 0; j < arrayNewKeys.length; j++) {
if (deleteSingle[i].innerHTML.includes(arrayNewKeys[j])) {
deleteSingle.eq(i).addClass('a');
break;
} else {
deleteSingle.eq(i).removeClass('a');
}
}
}
$('.styleContacts:not(.a)').remove();
if ($('.test > .single.a:only-child')) {
$('.single.a').removeClass('a');
}
Instead of this:
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here
'm trying to create a function that will continuously loop through an array and check if there are still elements with a certain value. If there are no more of these elements, then I would like the function to execute a certain action.
I'm checking for '0'. If nothing is ='0', then i want to display an image. Here's what I have, any suggestions?
function partiewin()
// On verifie si il y a encore des cases avec pour valeur '0' et si non, on fini la partie
{
var found=false;
for (i=1; i <= hauteur; i++)
{
for (j=1;j <= largeur; j++)
{
if( decor[i][j]!=0)
{
window.alert("You win");
found=1;
}
}
}
if(!found)
{
}
}
This is the array
var decor = new Array(hauteur);
for (i=0; i <= hauteur; i=i+1)
{
decor[i] = new Array(largeur);
}
The array is a long list of this shape :
decor[1][1] = '24'; decor[1][2] = '21'; decor[4][8]='0' ; etc
Shouldn't this work? I'm not getting any alerts or any answer whatsoever once all the '0' are technically gone from the map..
var found = false;
for(var i = 0; i < hauteur.length ; i++){
for (var j = 0; j< hauteur[i].length ; j++){
if( hauteur[i][j] == '0'){
found = true;
break;
}
}
}
if(!found){
console.log("display image code here")
}
previous and Next buttons don't have limitations, ie: can move before and after first and last pages... cant seem to limit this.
I've created if statements to try and stop the button from executing but it wont work. any ideas?
jsFiddle: https://jsfiddle.net/s7ac8aq3/
$(function() {
$(document).ready(function(){
//amount of items on page
var num = $('.post').length;
//set items per page
var itemsPerPage = 1;
var nav = false;
//array of all items
var items = $(".post");
//rounds up to the nearest whole number -- number of pages needed to display all results
var numOfPages = Math.ceil((num / itemsPerPage));
//container div
var paginationContainer = $("#pagination-container");
//initial link num
var linkNum = 1;
paginationContainer.prepend("<button class='pagination' id='btn-prev' value='prev'>Prev</button>");
//creates all pagination links as input buttons (can be anything... li, a, div, whatever)
for(i = 0; i < numOfPages; i++)
{
paginationContainer.append("<button class='pagination' id='btn-" + (i + 1) +"' " + "value='" + (i + 1) + "'>" + (i + 1) + "</button>");
}
paginationContainer.append("<button class='pagination' id='btn-next' value='next'>Next</button>");
//does the initial filtering of the items, hides anything greater than page 1
items.filter(":gt(" + (itemsPerPage -1) + ")").hide();
//finds the input feilds and executes onclick
paginationContainer.find('button').on('click', function(){
//REQUIRED RESETS NAV BOOL SO CLICKS WILL REGISTER
nav = false;
//stores the value of the link in this var
var val = $(this).val();
//if value is next or prev
if(val == "prev")
{
if(linkNum > 1)
{
nav = true;
linkNum = linkNum - 1;
var currentBtn = paginationContainer.find("#btn-" + linkNum);
var otherButtons = paginationContainer.find('button');
otherButtons.attr('class', "pagination");
currentBtn.attr('class', "current");
currentBtn.focus();
}
}
else if (val == "next")
{
if(linkNum < numOfPages)
{
nav = true;
linkNum = linkNum + 1;
var currentBtn = paginationContainer.find("#btn-" + linkNum);
var otherButtons = paginationContainer.find('button');
otherButtons.attr('class', "pagination");
currentBtn.attr('class', "current");
currentBtn.focus();
}
}
if(nav == false)
{
//reoves the current class from all buttons before reassigning
var otherButtons = paginationContainer.find('button');
linkNum = $(this).val();
otherButtons.attr('class', "pagination");
//assigns current class to current button
$(this).attr("class", "current");
}
//creates an array of items to hide based on if the set results are less than the link num
var itemsToHide = items.filter(":lt(" + ((linkNum-1) * itemsPerPage) + ")");
// adds any items that are greater than the set results from the link num to the hide array
$.merge(itemsToHide, items.filter(":gt(" + ((linkNum * itemsPerPage) -1) + ")"));
// hides the items in hide array
itemsToHide.hide();
//shows all items NOT in the hide array
var itemsToShow = items.not(itemsToHide);
itemsToShow.show();
});
});
});
A little debugging of your jsFiddle identified the problem. In this part of the code:
} else if (val == "next") {
if (linkNum < numOfPages) {
nav = true;
linkNum = linkNum + 1;
the value of linkNum is sometimes being stored as a string. As a result, adding "3"+1 produces "31" in JavaScript.
The trivial solution is to convert it to an integer before the addition:
linkNum = parseInt(linkNum,10) + 1; // always use a radix
https://jsfiddle.net/mblase75/s7ac8aq3/3/
However, I would instead prefer to solve the problem at its source, a few lines down:
if (nav == false) {
var otherButtons = paginationContainer.find('button');
linkNum = $(this).val();
When you store linkNum in the first place, .val() returns a string. Parse it as an integer right away:
linkNum = parseInt($(this).val(),10);
https://jsfiddle.net/mblase75/s7ac8aq3/4/
and then you don't have to change it before performing the addition.
Your problem in linkNum variable, when you click on certain page number, variable gets a string value, after that when you trying to add 1 you receive a new string, for example "3" + 1 => "31", "4" + 1 => "41"
The code below came as an included file with a beginner puzzle app tutorial I'm working through. The code works, however now that I've completed the tutorial, I'm trying to read through the files that came preloaded which were not explained.
I'm really tripped up over the "spacecount" variable, and what exactly it's doing. Can anyone comment each line in plain english, so that I can better understand how exactly the code below is populating the rowCount array. Thank you so much.
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i]="";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols-1) rowCount[i] += spaceCount + " ";
} else {
if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
Here's a slightly more legible version:
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i] = "";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols - 1) {
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
The confusing parts are probably the if blocks in the middle.
if (puzzle[i][j] == "#") { // If a puzzle piece is `#` (a space?)
spaceCount++; // Increment the spaceCount by 1.
if (j == totalCols - 1) { // Only if we are on the last column, add the text
// to the row.
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) { // If the current piece isn't a `#` but
// spaces have already been counted,
// add them to the row's text and reset `spaceCount`
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
From what I can tell, this code counts the number of consecutive pound signs and appends this text to each row.