kendo ui grid: Compare data in multiple selected rows? - javascript

Ok, rephrasing the question here, it seems the articulation was lacking.
I have a kendo ui grid, and when I make multiple selections (2 or more at a time) of rows, I need to compare values of a specific column in all the selected rows to determine if they are exactly equal(same) or not. Here's is my kendo 'change: ' function, the dataItem in question we'll call 'fancyNumber':
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
selectedDataItems.push(dataItem);
}
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
function allValuesSame() {
for (var i = 1; i < selectedRows.length; i++)
{
if(this[i] != this[0])
return false;
}
return true;
}
if (selected.length > 1){
var selectedRows = $("#myTable").data("kendoGrid").select();
var fancyNumberText = this.dataItem(this.select()).fancyNumber
if (allValuesSame(fancyNumberText) === true) {
alert(fancyNumberText); //just testing to see what I get
}
return allValuesSame(fancyNumberText);
}
if (selected.length == 0) {
$('#fancyButton').attr('disabled', 'disabled');
} else if (selected.length == 1) {
$('#fancyButton').attr('disabled', false);
} else if (selected.length > 1 && allValuesSame == true) {
$('#fancyButton').attr('disabled', false);
}
},
Clearly, this isn't correct; how do I do this?

You can use the .dataSource property to get the model that your grid is bound to and make the comparison there.
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#fields-dataSource
Say your grid has an Id of myDataGrid, you would use:
var gridModel = $("#myDataGrid").data("kendoGrid").dataSource.data();
// Sample comparison
if (gridModel[3].someField === gridModel[5].someField) {
// Do something with your buttons
}

You need to set up the grid with the following...
.Selectable(sel => sel.Mode(GridSelectionMode.Multiple))
.Events(e => e.Change("onChange"))
Once you have these in place, you can select individual lines and you have an event which is called on selection onChange
In your script, wire up this funciton...
function onChange() {
//you can get the selected row like this
var selected = $.map(this.select(), function(item) {
return item.getAttribute('data-uid');
});
//if selected count > 1 then check logic and enable/disable button
EnableDisableButton(true, "#myButton");//assuming condition was good
}
You need to set up the onChange to record the rows values from each selection, maybe using an array and then comparing the values in the array.
function EnableDisableButton(isToBeEnabled, buttonName) {
if (isToBeEnabled)
$(buttonName).removeAttr("disabled").removeClass("k-state-disabled");
else
$(buttonName).prop("disabled", true).addClass("k-state-disabled");
}

Related

Validation to prevent duplicated values on input text

Im trying to prevent duplicated values on inputs with same name when I click a submit button, but it is not working and i am not sure why...
I need some help to understand why is not working?
Thanks lot in advance!
this is my code:
I tried with a solution I found here which it worked "on input change" behavior, but it doesnt with button click...
My button:
<button type="button" id="approve" class="positive valid" tabindex="-1">Approve</button>
and my jquery
$('#received').on('click',function() {
var $current = $(this);
if ($('input[name^="RE_SignedByID"]').val() == $current.val() && $('input[name^="RE_SignedByID"]').attr('tabindex') !== $current.attr('tabindex') ) {
alert('You can not have duplicated ID´s');
return false;
}else {
return true;
}
});
I want to show an alert and prevent the submit.
Thanks a lot for any help!
The issue is because you're comparing the value of the clicked button to the first input[name^="RE_SignedByID"] element.
To fix this you could instead create an array of all the input[name^="RE_SignedByID"] values using map(). You can then dedupe this list and compare the resulting array lengths. If they are different there was a duplicate. Try this:
$('#received').on('click', function(e) {
var values = $('input[name^="RE_SignedByID"]').map(function() {
return this.value.trim();
}).get();
var unique = [...new Set(values)];
if (values.length != unique.length) {
e.preventDefault();
alert('You can not have duplicated ID\'s');
}
});
Note that [...new Set(values)] will not work in IE. If you need to support legacy browsers there are plenty of alternatives to dedupe an array. See this answer for more information.
I could fix it! Here is the code... you can add a button event like:
$('#submit').on('click', function () {
var values = $('[name=RE_SignedByID]').map(function() {
return this.value.trim();
}).get();
var values2= $('[name=RE_OwnersID]').map(function() {
return this.value.trim();
}).get();
values.sort();
values2.sort();
for (var i = 0; i < values.length-1; i++) {
if( values[i] == values[i+1] && values[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated signers ID\'s'));
return false;
// break;
}
}
for (var i = 0; i < values2.length-1; i++) {
if( values2[i] == values2[i+1] && values2[i] !=""){
showAlert(translator.getTranslation(' You can not have duplicated owners ID\'s'));
return false;
// break;
}
}
});

on option select, show/hide table row and sort

This block of code verify if all of codes is checked. I am looking for a way to check if at least one of the codes is checked, instead.
function containsAny(needles, haystack){
for(var i = 0 , len = needles.length; i < len; i++){
if($.inArray(needles[i], haystack) == -1) return true;
}
return false;
}
I have a full working example here: http://jsfiddle.net/v7wt5eop/
How to see this behavior:
In the selectbox click Deselect All
Check A
Line 2 and 3 of the table should be unfaded because A is one of the codes
And the rows that are with the class row-disabled should be at the end of the table. I am using Bootstrap Sortable, but couldn't figure out how to do it. So everytime I click in an option in the selectbox it should re-order the table.
Your function containsAny should be
function containsAny(needles, haystack){
for(var i = 0 , len = needles.length; i < len; i++){
if($.inArray(needles[i], haystack) != -1) return false;
}
return true;
}
To sort every time you check/uncheck
$('.selectpicker').on('change', function() {
var list = [];
$('.selectpicker :selected').each(function(i, selected) {
//Removed the irrelevant codes
});
$('.CodeCheck').each(function() {
//Removed the irrelevant codes
});
el = $(".table tbody tr.row-disabled:first-child");
$(".table tbody tr").not(".row-disabled").each(function() {
$(this).insertBefore(el);
});
});

Button is being disabled due to hidden select elements

I have a form with three select options:
Fit
Colour
Size
By default, the 'Fit' dropdown and 'Colour' dropdown are active with a default value selected (e.g. Regular Fit and Blue Colour).
There are three different 'Size' dropdowns, but only one is visible at any time depending on what is selected from the 'Fit' dropdown.
The Button is disabled if an option value="none".
Problem
The Button only becomes active if all three 'Size' dropdowns are altered so that their value is not "none" (this is done by selecting an initial size for Regular, and then selecting Petite and Long from the 'Fit' dropdown). Ideally, I only want the button to take into account the 'Size' dropdown that is active.
Update
Working jsFiddle solution provided by #nagappan below, big thanks.
https://jsfiddle.net/dodgers76/c0dvdwbz/
var currentSelectedVals = {'selector-fit':'','selector-color':'','selector-sizes':''};
var disableComboVals = [
{'selector-fit':'','selector-color':'','selector-sizes':'none'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'10'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'20'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'22'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'24'},
{'selector-fit':'long','selector-color':'','selector-sizes':'22'},
{'selector-fit':'long','selector-color':'','selector-sizes':'24'}
];
function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
cnt = 0;
$.each(vals, function(key,val) {
console.log('comparing key val '+key+val);
if (val === '' || val === currentSelectedVals[key]) {
console.log('>>matched values');
cnt = cnt + 1;
}
});
if (cnt===3) {
return true;
}
return false;
});
};
$(function(){
var sizeVal = 'none';
$("select.selector-fit").on("change", function(){
//remove active
$("select.selector-sizes.active").removeClass("active");
//check if select class exists. If it does then show it
var subList = $("select.selector-sizes."+$(this).val());
if (subList.length){
//class exists. Show it by adding active class to it
subList.addClass("active");
subList.val(sizeVal);
}
});
$('.selector-sizes').on('change', function() {
sizeVal = $(this).val();
});
});
$(function() {
$('.selector').on('change', function() {
var $sels = $('option.selector-sizes:selected[value="none"]');
var isSizeSelector = jQuery.inArray( "selector-sizes",this.classList);
currentSelectedVals[this.classList[1]] = this.value;
console.log(currentSelectedVals);
var result = checkDisableCombo();
console.log(result);
if ( result.length > 0) {
console.log('disabled false');
$("#Testing").attr("disabled", true);
} else {
$("#Testing").attr("disabled", false);
}
}).change();
});
If we want to disable the button by combination of the drop down selected values. We can have a global variable to track the current selected values from three drop downs. Only we can have array of disbale combos. So whenever user select a value we cross check with disable combos and if it matches we can disable the button. Validate the combo can be done as below. Updated the jsfiddle link. JS FIDDLE UPDATED
function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
cnt = 0;
$.each(vals, function(key,val) {
console.log('comparing key val '+key+val);
if (val === '' || val === currentSelectedVals[key]) {
console.log('>>matched values');
cnt = cnt + 1;
}
});
if (cnt===3) {
return true;
}
return false;
});

Reset button for JQuery table row filter

I have a table on my page, and a filtering text box above it that works fantastic, using the following JQuery:
$("#searchInputCompanies").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#cBody").find("tr");
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.text().toLowerCase().indexOf(data[d].toLowerCase()) > -1) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
$('#selectAllCompanies').prop('checked', '');
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
How can I set up a Reset Filter button for this?
Uhh, this is quite a bad implementation :(
First, you need to change the event for $("#searchInputCompanies") to make it all a bit easier. So, it will become $("#searchInputCompanies").on("input", function() {...
$("#resetAction").on("whatEventYouWant", function() {
$("#searchInputCompanies").val("").trigger("input");
});
This will trigger input event on $("#searchInputCompanies") and because the text box is empty all rows will become visible.

Return through all functions

Is it possible to return through multiple functions?
I have a jQuery on click function with a $.each loop in it. In the $.each loop I test for various conditions, and if not met display an alert message and then return. Here is a cut down version of my code:
$(document).on('click', '.add-to-basket, #add-to-basket', function(e) {
var data = {
id: $(this).data('id'),
quantity: 1
};
if($('#quant').length > 0) {
data.quantity = $('#quant').val();
}
var i = 0;
var j = 0;
if($('.product-option').length > 0) {
$('.product-option').each(function(index, element) {
if($(this).is('select')) {
//check to see if this is a required select, and return if a selection has not been made.
if($(this).data("force") == 1 && $(this).val() == 0) {
AlertDialogue($(this).data("title") + " requires a selection before you can add this product to your basket.", "Required Option");
return;
}
data.opts[i++] = $(this).val();
} else if($(this).is('input[type="checkbox"]:checked')) {
data.opts[i++] = $(this).val();
//check to see if this is a required group of checkboxes, and if so at least one has been checked. If not return.
} else if($(this).is('input[type="checkbox"]')) {
if($(this).data("force") == 1 && $('input[name="' + $(this).prop("name") + '"]:checked').length == 0) {
AlertDialogue($(this).data("title") + " requires at least one option to be checked before you can add this product to your basket.", "Required Option");
return;
}
} else if($(this).is('input[type="radio"]:checked')) {
data.opts[i++] = $(this).val();
} else if($(this).is('textarea')) {
//Check to see if this is a required textarea, and if so make sure there is some text in it.
if($(this).data("force") == 1 && $.trim($(this).val()).length == 0) {
AlertDialogue($(this).data("title") + " requires text before you can add this product to your basket.", "Required Option");
return;
}
if($(this).val().length > 0) {
data.text[j].id = $(this).data("id");
data.text[j++].val = $(this).val();
}
}
});
}
//submit product to the cart
});
However the return will only break that loop of the $.each loop, and start the next loop. I would like to not only break the $.each loop, but return from the on click function entirely.
Is this possible?
If so, how can I achieve this?
To exit from $.each you should return false
To exit from event handler function you should use return
As per your requirement you can do little like below,
var break = false;
$('.product-option').each(function(index, element) {
// rest of code
if(condition) {
break = true;
return false; // this will break out of each loop
}
});
if(break) {
return; // return from event handler if break == true;
}
// rest of code
Check out the docs for jQuery.each():
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same
as a continue statement in a for loop; it will skip immediately to
the next iteration.
Essentially, use return false; instead of just return;.

Categories

Resources