How to set value kendo multiselect? - javascript

My scenario is I want to select some informations with checkbox in my grid and I can get that values like array ["3001","3004"] but when i click button kendo multiselect cannot set my values
here is onclick function:
function ongrdfleetinvoice() {
var multiselect = $("#fleetinvoice").data('kendoMultiSelect');
multiselect.value(["3001","3004"]);
}
// I also try like this same function
function ongrdfleetinvoice() {
$("#fleetinvoice").getKendoMultiSelect().value(["3001","3004"]);
}
//Here is my multiselect
#(Html.Kendo().MultiSelect().Name("fleetinvoice")
.DataTextField("CariNam")
.DataValueField("CariKod")
.Placeholder("All")
.Filter(FilterType.Contains)
.HtmlAttributes(new { style = "width: 300px;" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("FillFleet", "HeadOffice");
});
})
)
//C# Code
var resultCariler = (from m in objEntities.Cariler
where (m.CariTip == 13)
orderby m.CariNam ascending
select m).AsQueryable();
foreach (var item in resultCariler)
{
Cariler objCariler = new Cariler();
objCariler.CariKod = item.CariKod.Trim();
objCariler.CariNam = item.CariNam + - + item.CariKod.Trim();
listCari.Add(objCariler);
}
but it's not working.
Do you have any idea?

I realise something when i fill my grid and my multiselect in C# side the field names are equal but values are not equeal when i change of that and put same values.. It worked...
var resultCariler = (from m in objEntities.Cariler
where (m.CariTip == 13)
orderby m.CariNam ascending
select m).AsQueryable();
foreach (var item in resultCariler)
{
Cariler objCariler = new Cariler();
objCariler.CariKod = item.CariKod.Trim();
objCariler.CariNam = item.CariNam + - + item.CariKod.Trim(); //I changed this part with same in grid
listCari.Add(objCariler);
}
TO
var resultCariler = (from m in objEntities.Cariler
where (m.CariTip == 13)
orderby m.CariNam ascending
select m).AsQueryable();
foreach (var item in resultCariler)
{
Cariler objCariler = new Cariler();
objCariler.CariKod = item.CariKod.Trim();
objCariler.CariNam = item.CariNam;
listCari.Add(objCariler);
}

Related

Get Selected Row Value In Kendo Grid

I'm able to get the selected row in kendo grid, But I'm unable to get the specific selected row data in detail grid.
One thing that I expect is just get the Ticket_ID field string "5d484b061bf03".
I've tried to make my code just like this:
function onChange(arg) {
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
myWindow.data("kendoWindow").open();
undo.fadeOut();
console.log(selected.TICKET_ID);
}
But just getting "undefined".
Any well thought to advise will be appreciated.
Thanks
jQuery $.map returns an array constructed of return values, and you are returning strings.
See Telerik example in API reference for kendo.ui.Grid change to see more about getting the data items used to construct the selected grid rows. The data items will have a field corresponding to the ticket_id value. The name of the field is case-sensitive.
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
console.log (dataItem);
selectedDataItems.push(dataItem);
}
// selectedDataItems contains all selected data items
}
you can get and persist selected row on a specific page after edit or paging in change and databound events like this:
Grid_OnRowSelect = function (e) {
this.currentPageNum = grid.dataSource.page();
//Save index of selected row
this.selectedIndex = grid.select().index();
}
.Events(e => e.DataBound(
#<text>
function(e)
{
//جهت نمایش صحیح پیجینگ
var grid = $("#Grid").data("kendoGrid");
grid.pager.resize();
//در صورت تغییر صفحه، سطر را انتخاب نکند
if(this.currentPageNum == grid.dataSource.page())
{
//انتخاب مجدد سطر انتخاب شده قبل از ویرایش
var row = grid.table.find("tr:eq(" + this.selectedIndex + ")");
grid.select(row);
}
}
</text>)
)

Fill DropDown List on selection

Helo guys, I've been working for my project for several months.
Now I'm trying to fill my dropdown list named (drpIdCorsi), based on the selection of another dropdown list named (drpDocente).
This is how my JSON object is composed:
listaCorsi =
[
{nomeCorso: "some course name"},
{emailDocente: "some email"},
]
I've loaded with an AJAX request a JSON object (which is filled correctly).
Now I'm trying to navigate my JSON object and fill the dropdown list, but it doesn't work.
This is the first function:
var listaCorsi = selezionaCorsoDocenti();
var listaCorsiDDL = '';
$('#drpDocente').on('change',function()
{
docente = $('#drpDocente').val();
docente = docente.trim();
docente= docente.split("-")[0];//gets the email of the professor
console.log(listaCorsi);
console.log(docente);
console.log(listaCorsi);
if(!$.isArray(listaCorsi))
listaCorsi = [listaCorsi];
$.each(listaCorsi,function(key,value)
{
console.log(value);
if(docente == value.emailDocente)
listaCorsiDDL += '<option value="">' + value.nomeCorso + '</option>';
});
$('#drpIdCorsi').append(listaCorsiDDL);
}).change();
This is the function called above (It actually works, but I'm not able to fill the second dropdown list, cause it shows undefined as result or nothing in the second dropdown list)
function selezionaCorsoDocenti()
{
var listaCorsi = [{}];
$.get('selezionaCorsiPerDocente',function(responseJson)
{
if(responseJson != null)
{
var i = 0;
$.each(responseJson,function(key,value)
{
listaCorsi[i] = [{nomeCorso: value.NOME_CORSO}, {emailDocente: value.EMAIL}];
i = i + 1;
});
}
else
alert("AJAX FAILED");
});
return listaCorsi;
}
I'd like to fill the second dropdown list like this:
if(docente === value.EMAIL)
course += '<option value="">' + value.NOME_CORSO + '</option>
$('#drpIdCorsi').append(course);
The function selezionaCorsoDocenti() WORKS JUST FINE.
The problem is that the JSON object listaCorsi, when I iterative over that object with the $.each() prints undefined for a certain field of the object
Your main issue is in this line:
var listaCorsi = selezionaCorsoDocenti();
$.get('selezionaCorsiPerDocente',.... is an ajax call, so it's asynchronous. You need to wait in order to get the result.
Moreover, when a change happens you need to empty the dropdown. From:
$('#drpIdCorsi').append(listaCorsiDDL);
to:
$('#drpIdCorsi').empty().append(listaCorsiDDL);
function selezionaCorsoDocenti() {
var listaCorsi = [{}];
return $.get('https://gist.githubusercontent.com/gaetanoma/5f06d1dbd111ff6a7778cd6def6b1976/raw/037587e927ac297e1f4907364898ead22ed03a0d/selezionaCorsiPerDocente.json',function(responseJson) {
responseJson = JSON.parse(responseJson);
if(responseJson != null) {
var i = 0;
$.each(responseJson,function(key,value) {
listaCorsi[i] = [{nomeCorso: value.nomeCorso}, {emailDocente: value.EMAIL}];
i = i + 1;
});
}
});
}
selezionaCorsoDocenti().then(function(x) {
listaCorsi = JSON.parse(x);
$('#drpDocente').trigger('change');
});
$('#drpDocente').on('change',function(e) {
var listaCorsiDDL = '';
docente = $('#drpDocente').val();
docente = docente.trim();
docente= docente.split("-")[0];//gets the email of the professor
if(!$.isArray(listaCorsi))
listaCorsi = [listaCorsi];
$.each(listaCorsi,function(key,value) {
if(docente == value.emailDocente)
listaCorsiDDL += '<option value="">' + value.nomeCorso + '</option>';
});
$('#drpIdCorsi').empty().append(listaCorsiDDL);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="drpIdCorsi"></select>
<select id="drpDocente">
<option>docente1#mail.edu</option>
<option>docente2#mail.edu</option>
<option>docente3#mail.edu</option>
</select>

select all method for checkboxes , should not select disabled checbox in vue.js

i have a list with checkboxes in the table , when i click select all function , it selects all checkbox including disabled ones, i neeed to exclude the disabled checkbox .
<li><a #click.prevent="selectAll" id="cardSelectAllAId">
SelectAll</a></li>
<single-checkbox class="checkbox "
inputId="card.data.id"
v-if="card.data.id"
#change="change(card.data)"
:value="card.data.selected"
:disabled="!card.data.licenseEnabled">
selectAll() {
for (let i = 0; i < this.cards.length; i += 1) {
if (this.cards[i].selected !== undefined) {
this.cards[i].selected = true;
}
},
You can try something like this in your function-
// Reset all selected first
this.cards.map((x) => x.selected = false);
// Filter and then set selected to true
this.cards
.filter((x) => x.data.licenseEnabled)
.map((x) => x.selected = true);
if(this.cards[i].selected !== undefined && this.cards[i].licenseEnabled)
this works

javascript save state of check boxes

I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.

Need a solution to this javascript coding problem

I have a SELECT in a FORM.
This select is populated using js.
I need to add a "Selected" attribute to one of these options.
I get which one, by checking a MySql database to see the name of the community which needs to have a "selected attribute" added to it.
<select name="community" id="community">
//OPTIONS HERE
</select>
The filler() function:
function filler(com){
//com is the options which needs to be selected, this variables value comes from the mysql database
var community = document.getElementById("community");
var area = document.getElementById("area").value;
// area is just another input on the page which value also is fetched from mysql db. Each area has x communities, so I have alot of IF:s.
if(area == 'Blekinge') {
community.length = 6;
community.options[0].value = "Välj Kommun";
community.options[0].text = "-- Välj Kommun --";
community.options[0].id = "Välj Kommun";
community.options[1].value = "Karlshamn";
community.options[1].text = "Karlshamn";
community.options[1].id = "Karlshamn";
community.options[2].value = "Karlskrona";
community.options[2].text = "Karlskrona";
community.options[2].id = "Karlskrona";
community.selected = 0;
}
}
As you can see, "com" variable is the option which needs to have the "selected" attribute added to it.
I have over 30 of these if-statements, and I have no clue how to create a function to add this "Selected" attribute to the matching option.
So I have "com" which for example could be "Karlskrona" in the example above. How should I add the selected to it?
I need a simple function for this which works in all major browsers...
Set the selectedIndex property of the SELECT to whichever index you need. Zero-based, of course.
Just do
community.value = com;
example at http://www.jsfiddle.net/jMapA/
for(var i = 0; i < community.options.length; i++) {
if(community.options[i].id == com)
community.selectedIndex = i;
}
function selectOptionValue(selectId, value)
{
select = document.getElementById(selectId);
if (select)
{
for (var i = 0; i < select.options.length)
{
if (select.options[i].value == value)
{
select.options[i].selected = 'selected';
return true;
}
}
}
return false;
}
Use my function like this:
selectOptionValue('community', 'Karlskrona');

Categories