Limit Selected Divs to 5? - javascript

i'm currently selecting divs using this:
$(".gridbox").click(function () {
$(this).toggleClass("selected");
var isSelected = $(".gridbox.selected").length > 0;
$("#button").toggle(isSelected);
});
});
Is there any way I can limit the number of selected Divs to 5? I have tried:
var isSelected1 = $(".gridbox.selected").length < 3;
if (typeof isSelected1 !== 'undefined') {
alert("You have selected the maximum amount.");
}
But that doesn't seem to work. If anyone has any ideas that'd be greatly appreciated!
Also I am presently selecting divs using:
<div onclick="clicked(this);" class="gridbox" id="1"></div>
Is there anything I can put anywhere to disable a certain ID from being selected?
Many thanks in advance!
Cheers

This seems to achieve what you are looking for:
jsFiddle example
$(".gridbox:not(#disabled)").click(function () {
if ($('.selected').length < 5 || $(this).hasClass('selected')) {
$(this).toggleClass("selected");
}
});
It will limit the selection to 5 of any elements with class .gridbox. Not just the first 5 elements.
With usage of :not, you are unable to select an element with an id of "disabled" in this example.

Related

jQuery search for nearest number

I'm creating a form where you can choose between different sizes of paper, everything working well and I've made a search form in jQuery that looks in the text() of a div to find matching formats. In example: there's a size 105 x 148 and if I type "105" in #searchformat it hide()s all other divs without "105".
$('#searchformat').keyup(function() {
$('.awspc-image-selection-box').hide();
$('.awspc-image-selection-box-content .awspc-image-selection-box-content-label').each(function() {
if($(this).text().toLowerCase().replace(/\s/g, '').indexOf(""+text+"") != -1 ) {
$(this).closest('.awspc-image-selection-box').show();
}
});
});
This works great. There's just one thing I can't seem to get working, I want to have the ability if you type in the input field for example "104" that it will also show the divs with "105" in it. With a margin of +- 5.
The field where I need to search in is $('.awspc-image-selection-box-content-label').text() and I already tried it with a function having return Math.round(x.match(/\d+/) / text) * text; but this looks for the nearest number and the problem here also is that the value of the field is like this: <div class="awspc-image-selection-box-content-label"> 38.1 x 8 mm </div>
HTML:
<div class="awspc-image-selection-box" data-value="7" data-id="aws_price_calc_45" data-substrate="">
<div class="awspc-image-selection-box-content">
<img style="width: ; height: " src="/uploads/woocommerce-placeholder-768x768.png" alt="170">
<div class="awspc-image-selection-box-content-label">38.1 x 8 mm</div>
</div>
</div>
So how can I in example search for "39" and it will show me the div having "38"?
Thanks a lot!
UPDATE
I figured some working code out but the only problem now is how I can retrieve what the closest() div is from the result...
var tooSearchFor = $('.awspc-image-selection-box-content-label').text();
tooSearchFor = tooSearchFor.split('\n');
for(var i = 0; i < tooSearchFor.length; i++)
tooSearchFor[i] = parseInt(tooSearchFor[i]) || 0;
var goalFormat = textInputSearch;
var closestFormat = null;
$.each(tooSearchFor, function(){
if (closestFormat == null || Math.abs(this - goalFormat) < Math.abs(closestFormat - goalFormat)) {
closestFormat = this;
}
});
console.log ('Closest format:' + closestFormat); // outputs the closest found number
How can I retrieve the div where closestFormat is found in the array...?

Append div inside of td and set the value?

I have multiple tables that I need to populate. I use jQuery to loop through table cells. If table cell has data-text attribute I need to append div element. Div element will allow cell to have scroll bar vertical. This way table won't expend if text is too long.
Here is example of my code:
$('#'+tabID+' table tr td').each(function(){
elementID = $(this).prop('id').toUpperCase();
value = $.trim(decodeURIComponent(obj.DATA[elementID]['value']));
if($(this).attr('data-text')) {
$(this).append('<div class="hm_textScroll">'+value+'</div>');
} else {
$(this).text(value).css({'color':'blue','font-weight':'bold'});
}
});
Code above will append div element and set the value but the problem is that if I move to a different table and come back again one more div will append. That creates duplicate. I'm not sure what is the best way to prevent that? Or if there is a better way to work around this. If anyone have suggestions please let me know.
Thanks in advance.
Here you go with a solution
$('#' + tabID + ' table tr').each(function(){
$(this).find('td').each(function(){
elementID = $(this).prop('id').toUpperCase();
value = $.trim(decodeURIComponent(obj.DATA[elementID]['value']));
if(typeof $(this).attr('data-text') != 'undefined') {
if($(this).find('div.hm_textScroll').length > 0){
$(this).find('div.hm_textScroll').text(value);
} else {
$(this).append(`<div class="hm_textScroll">${value}</div>`);
}
} else {
$(this).text(value).css({'color':'blue','font-weight':'bold'});
}
});
});
First loop through each tr then loop through each td.
For check the data-attribute, use typeof $(this).attr('data-text') != 'undefined
In the if statement (true condition) I've used backtick ES6 for appending div container.
Hope this will help you.
If I understand you correctly, you would have to additionally check whether a <div class="hm_textScroll"></div> already exists in the <td>.
One possible solution using vanilla javascript would be this:
const tableElement = document.querySelectorAll('#'+tabID+'table tr td');
tableElement.forEach(td => {
if (td.hasAttribute("data-text")) {
if (!td.querySelector(".hm_textScroll")) {
td.innerHTML='<divclass="hm_textScroll">'+value+'</div>'
}
}
});

How to concatenate variables with selectors?

I'm having problems with this code: https://jsfiddle.net/vitordhers/fm8a14x6/2/
I intend to make subcategories appear if at least one check-box is checked, however when I uncheck the check-boxes, the subcategories don't disappear, since they share the same class with those from the other category.
In order to apply the code to one paragraph only, I tried to concatenate the $this selector with :checked selector, but it doesn't seem to work:
$( "p" ).click(function() {
var $line = $('.l' + $(this).data('value'));
var n = $( $this+"input:checked" ).length;
alert(n);
if(n == 0){
$($line).hide(); //if there are none checked, hide visible elements
} else {
$($line).show(); //otherwise (some are selected) fadeIn - if the div is hidden.
}
});
Could anybody help me in this case? Thanks in advance
$("input:checked", this)
did the trick.

jQuery - check if selected row is last visible row in table

previously i checked whether a row is last row in a table like this in a condition:
$row.is(':last-child')
which works fine.
Now, i have a requirement where some of the rows in the table are hidden - now i have to check whether a specific row is the last visible row in the table.
I tried with this:
$row.is(':visible:last-child')
but not that successfull. Does someone have a clue?
This doesn't work because the last-child is display: none;.
One approach is to iterate the childs to find the index of the last visible child (see fiddle) :
var $rows = $('td');
var $rowsReverse = $($rows.get().reverse());
var $lastVisibleIndex = -1;
$rowsReverse.each(function(index) {
if ($lastVisibleIndex == -1 && $(this).is(':visible')) {
$lastVisibleIndex = $rowsReverse.length - index - 1;
}
});
$rows.each(function(index) {
var $row = $(this);
if (index == $lastVisibleIndex) {
$row.addClass('red');
}
});​
Thanx everybody for the quick feedback. I could solve it with the following:
$row.parent().find('tr:visible').last().attr('data-id') is $row.attr('data-id')
(it's in a loop)
#falsarella your answer i guess works fine - is a bit complicated, but it works apparently.
You could try
$(element).is(":visible").last();
or
$(element:visible).last();
If that doesn't work, let me know.

Prevent checkbox tick after Nth selection (allow more from the same category)

We have checkboxes in two columns (they denote the same category, but different subscription)
We would like to limit the selection to 4. We have a jQuery code to disable the checkbox selection after the user selected 4.
But now we need to have the following logic:
Allow the user to choose both values from the same rows (aka: subscribe to both subscriptions from the same category) and do not count in the 4 limit we have if they have chosen more from the same row.
So if you look in the following screencast, we would like to be able to select the first checkbox (1st row).
The code we used was:
$("input:checkbox").click(function() {
var bol = $("input:checkbox:checked").length >= 4;
$("input:checkbox").not(":checked").attr("disabled",bol);
});
A jsFiddle has been created to reflect the current state of work:
http://jsfiddle.net/fFbLx/
Feel free to name the classes, inputs as you wish.
I think you would have to "categorise" them by the LI then. So count the LI's with an checked box - disable all others if more than 4 active.
See: http://jsfiddle.net/fFbLx/4/ (maybe give the UL's a class, so you can use the selector on that)
$("input:checkbox").click(function() {
var counter = 0;
$('li').each( function() {
if($(this).find("input:checkbox:checked").length)
{
$(this).addClass('active');
counter++;
} else {
$(this).removeClass('active');
}
});
var bol = counter >= 4;
$('li').not('.active').find("input:checkbox").not(":checked").attr("disabled",bol);
});
If you wrap your checkboxes in an element you can then use the jquery has selector filter to check how many have selected checkboxes:
$("input:checkbox").click(function() {
var bol = $(".myCheckboxWrapper:has(input:checkbox:checked)").length >= 4;
$("input:checkbox").not(":checked").attr("disabled",bol);
});
Try this http://jsfiddle.net/fFbLx/2/
$("input:checkbox").click(function() {
$(this).parent().find("input:checkbox:first").toggleClass("active");
var bol = $("input:checkbox:checked").length >= 4;
$("input:checkbox").not(":checked,.active").attr("disabled",bol);
});

Categories

Resources