jqgrid checkbox change event - javascript

I have true/false values in my database. I want to update them with checkbox in jqgrid.
Once the value is set to true, it will remain true and should not change. Please take a look at my column model :
{
name : 'available',
width : 12,
resizable: true,
editable: true,
align: 'center',
edittype:'checkbox',
formatter: "checkbox", formatoptions: {disabled : false},
classes:'check',
editrules:{required:false}, editoptions:{size:39,value:"True:False"}
}
I'm trying to capture the event when checkbox is checked, currently they are all unchecked, so far I've tried:
jq(".check input").each(function(){
jq(this).click(function(){
aler("works");
});
});
jq("input[type='checkbox']").change(function(){
alert("works");
});
jq(":checkbox").parent().click(function(evt) {
if (evt.target.type !== 'checkbox') {
var $checkbox = jq(":checkbox", this);
$checkbox.attr('checked', !$checkbox.attr('checked'));
$checkbox.change();
alert("");
}
});
None of these work, I'm stuck don't know what else to try.
When inspect checkbox code with firebug it looks like this :
<input type="checkbox" offval="no" value="false">

You can create a custom formatter. In your grid,
formatter: cboxFormatter,
Then define the function,
function cboxFormatter(cellvalue, options, rowObject)
{
return '<input type="checkbox"' + (cellvalue ? ' checked="checked"' : '') +
'onclick="alert(' + options.rowId + ')"/>';
}
You can use onclick to perform your task or call a function.

The usage of the custom formatter is one of the possibilities. One can also use unobtrusive style of onclick binding
First one defines
var grid = $("#list"),
getColumnIndexByName = function(columnName) {
var cm = grid.jqGrid('getGridParam','colModel'),i=0,l=cm.length;
for (; i<l; i++) {
if (cm[i].name===columnName) {
return i; // return the index
}
}
return -1;
},
disableIfChecked = function(elem){
if ($(elem).is(':checked')) {
$(elem).attr('disabled',true);
}
};
Then one can use the in the loadComplete the code like
loadComplete: function() {
var i=getColumnIndexByName('closed');
// nth-child need 1-based index so we use (i+1) below
$("tbody > tr.jqgrow > td:nth-child("+(i+1)+") > input",
this).click(function(e) {
disableIfChecked(this);
}).each(function(e) {
disableIfChecked(this);
});
}
See the corresponding demo here.

This worked for me:
// Listen for Click Events on the 'Process' check box column
$(document).on("click", "td[aria-describedby='grdOrders_Process']", function (e) {
var checked = $(e.target).is(":checked")
var rowId = $(e.target).closest("tr").attr("id")
rowData = jQuery("#grdOrders").getRowData(rowId);
alert("Checked: " + checked)
alert("OrderNo: " + rowData.OrderNo);
alert("Name: " + rowData.Name);
});

Related

Highlight Jqgrid when clicking on row but dont select the multiselect checkbox

Within jQgrid is there a way that a row can be clicked on and then highlighted without the multiselect row checkbox being checked?
I have tried with Multiboxonly = true which was recommended by Oleg https://stackoverflow.com/a/3719637/853607
Any help would be great as this is stopping progress on a critical project.
Maybe you have typed it wrong. You speak Multiboxonly : true, but actuually it is multiboxonly : true in the implementation. This should work if you use JavaScript only version. If you use some wrapper like ASP.NEt or PHP you should consult the docs for these.
Kind Regards
Here is my answer for clicking on a row and not checking the checkbox but the row getting highlighted - returning false ensures onSelectRow is not fired. ps #tony I had multiboxonly in lower case.
beforeSelectRow: function (rowid, e) {
//debugger;
rowId = rowid;
if ($("#jqg__tradesGrid_" + rowid).attr("disabled") || CommentsClicked) {
CommentsClicked = false;
return false;
}
if (e.target.type == "checkbox") {
var blnChecked = $(e.target).is(":checked");
var trElement = jQuery("#" + rowid, jQuery('#_tradesGrid'));
if (!firstLoadWithRecords) {
updateIdsOfSelectedRows(rowid, blnChecked);
}
if (blnChecked || $.inArray(rowid, idsOfSelectedRows) >= 0) {
trElement.removeClass('ui-widget-content');
trElement.addClass('ui-state-highlight');
} else {
trElement.removeClass('ui-widget-content');
trElement.removeClass('ui-state-highlight');
}
} else {
var blnChecked = $(e.target).is(":checked");
var trElement = jQuery("#" + rowid, jQuery('#_tradesGrid'));
trElement.removeClass('ui-widget-content');
trElement.removeClass('ui-state-highlight');
}
//TODO: put in the style to chagne to silver when the checkbox is checked
CommentsClicked = false;
return false;
},

Jquery validation not working properly?

I am trying to do required validation in a asp.net page.
I have multiple controls that will be hidden and displayed.
Controls like checkboxlist,dropdownlist,multiselectedlistbox.
I am using a css class called required attaching to all these controls to check the validation.
I am trying to check if each control has value or not but my code is checking each options with in each controls.
I am really not finding a way not a jquery expert just a novice...
Here is my code any ideas anyone please....
$("input[type='submit']").click(function () {
if ($(this).val() != 'Back') {
var names = [];
var info=" ";
$('.required input').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
$('.required option').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if ((radio_buttons.filter(':checked').length == 0) ||(radio_buttons.filter(':selected').length == 0)) {
info += radio_buttons.closest("table").find('label').html()+"</br>";
}
}
if (info != " ") {
$("#validation_dialog p").html(info);
$("#validation_dialog").dialog({
title: "Validation Error!",
modal: true,
resizable: false,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
return false;
}
}
});
here is a fiddle for it...
http://jsfiddle.net/bDmgk/35/
I think what you want is:
$(".required input[type='radio']:checked").each(function(){
});
instead of :
$(".required option").each(function(){ ... });
Hi I made some changes to your fiddle basically I checked for the inputs inside each column like this and then I added them to your names array.
Using
$('table.required:eq(0) input:checked')
I you can got all the inputs that are checked on the first column if the lenght of the array returned is 0 then no input is checked, i't the same procedure for the other ones.
An yes those input names are weird.
Check this fiddle
JSFiddle

Storing check box in local storage

I'm able to store text how I want but cant get check boxes to work properly. It is storing the check box values as 'on' regardless if checked or not. How can I set is to store "off" by default and "on" when checked?
something that would achieve this:
var value = $(this).val() && $(this).prop(checked);
JS Fiddle: http://jsfiddle.net/cRJ23/17/
Storage.prototype.setObj = function (key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function (key) {
return JSON.parse(this.getItem(key))
}
var Survey = {},
Surveys = {},
save = function () {
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
console.log('Saving');
console.log(name + ':' + value);
Survey[name] = value;
});
if (localStorage.getObj('Surveys') != null) {
Surveys = localStorage.getObj('Surveys');
}
Surveys[$('#FirstName').val() + '.' + $('#LastName').val()] = Survey; //store in big list
localStorage.setObj('Surveys', Surveys);
}
Hope this helps:
var value = $(this).val();
var name = $(this).attr('name');
if($(this).hasClass('checkers')){
value = $(this).is(":checked")
if(value){
value='on';
}else{
value='off';
}
}
http://jsfiddle.net/juvian/cRJ23/22/
You should not use .val to check whether checkbox is selected, use .is('checked')
Instead of using .val()to get the state of a checkbox you should use .prop() or the property .checked
$('input, select, textarea').each(function () {
var value = ($(this).is('[type="checkbox"]')) ? this.checked :$(this).val(),
name = $(this).attr('name');
console.log('Saving');
console.log(name + ':' + value);
Survey[name] = value;
});
Working example: http://jsfiddle.net/cRJ23/24/
Working Fiddle http://jsfiddle.net/jFeLv/
The val function does not work like you would expect with check boxes, the way to get true or false from them is to use the is(':checked') function.
$(this).is(':checked')
The fiddle is a modified version of your code by modifying one line that seems to be working fine by shorthanding an if else for the variable "value" checking to see if it is a checkbox.
($(this).attr('type','checkbox') ? value = $(this).val() : value = $(this).is(':checked'));
I hope this helps.

Filtering html fields with jQuery

I have read about filtering table plugins. What I'm searching for is like this popup window.
(source: staticflickr.com)
When the user starts typing in the search-box, the relevant channel/category (as selected on previous dropdown box) should filter up. Also some animated loading action should happen while the filter process is going on.
I am looking for jQuery plugins which will make my filter-job easier to implement.
I think it is to ambigous to have a plugin for it. Just do something like this:
function filter($rows, category, search) {
$rows.each(function() {
if (category == ($("td:eq(2)", this).text() || category == "all") && (search. === "" || $("td:eq(1)", this).text().indexOf(search) !== -1) {
$(":checkbox", this).removeAttr("disabled");
$(this).show();
}
else
$(this).hide(function(){
$(":checkbox", this).attr("disabled", "disabled");
});
});
}
$("select.category").change(function() {
filter ($(this).closest("form").find("tr"), $(this).val(), $(this).closest("form").find("input.search").val());
});
$("input.search").keyUp(function() {
filter ($(this).closest("form").find("tr"), $(this).closest("form").find("select.catagory").val(), $(this).val());
});
You may need to make a few adjustments in order to make it work with the exact format of html.
Update to make it into a PLUGIN
$.fn.filter_table = function(options) {
options = $.extend(options, {
show: $.noop(), //Callback when a row get shown
hide: $.noop(), // Callback when a row gets hidden
entries: "table tr", // Selector of items to filter.
map: {} //Required parameter
//TODO Add default ajustment parameters here to remove ambiguity and assumptions.
});
return this.each(function() {
var form = this;
function each(callback) {
for (var selector in options.map) {
var check = options.map[selector];
$(selector, form).each(function(){
callback.call(this, check);
});
}
}
function show(row) {
if (!$(row).is(":visible")) {
options.show.apply(row);
$(row).show();
}
}
function hide(row) {
if ($(row).is(":visible"))
$(row).hide(options.hide);
}
function run_filter() {
$(options.entries, form).each(function() {
var row = this, matched = true;
each(function(check) {
matched &= check.call(this, row);
});
matched ? show(this) : hide(this);
})
}
//Bind event handlers:
each(function() {
$(this).bind($(this).is(":text") ? "keyup" : "change", run_filter);
});
});
};
You can use this plugin as follows:
$("form").filter_table({
map: {
//These callback define if a row was matched:
"select.category": function(row) {
//this refers to the field, row refers to the row being checked.
return $(this).val() == "all" || $(this).val() == $("td:eq(2)", row).text();
},
"input.search": function(row) {
return $(this).val() == "" || $(this).val() == $("td:eq(1)", row).text();
}
},
entries: "tr:has(:checkbox)", //Filter all rows that contain a checkbox.
show: function() {
$(":checkbox", this).removeAttr("disabled");
},
hide: function() {
$(":checkbox", this).attr("disabled", "disabled");
}
});
Okay it should work once it was debugged. I haven't tested it. I think that part is up to you.
If your HTML looks like this:
<form id="filterForm">
<input type="text" id="filterBox">
<input type="submit" value="Filter">
</form>
<div id="checkboxContainer">
<label><input type="checkbox" id="checkbox123"> Checkbox 123</label>
</div>
You could do something like...
//Set variables so we only have to find each element once
var filterForm = $('#filterForm');
var filterBox = $('#filterBox');
var checkboxContainer = $('#checkboxContainer');
//Override the form submission
filterForm.submit(function() {
//Filter by what the label contains
checkboxContainer.find('label').each(function() {
//If the value of filterBox is NOT in the label
if ($(this).indexOf(filterBox.val()) == -1) {
//Hide the label (and the checkbox since it's inside the label)
$(this).hide();
} else {
//Show it in case it was hidden before
$(this).show();
}
});
//Prevent the form from submitting
return false;
});
You can use this tablesorterfilter plugin to achieve what you need
Working Fiddle
And also please have a look at http://datatables.net/
There are many options out there. Here is a good place to start: http://www.wokay.com/technology/32-useful-jquery-filter-and-sort-data-plugins-62033.html
Filtering like this isn't incredibly complicated. It may be worth looking at the source of a couple plugins that come close to what you want and then try to write your own. You'll learn a lot more if you do it yourself!

How to change a single value of checkbox inside a localStorage?

I'm trying to change a value inside localstorage. This item is the status of a checkbox. I want, everytime that a checkbox is checked to set the value to true or false of that checkbox. I tried many ways until I realized that there is no way you can change a value without using JSON.
To add the value I use:
localStorage.setItem("status-" + i, $status.is(":checked"));
and to delete I use:
var parentId = $this.parent().attr('id');
localStorage.removeItem("'" + parentId + "'");
Now to change the value I tried:
$itemList.delegate("#status-" + i, 'click', function(e) {
var $this = $(this);
var parentId = this.parent().attr('id');
if ($this.is(":checked")) {
localStorage.setItem("'" + parentId + "'".val("fdgsdagf"));
// Note that alert here works.
}
});
This is how my local storage looks like:
I hope someone could help me. I've been working on it for few days...
Here is a fiddle for it: http://jsfiddle.net/CC5Vw/7/
Thanks alot
look at this: http://jsfiddle.net/Rh4Au/6/ works well..
changes http://jsfiddle.net/CC5Vw/7/ to http://jsfiddle.net/Rh4Au/6/
line 30:
+ "<div class='checkbox'><input type='checkbox' class='test' id='status-" + i + "'></div>"
i chaged to j because i is the length and j is the iterator.
insertion after line 34:
var tempasd = orderList[j].split("-")[1];
if(localStorage.getItem("status-"+tempasd) == "true") {
$("#status-"+j).get(0).checked = true
}
else {
$("#status-"+j).get(0).checked = false
}
}
The code loads the data from localStorage and check in the checked checkboxes.
The tempasd is a temporary variable store the current ID num of the checkbox (because they not always come ascending.
changes from line 99 to 117:
// ON STATUS CLICK
console.log('i=',i,' j=',j, 'k=',k);
$itemList.delegate("#status-" + i, 'click', function(e) { // ON CLICK
var $this = $(this);
var parentId = $this.attr('id');
if ($this.is(":checked")) {
console.log('set ', parentId, 'to foo');
localStorage.setItem(parentId, 'foo');
// localStorage.setItem("'" + parentId + "'".val("fdgsdagf"));
// localStorage.setItem($this.parent().attr('checked', true));
// window.location = "http://mail.aol.com"
}
});
to
// ON STATUS CLICK
console.log('i=',i,' j=',j, 'k=',k);
var tempxx;
for(tempxx = 0;tempxx < j; tempxx++) {
$itemList.delegate("#status-" + tempxx, 'click', function(e) { // ON CLICK
var $this = $(this);
var parentId = $this.parent().parent().attr('id').split("-")[1];
console.log('set ', parentId, 'to foo');
localStorage.setItem("status-"+parentId, $this.is(":checked"));
// localStorage.setItem("'" + parentId + "'".val("fdgsdagf"));
// localStorage.setItem($this.parent().attr('checked', true));
// window.location = "http://mail.aol.com"
});
}
i need the loop because it needs to delegate an event to each checkbox, and also the event must set the localStorage to false when it gets unchecked.
btw the .parent().parent() is unnecesarry now because i fixed at line 30.

Categories