I'm having troubles with setting default category to this script. I want by default to be listed only Category 1 with one news in it insead of All but nothing I tried seem to work. Any ideas?
This is the full code with HTML and some CSS: https://codepen.io/NickyCDK/pen/lhaiz
//Filter News
$('select#sort-news').change(function() {
var filter = $(this).val()
filterList(filter);
});
//News filter function
function filterList(value) {
var list = $(".news-list .news-item");
$(list).fadeOut("fast");
if (value == "All") {
$(".news-list").find("article").each(function (i) {
$(this).delay(200).slideDown("fast");
});
} else {
//Notice this *=" <- This means that if the data-category contains multiple options, it will find them
//Ex: data-category="Cat1, Cat2"
$(".news-list").find("article[data-category*=" + value + "]").each(function (i) {
$(this).delay(200).slideDown("fast");
});
}
}
You could use a trigger
$('select#sort-news').trigger(filterList('Cat1'), 'click');
Related
I am using the below code to render the same as many as times,
I have two sections, one section with show-all class and another with no class.
When 'show-all' class is not available, it need to run countIncrease function, if class available no need to run the function,
In every time section need to check whether the class is available or not.
class Grid {
init() {
$('.grid').each(function() {
const $this = $(this);
// getting values & url from from html
const dropDownUrlpath = $this.find('.grid__dropdown-select').attr('data-ajaxurl');
const hasClass = $this.find('.grid').hasClass('grid_showall');
// countIncrease shows the inital 6 compoents/div and rest of will be hidden
// onclick it will display 3 components/div
function countIncrease() {
let limit = parseInt($this.find('.grid__component').attr('data-initcount'), 10);
const incrementalCall = parseInt($this.find('.grid__component').attr('data-incrementalcount'), 10);
$this.find(`.grid__content > .grid__component:gt(' ${limit - 1} ') `).hide();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
else {
$this.find('.grid__cta').show();
}
$this.find('.grid__cta').on('click', function(event) {
event.preventDefault();
limit += incrementalCall;
$this.find(`.grid__content > .grid__component:lt(' ${limit} ')`).show();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
});
}
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
// on dropdown change taking the selected dropdown value and adding #end of the url and replacing the previous html
$this.find('.grid__dropdown-select').on('change', function() {
const optionValue = this.value;
$.ajax({
url: dropDownUrlpath + optionValue,
success(result) {
$this.find('.grid__content').html(result);
countIncrease();
}
});
});
});
}
}
I written if condition, but it running once and giving false condition in both the scenarios,
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
How to handle it...?
shouldnt you add a parameter to the .hasClass so it knows what to check?
if ( $this.hasClass ('some class') === true ) {
alert('something');
}
or set if(hasClass.length > 0){}
keep the checking class in a variable by finding with parent div,
const hasClass = $this.find('.grid').hasClass('grid_showall');
gets the attribute value for only the first element in the matched set with .attr() method
const classInthis = hasClass.attr('class');
check the condition, with
if (classInthis !== 'grid_showall') {
countIncrease();
}
I have a multiselect with many options. When 'everybody' is selected it removes other selected, if other are selected and the 'everybody' is selected it should remove it.
To remove the other and keep the item 'everybody' it's ok. But I have problem to keep other and only remove everybody.
For the moment I have something like :
resetGroupSelectionWhenEverybody: function() {
$(".group_ids").on("select2:select", function (e){
if (e.params.data.text === 'everybody') {
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
} else {
if ($('[title="everybody"]').length > 0) {
var idToRemove = 0;
groupIdsData = $('#scheduled_publication_groups_ids').select2('data');
groupIdsData.forEach(function(e, i) {
if (e.text === 'everybody') {
idToRemove = i;
}
});
groupIdsData.splice(idToRemove, 1);
$('#scheduled_publication_groups_ids').select2({'data': groupIdsData}).trigger("change");
}
}
});
},
With this code groupIdsData is tonly the selected elements I want (all expect everybody's group). But after I'm stuck to change the view. select2({'data': groupIdsData}) doesn't seems to be the right choice.
Few things :
I don't think I'm setting the idToRemove properly
What the best way to update the value of the select2 multiselect? It seems it can be a hash
The answer is to use select2('val') to get a array of ids, and then work with this. Code is better using .val() not full select2 objects.
resetGroupSelectionWhenEverybody: function() {
$(".group_ids").on("select2:select", function (e){
if (e.params.data.text === 'everybody') {
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
} else {
if ($('[title="everybody"]').length > 0) {
groupIds = $('#scheduled_publication_groups_ids').select2('val');
groupToKeep = groupIds.splice( $.inArray(group_everybody_id, groupIds), 1);
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(groupToKeep).trigger("change");
}
}
});
},
I've created an auto-complete Textbox, and a div under it.
When the client select an item from the Textbox, it automaticly appears in the div, after styling with CSS.
What I want to do now is to create an event, that when the client clicks on the styled selected items, they will disappear.
here is the JS code, and jsfiddle under it, for your comfort.
`$(function() {
/* Textbox ID */ $("#destinations").autocomplete({
select: function (event, ui) {
/* div ID */ $("#DestinationsChosen").html(function(i, origText)
{
var SelectedCountry = ui.item.value.toString();
var CurrentText = origText.toString();
if ((CurrentText.indexOf(SelectedCountry) >= 0))
{
alert("Already Exists");
return CurrentText;
}
return CurrentText + " <span class='toButton'>" + SelectedCountry + "</span>";
})
}
http://jsfiddle.net/dgu1ncsj/
thanks :)
Idan
Simplest solution for this existing code is to add the line:
$('.toButton').click(function(){$(this).remove(); });
Just after the $("#DestinationsChosen").html(...) block.
I don't recommend putting script in the tag itself because it's not a good habit, since it doesn't separate concerns. But my short answer has problems too, since it is getting all .toButtons each time and setting the listener again.
The better way to do this, is to create the toButton as a DOM node, and append it to the parent div. This way, you can put the listener on the node itself.
$(function() {
$("#destinations").autocomplete({
select: function (event, ui) {
$("#DestinationsChosen").append(function(i, origText){
var SelectedCountry = ui.item.value.toString();
var CurrentText = origText.toString();
if ((CurrentText.indexOf(SelectedCountry) >= 0))
{
alert("Already Exists");
}
var destination = document.createElement('span');
destination.classList.add('toButton');
destination.appendChild( document.createTextNode(SelectedCountry));
destination.addEventListener('click', function(){ this.remove(); });
return destination;
})
}
});
})
You could simply add an onclick event to each selected item. I have modified your code a bit. See the working code segment below:
$(function() {
$("#destinations").autocomplete({
select: function (event, ui) {
$("#DestinationsChosen").html(function(i, origText)
{
var SelectedCountry = ui.item.value.toString();
var CurrentText = origText.toString();
if ((CurrentText.indexOf(SelectedCountry) >= 0))
{
alert("Already Exists");
return CurrentText;
}
return CurrentText + " <span class='toButton' onclick='$(this).remove();'>" + SelectedCountry + "</span>";
})
}
});
})
In my limited understanding of jQuery, I don't understand what is happening here.
I have two divs, each with a class of "required". The 1st div contains a set of checkboxes, while the second contains radio buttons. The object is to highlight the appropriate div background if no objects in either set are selected.
The 2nd set, however (the radio buttons), does have a button pre-selected by default, so should never be highlighted.
Here is what is happening:
Both sets are being looped through twice. At the end of the 1st div (checkbox) loop, the div is correctly highlighted. The radio button items are them checked and the default checked button is recognized and that div is not highlighted. Then, the first div items are again gone through. At the end of this - and BEFORE the 2nd div is looped through for the second time, the 2nd div is highlighted. I am assuming that the cause here, even though it is correctly looping through the checkboxes, it is associating them with the id of the radiobuttons. What I need to do is prevent this second loop-through.
$(document).ready(function () {
$('#Submit').click(function () {
$('div.Required', '#JobForm').each(function () {
var FieldName = this.id;
var FieldLength = FieldName.length
var CheckError = true;
$("input:checkbox").each(function () {
if (this.checked) {
CheckError = false;
}
});
if (CheckError) {
ErrorList += FieldName + ' requires a selection\n';
this.style.backgroundColor = "#FFC0C0";
}
CheckError = true;
$("input:radio").each(function () {
if (this.checked) {
CheckError = false;
}
});
if (CheckError) {
ErrorList += FieldName + ' requires a selection\n';
this.style.backgroundColor = "#FFC0C0";
}
});
if (Error) {
$('#Submit').val('Submit');
alert(ErrorList)
return false;
} else {
document.JobForm.submit();
}
});
});
Thanks to adeneo's suggestions, I was able to limit the double div looping, which also allowed me to eliminate the additional error message. As adeneo stated, since there are two div's, as originally written, the code was looping through both input types each time.
As written below, the first loop loops through the checkboxes, while the second loops through the radio buttons.
$(document).ready(function()
{
$('#Submit').click(function ()
{
$('div.Required','#JobForm').each(function()
{
var FieldName = this.id;
var FieldLength = FieldName.length
var CheckError = true;
$("input:checkbox", this).each(function ()
{
if(this.checked){CheckError=false;}
});
$("input:radio", this).each(function ()
{
if(this.checked){CheckError=false;}
});
if(CheckError){ErrorList += FieldName+' requires a selection\n'; this.style.backgroundColor="#FFC0C0";}
});
if(Error)
{
$('#Submit').val('Submit');
alert(ErrorList)
return false;
}
else
{
document.JobForm.submit();
}
});
});
You're not iterating over each DIV twice, but you're iterating over all the inputs the same number of times as you have matching DIV's
$('#Submit').click(function () {
// loop over the DIV's, lets say two times if there are two elements
$('div.Required', '#JobForm').each(function () {
// ..... other code
// the code below selects all the checkboxes, both times
$("input:checkbox").each(function () {
if (this.checked) {
CheckError = false;
}
});
// the code below selects all the radiobuttons, both times
$("input:radio").each(function () {
if (this.checked) {
CheckError = false;
}
});
// .......more code
});
});
Limit the selection of inputs with context or find()
$("input:checkbox", this).each(function () { ...
or
$(this).find("input:checkbox").each(function () { ...
also, your conditions don't make sense, you keep setting CheckError to a boolean, and on the next line you're checking for that boolean, and you'll never get a different result
CheckError = true;
if (CheckError) { ...
is like doing
if (true) { ...
I'm trying to search multiple data results based on inline data attributes.
However, I can only figure out how to search a single data attribute instead of them all.
How would I accomplish this?
What I have: http://jsfiddle.net/9SMZC/2/
$("input[type=text]").keyup(function () {
var filter = $(this).val();
$("a").each(function () {
if ($(this).attr("data-event-name").search(new RegExp(filter, "i")) < 0) {
$(this).hide();
} else {
$(this).show();
matches++;
}
});
});
Thanks in Advance!
If you want to apply a "or" logic, you may do this :
$("input[type=text]").keyup(function () {
var filter = $(this).val();
$("a").each(function () {
var data = $(this).data();
$(this).hide();
for (var key in data) {
if (~data[key].search(new RegExp(filter, "i"))) {
$(this).show();
break;
}
}
});
});
Demonstration (try to search "andrew" for example)
The idea is to get the data object and iterate over the properties. To simplify the code (that is to avoid keeping a boolean) I also always hide and show when the element is ok.