Select unselect checkboxes using jquery - javascript

I have a list of checkboxes in my kendo grid.Select all option is also there.
Problem is When i click select all then all the checkboxes selected and then unselect some checkboxes and going to save then it shows me all the checkboxes.(un checked checkboxes also shown )
My Code
$('#itemGrid').on('change', '.usedchk', function () {
var checked = $(this).is(':checked');
var grid = $('#itemGrid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
var selected = $('#selected').val();
var id = dataItem.itemId;
if ($('#selected').val().indexOf(id) == -1) {
if ($('#selected').val() == '') {
$('#selected').val(id);
} else {
$('#selected').val(selected + "," + id );
}
}
});

use below code on save, to get all checked checkboxes as a comma separated string
var output = $.map($('#selected:checked'), function(n, i){
return n.value;
}).join(',');

Related

How do I filter the options in multiple selects based on the option selected in one select?

I have three select boxes on a page: Company, Vendor, Type. I have the following function that when I select a company, it will filter the vendor options to only show vendors for the company selected.
jQuery("#companySel").change(function() {
if (jQuery(this).data('options') == undefined) {
jQuery(this).data('options', jQuery('#vendorId option').clone());
}
var id = jQuery(this).val();
if (id === '') {
var options = "";
} else {
var options = jQuery(this).data('options').filter('[companyId=' + id + ']');
}
jQuery('#vendorId').html(options);
});
That function works great for the one select box. I can do a second one for the Type select box and it also works great:
jQuery("#companySel").change(function() {
if (jQuery(this).data('options') == undefined) {
jQuery(this).data('options', jQuery('#typeId option').clone());
}
var id = jQuery(this).val();
if (id === '') {
var options = "";
} else {
var options = jQuery(this).data('options').filter('[companyId=' + id + ']');
}
jQuery('#typeId').html(options);
});
What I can't figure out how to do is to combine them. I want to select a company and then it filter BOTH the vendors for that company and the types for that company.
When I try to combine them, it works the first time; however, the second time you change the company select box, it tries to filter the filtered list, not the original list prior to the filter.

Check if KendoGrid selected checkbox is checked or not

I have a ASP.Net MVC Kendo Grid with checkbox selection, as the documentation I added the checkbox using columns.Select().Width(50); as, then I want to fill an array of selected checkboxes inside of onChange function with javascript as:
Note: the stations array already have some values I.E [1,2,3], so I want to add new values in the next script
function onChange(e) {
const grid = $("#grid").data("kendoGrid");
var items = grid.items();
let ids = '';
grid.select().each(function() {
if (ids === '')
ids = grid.dataItem(this).StationId.toString();
else
ids = ids + ',' + grid.dataItem(this).StationId.toString();
stations.push(grid.dataItem(this).StationId);
})
}
The problem is on each check it is adding all existing checked checkboxes, I have no way to do something like if(checkbox is not checked) do a pop instead a push.
How can I check if clicked checkbox is checked or not in order to implement push or pop logic?
The select method will return all rows that are currently selected. If you need to figure out which is the checkbox that the user clicked last, you can probably toggle a class when the checkbox is checked/unchecked
function onChange(e) {
const grid = e.sender;
var items = grid.items();
let ids = '';
grid.select().each(function(idx,itm) {
$(itm).find("input").hasClass("checkedFlag") ?
kendoConsole.log(grid.dataItem(itm).ProductName + " was checked") :
kendoConsole.log(grid.dataItem(itm).ProductName + " was NOT checked");
})
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
kendoConsole.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
}
function onDataBound(arg) {
$("input.k-select-checkbox").change(function(){
$(this).toggleClass("checkedFlag")
})
kendoConsole.log("Grid data bound");
}
If you are interested in only the Id's of the selected items then the Grid exposes a selectedKeyNames method, that you could use instead.
The change event of the Kendo grid will fire when the user selects or deselects a table row or cell in the grid (documentation), but it does not provide us with which rows are selected or deselected.
What you will need to do is store the selected items outside of the grid, compare it to the results of the select method in the change event, then store the updated results.
Something along these lines:
var selectedRecords = [];
function onChange(e) {
var updatedSelectedRecords = e.sender.select();
if (selectedRecords) {
var recordsSelected = updatedSelectedRecords.filter(record => !selectedRecords.includes(record)).map(record => record.StationId.toString());
stations.push(...recordsSelected);
var recordsDeselected = selectedRecords.filter(record => !updatedSelectedRecords.includes(record));
// do something with deselected records?
}
selectedRecords = updatedSelectedRecords;
}

Change selected text of a dropdown without changing the text in the option?

How to change the selected text of the dropdown without changing the text in the option? For ex: if dropdown has code and description both but on select i only wants to display the code and remove the description but description should be present in the dropdown.
Populating data in the dropdown:
$.each(jtc12_2_2_reasoncode1List, function(i, item) {
$('#jtc12_2_reasonForFailure1').append($('<option>', {
value : item.Code,
text : item.Code + " " + item.Description
}));
});
Change the text of selected option:
var jtc12_2_2_reasonCode1Code = $("#jtc12_2_reasonForFailure1 :selected").val();
var jtc12_2_2_reasonCode1Desc = _.filter(e.data.jtc12_2_2_reasonCode1List, function(item) {
return item.Code === jtc12_2_2_reasonCode1Code;
});
jtc12_2_2_reasonCode1Desc = jtc12_2_2_reasonCode1Desc[0].Description;
$("#jtc12_2_reasonForFailure1 option[value = " + jtc12_2_2_reasonCode1Code + "]").text(jtc12_2_2_reasonCode1Code);
One way to achieve this is to add a new option at runtime and select that (the newly added) value instead of the selected value. Then the selected value can be removed on dropdown's click event.
Assuming the code and description are separated by a colon (:) refer the following code.
var onSelect = false;
$('select').click(function (e) {
if ($(this).val() !== '' && !onSelect) {
$(this).find('option:selected').remove();
} else {
onSelect = false;
}
});
$('select').change(function (e) {
var selectedVal = $(this).val();
var newVal = selectedVal.split(':')[0];
$(this).append($('<option>', {
value: newVal,
text: newVal
}));
$(this).val(newVal);
$(this).find('option:selected').hide();
onSelect = true;
});
jsFiddle

reset values of not selected fields of dropdown

I have a dropbox that when selected it displays its respective fields
in first image you can see there is A person without an ID so when selected it displays
something like:
if you see I added 12
Now if i change my mind and select the other option (person with ID) one field is displayed like:
I added 9999
That is ok, but now if I change my mind again and return to other selected option the values are still there like:
I would like to clean them... How can I accomplish that?
It does not matter to fill all respective fields again, I want to reset values in that case if select
person without ID, delete the 9999, on the other hand, if i select person with Id, i want to reset the vakue 12
please take a look at my fiddle
some of the jquery code is:
//function available
function validate(id, msg) {
var obj = $('#' + id);
if(obj.val() == '0' || obj.val() == ''){
$("#" + id + "_field_box .form-error").html(msg)
return true;
}
return false;
}
$(function () {
$('#has_id').show();
$('#select_person').change(function () {
$('.persons').hide();
if ($('#select_person').val() == 'typeA') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type A--').appendTo("#has_id");
$("<option/>").val('person-A-withID').text('person-A-withID').appendTo("#has_id");
$("<option/>").val('person-A-withoutID').text('person-A-withoutID').appendTo("#has_id");
}
if ($('#select_person').val() == 'typeB') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type B--').appendTo("#has_id");
$("<option/>").val('person-B-withID').text('person-B-withID').appendTo("#has_id");
$("<option/>").val('person-B-withoutID').text('person-B-withoutID').appendTo("#has_id");
}
});
$('#has_id').change(function () {
$('.persons').hide();
$('#' + $(this).val()).show();
});
});
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
err += validate('has_id', "Select whether it has an ID or not.");
if(err == 0){
alert('continue');
}else{
alert('error');
}
};
Simply make this change:
$('#has_id').change(function () {
$('.persons input').val('');
$('.persons').hide();
$('#' + $(this).val()).show();
});
New fiddle: http://jsfiddle.net/6m27M/
This simply clears out all the values any time a change is made to the #has_id dropdown.

Append option values to a hidden field?

With the push of a button, I'm iterating through a list of options in a select. I wish to append all of these option (values of the options) to a hidden fields, separated by a pipe |. So far I've come up with this, however, It just puts the last value of the option in the select in the hidden field?
//Select all cities
$jq("input#checkcities").click(function () {
$jq(".select-cities > option").each(function () {
var zipCodeValue = $jq(this).val();
$jq(".select-cities option").attr("selected", "selected");
$jq(".select-cities option").appendTo(".chosen-cities");
//Put value of cities in hidden field.
$jq('.hiddenFieldChosenCities').val(zipCodeValue);
});
});
You can use map method:
var zipCodeValues = $jq(".select-cities > option").map(function () {
return this.value;
}).get().join('|');
$jq('.hiddenFieldChosenCities').val(zipCodeValues);
Try like this
$jq('.hiddenFieldChosenCities').val($jq('.hiddenFieldChosenCities').val() + '|' + zipCodeValue);
You need to add the value:
$jq('.hiddenFieldChosenCities').val($jq('.hiddenFieldChosenCities').val() + '|' + zipCodeValue);
Create the string zipvalues
Loop over the cities and append cities to zipvalues
Finally set the hidden field value to zipvalues.
// Select all cities
$jq("input#checkcities").click(function () {
var zipvalues = "";
$jq(".select-cities > option").each(function () {
var zipCodeValue = $jq(this).val();
$jq(".select-cities option").attr("selected", "selected");
$jq(".select-cities option").appendTo(".chosen-cities");
zipvalues += "|" + zipCodeValue;
});
//Put value of cities in hidden field.
$jq('.hiddenFieldChosenCities').val(zipvalues);
});

Categories

Resources