I have a column in a DataTable in Jquery where in each row the cell respective to the column has a dropdown box inside of it.
I am rendering this dropdown by defining it in the 'columnDefs' options as such:
$(document).ready(function() {
$('#example').DataTable(
"columnDefs":[
{
"render": function(d,t,r){
var $select = $("<select></select>", {
"id": r[1]+"start",
"value": d,
"class": r[1]
});
$.each(times, function(k,v){
var $option = $("<option></option>", {
"text": v,
"value": v
});
if(d === v){
$option.attr("selected", "selected")
}
$select.append($option);
});
return $select.prop("outerHTML");
},
"targets": 2
}
]
)})
The data variable times in the $.each statement is just a variable that I am loading from localStorage, which consists of dates.
Since I want to wait for the data in the DataTables to be loaded before I select an item, I add an option called initComplete and in it I add the change() method as well as a method to store the change value into localStorage:
"initComplete": function(settings, json) {
$(function() {
$('.SomeDate').change(function() {
localStorage.setItem('storeddata', this.value);
});
if(localStorage.getItem('storeddata')){
$('.SomeDate').val(localStorage.getItem('storeddata'));
}
});
}
The dropdown <select> tag generated in the front end looks as such:
<select id="SomeDatestart" value="SomeValue" class="SomeDate"></select>
For some reason when I select an item in the dropdown box, I don't get any results stored in the localStorage.
I could have made the selector select the select tag id instead of the select tag class, but even while trying that, I was not able to trigger a change() event.
However I tried to take the change() method above, and isolate it from the datatable function, and create a dummy dropdown box with the same select tag and sample <option> tags, and after doing that, I was able to successfully trigger the change() method, and similarly store the value in localStorage.
Am I missing something? Perhaps there is a different way of triggering the change() method for selections in DataTables?
Related
I need to recalculate the table by calling recal after a row was selected by check box. If it is selected by clicking the row calling recal works. I copied the below code from plugin site
{formatter:"rowSelection", titleFormatter:"rowSelection", hozAlign:"center", headerSort:false, cellClick:function(e, cell){
console.log("table ",table);
// cell.getRow().toggleSelect();
console.log("table ",table);
table.recalc();
}},
but nothing gets executed. The checkbox gets checked and the row highlighted. You can try my jsFiddle.
UPDATE 1
so it works if I click off the checkbox but I want the function to be triggered when the checkbox is clicked.
As the name suggest cellClick which should be called on cell element click there is another element which is considered cell and checkbox is contained inside cell that's why cellClick is not trigger when you click checkbox and triggered when click outside of checkbox
Issue
As Suggested by #EugeneOlisevich instead of listening to cellClick, Listening to rowSelectionChanged would be better option.
Instead of using table to call recalc as table reference is not created until first load completes.
Another way you can access recalc function is through this
...
rowSelectionChanged: function(e, row) {
this.recalc();
},
...
Issue
When you click editable column if row is selected then it will deselect the row
which can be solve by preventing event bubbling to parent through cellClick function.
...
{
title: "mn",
field: "mn",
editor: "number",
cellEdited: function(cell) {
aktualizuj_m(cell);
},
cellClick: function(e, cell) {
e.preventDefault();
e.stopPropagation();
},
},
...
Issue
As table reference is not created on first load here i added condition to not run loop until table reference is undefined/null
table && values.forEach(function(value, index) {
var row = table.getRow(index + 1);
if (row.isSelected() && value) {
calc = calc + value;
}
});
Issue
If you change mn column input to 0 then sum is not updated
which can be solved by updating condition.
...
if (typeof mnozstvi == "number") {
cell.getRow().update({
cena_m: cena * mnozstvi
});
}
...
Note: Negative range can be input in mn column
Here working example
You can try to use another event handler instead of listening to direct cell click or row selection (or it depends on behaviour you want)
Here is the link to fiddle to check the solution:https://jsfiddle.net/02phqxz8/
...,
rowSelectionChanged:function(data, rows) {
if(table) {
table.recalc();
}
},
...
What was changed:
Instead you can handle rowSelectionChanged event. Every time it is called, by clicking row, or clicking checkbox you can call recalculate for table. Just be sure to check teh table object by default, because the event is fired prior the constuctor return tha table itself.
Or as an option to avoid this additoinal check every time, you can subscribe to this event right after table is created.
You can use rowSelectionChanged
rowSelectionChanged:function(data, rows) {
if (updatedDataLength != data.length) {
updatedDataLength = data.length;
table.recalc();
}
},
var updatedDataLength = 0;
You need to add a local variable that could check data changed because the first time the table rendered, it will also call table.recalc() that will cause a problem of rendering the initial table.
So I suggest using to check updated data length to keep it simple rather than comparing whole data.
Or you can just add a flag var tableRendered = false;.
rowSelectionChanged: function(data, rows) {
if (!tableRendered) {
tableRendered = true;
} else {
table.recalc();
}
},
i have this column with dropdown, currently when i select any value from the dropdown it it gets saved, i would like to add a validation while selecting a value from dropdown before saving, for example,
{name:'color_name',
cellattr: function (rowid, cellValue) {
if ($.inArray(cellValue, hilightcolorcell) < 0) {
return " class='redcells'";
}
},editable:true,edittype:"select",editoptions:
{value:"PURPLE:PURPLE;PINK:PINK;GREEN:GREEN"}}
if the selected value was PINK, i wanted to have a validation prompt with Save and Cancel button something like this, Selected Value is : PINK, SAVE CANCEL
this is demo link https://jsfiddle.net/kwu7v3fc/3/
please help.
There are many ways to implement your requirement. The most native would seems to me to ask the confirmation from the user directly on change of the select option and before real saving it. One can add "change" event handler, which do all you need. The corresponding implementation will look like on the example below
editoptions: {
value: "PURPLE:PURPLE;PINK:PINK;GREEN:GREEN",
dataEvents: [
{
type: "change",
fn: function (e) {
if ($(this).val() === "PINK") {
if (!confirm("Are you sure you want PINK?")) {
// reset the value to the previous one
var savedRow = $("#rowed5").jqGrid("getGridParam", "savedRow");
$(this).val(savedRow[0].v);
}
}
}
}
]
}
See the modified demo https://jsfiddle.net/OlegKi/kwu7v3fc/5/
I have a following select element:
<select id="options" title="prd_name" name="options">
<option id='option1' value='Prdt1'>Product1</option>
<option id='option2' value='Prdt2'>Product2</option>
<option id='option3' value='Prdt3'>Product3</option>
<option id='option4' value='Prdt4'>Product4</option>
</select>
I populate this select element using JQuery with some data from the database. I want to run a few Javascript functions as soon as this select element is populated with a options and I want those functions to run using the first option value. I am currently only able to run functions by adding onblur and onchange attributes in the select tag.
The problem arises, when I have only one option element, i.e. one product. By this I am unable to onblur or onchange and I used onload in the select element, which is not working aswell.
Anyone has any idea what am I missing or doing wrong?
You might want to consider calling the methods immediately after you populate the options , rather than triggering onblur / onchange.
Here is the code :
$(document).ready(function(){
//Consider this as success callback
populateOptions();
});
function populateOptions(){
var options = [1,2,3];
var optionsHtml = "";
for(var idx = 0; idx < options.length; idx++){
var val = options[idx];
optionsHtml += "<option id=option"+val+" value='Prdt"+val+"'>Product"+val+"</option>"
}
$("#firstDropdown").html(optionsHtml);
executeMethods();
}
function executeMethods(){
// find the first element
var firstValue = $("#firstDropdown").find('option:eq(0)').val();
if(firstValue === undefined){
return;
}
console.log("Call Method with first Value : " + firstValue);
}
jsbin : Code Sample
imagine you have this data that you want to be populated into the select tag:
var _data=[
{
value:1,
text:'one'
},
{
value:2,
text:'two'
},
{
value:3,
text:'three'
},
{
value:4,
text:'four'
},
{
value:5,
text:'five'
}
];
you can create a custom event like this:
var selectPopulated=new Event('selectPopulated');
and then bind your event to your element like this:
$('select').on('selectPopulated',function(){
var firstOption=$(this).find('option:first-child').val();
//your functions go here
alert('Select is all populated - first option value is: '+firstOption);
});
and then just trigger the event wherever you populate the select tag:
$('select').trigger('selectPopulated');
now you can even trigger this event in other js files without having to repeat your snippet only using the trigger method, here's a simple example: DEMO
and here's the complete code:
var _data=[
{
value:1,
text:'one'
},
{
value:2,
text:'two'
},
{
value:3,
text:'three'
},
{
value:4,
text:'four'
},
{
value:5,
text:'five'
}
];
var selectPopulated=new Event('selectPopulated');
function init(){
$('select').on('selectPopulated',function(){
var firstOption=$(this).find('option:first-child').val();
//your functions go here
alert('Select is all populated - first option value is: '+firstOption);
});
renderElements();
}
function renderElements(){
var select=$('select');
for(var i=0, dataLength=_data.length; i<dataLength; i++){
select.append('<option value="'+_data[i].value+'">'+_data[i].text+'</option>');
}
$('select').trigger('selectPopulated');
}
init();
as pointed out in the comments by #PraneshRavi if you don't have control over how/when the element is getting populated the only possible way without having to change anything is to use an interval which is a bad idea but in the other hand if you do have control over the populating snippet I recommend creating an api where the code is populating the select and implementing the event method I just explained.
You can call your functions after populating the <select> because appending elements into DOM is a synchronous activity.
Try this
function addOptions() {
// do stuff to get the data from the database
$('select').html() //adding options based on the data from the database into the <select>
yourFunction(firstValue) //calling your functions
yourFunction2()
}
addOptions()
I got two Kendo ui multiselect elements on my page to select stores from a list. On the select event I have a function call where I check if the selected store is in another list.
If the selected item is already assigned to the other list i prompt a confirm. When the user click ok, then is ok, when clicks cancel i have to remove the selected item from the multiselect element.
Here is my function:
function checkStoreSelection(e) {
var selectedStore = this.dataSource.view()[e.item.index()];
var selectedStoreId = selectedStore.Id;
$.each(surveysData, function (index, surveyVal) {
// get each store
$.each(surveyVal.Stores, function (storesIndex, storesVal) {
// check if a store already assigned to another survey
if (selectedStoreId == storesVal.DBId) {
var answer = confirm('Some text here ... ');
if (answer) {
// nothing todo here
} else {
// have to remove the selected item
}
}
});
});
};
You can remove item from datasource dataSource.remove(item);
Check this example
http://jsfiddle.net/derickbailey/D4g8S/
Damn fool - Simple answer:
e.preventDefault();
Does what I need :-/
I´am sorry.
Hope that made sense. I have a text input that uses the jQuery UI autoselect feature. The input auto-fills when a user selects, as it should. My problem is if a user inputs something, but then doesn't select from the drop down. This results in the text input value being something that doesn't exist in the list upon a form submit. I want to know if there is a way to perform an action (clear text input value) on the 'change' event but leave it as it is for the 'select' event.
If I'm understanding you correctly, you should be able to leverage the ui parameter that's passed to a change event handler:
$("#auto").autocomplete({
/* options */
change: function (event, ui) {
if (!ui.item) {
this.value = '';
}
}
});
ui.item will be undefined if nothing is selected from the autocomplete candidate list.
Example: http://jsfiddle.net/ZBzpF/
Inside the change event handler, check if the current value is in the source, if not, reset it. Something like:
var sourceArray = ["a", "b", "c"],
$autocomplete = $('#autocomplete');
$autocomplete.autocomplete({
source: ,
change: function(e, ui) {
if ($.inArray($autocomplete.val(), sourceArray) === -1) {
//change the value
}
})
}