Jquery Uncheck the users last selected option - javascript

I have a Multi Select Box which contains the services and duration. If user selects some services then its duration is captured, if duration is exceed the limit then a alert is generated.How can i uncheck the last checked value by user so that duration is not reset if exceed limit.here is my code:
jQuery('.check-service').click(function () {
serviceselected = jQuery("input.check-service:checked").length;
serviceduration = 0;
jQuery('input.check-service:checked').each(function () {
serviceduration = parseInt(jQuery(this).val()) + parseInt(serviceduration);
if (selectvalues == '') {
selectvalues = jQuery(this).attr('title');
serviceids = jQuery(this).attr('id');
} else {
selectvalues = selectvalues + "," + jQuery(this).attr('title');
serviceids = serviceids + ", " + jQuery(this).attr('id');
}
});
if (serviceduration >= '600') {
alert("Selected Service is more than available time slot.");
jQuery('input.check-service').attr('checked', false);
console.log();
}
Currently its unchecked all the checked valued.I just want to uncheck the last previous selected value.
Thanks in Advance.

Try the below code:
jQuery('#CheckboxID').click(function(){ //instead of class use id
serviceselected = jQuery("input.check-service:checked").length;
serviceduration = 0;
jQuery('input.check-service:checked').each(function () {
serviceduration = parseInt(jQuery(this).val()) + parseInt(serviceduration);
if(selectvalues == '') {
selectvalues = jQuery(this).attr('title');
serviceids = jQuery(this).attr('id');
}
else {
selectvalues = selectvalues + "," + jQuery(this).attr('title');
serviceids = serviceids + ", " + jQuery(this).attr('id');
}
});
if (serviceduration >= '600') {
alert("Selected Service is more than available time slot.");
jQuery(this).attr( 'checked', false );
console.log();
}
});

You cant store last selected checkbox in some global variable.
var $lastChecked;
$(".check-service").on("change", function () {
if ($(this).attr("checked") == "checked") {
lastChecked = $(this);
}
//your logic
//...
//now when you have to uncheck:
$lastChecked.removeAttr("checked");
})

Related

Onchange within a loop

I am making a JavaScript solution related to MediaWiki, but what it is for is not really needed information, so I will leave it there. I have the following function:
wgAjaxLicensePreview=true;
function getLicensePreview(num) {
console.log('glp num', num);
window.licenseSelectorCheck = function () {
var selector = document.getElementById("license" + num);
var selection = selector.options[selector.selectedIndex].value;
if (selector.selectedIndex > 0) {
if (selection == "") {
// Option disabled, but browser is broken and doesn't respect this
selector.selectedIndex = 0;
}
}
// We might show a preview
wgUploadLicenseObj.fetchPreview(selection);
};
var wpLicense = document.getElementById('license' + num);
console.log('glp wpLicense', wpLicense);
if (mw.config.get('wgAjaxLicensePreview') && wpLicense) {
// License selector check
wpLicense.onchange = licenseSelectorCheck;
// License selector table row
var wpLicenseRow = wpLicense.parentNode.parentNode;
var wpLicenseTbody = wpLicenseRow.parentNode;
var row = document.createElement('tr');
var td = document.createElement('td');
row.appendChild(td);
td = document.createElement('td');
td.id = 'mw-license-preview' + num;
row.appendChild(td);
wpLicenseTbody.insertBefore(row, wpLicenseRow.nextSibling);
console.log('glp row', row);
}
window.wgUploadLicenseObj = {
'responseCache': {
'': ''
},
'fetchPreview': function (license) {
if (!mw.config.get('wgAjaxLicensePreview'))
return;
for (cached in this.responseCache) {
console.log('glp fp responseCache', this.responseCache);
if (cached == license) {
this.showPreview(this.responseCache[license]);
return;
}
}
$('#license' + num).injectSpinner('license' + num);
var title = document.getElementById('imagename' + num).value;
if (!title)
title = 'File:Sample.jpg';
var url = mw.util.wikiScript('api')
+ '?action=parse&text={{' + encodeURIComponent(license) + '}}'
+ '&title=' + encodeURIComponent(title)
+ '&prop=text&pst&format=json';
var req = sajax_init_object();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
console.log('glp fp response', req.responseText);
wgUploadLicenseObj.processResult(eval('(' + req.responseText + ')'), license);
}
};
req.open('GET', url, true);
req.send('');
},
'processResult': function (result, license) {
$.removeSpinner('license' + num);
this.responseCache[license] = result['parse']['text']['*'];
console.log('glp pr result license', result, license);
this.showPreview(this.responseCache[license]);
},
'showPreview': function (preview) {
var previewPanel = document.getElementById('mw-license-preview' + num);
console.log('glp sp', previewPanel, preview, previewPanel.innerHTML == preview);
if (previewPanel.innerHTML != preview)
previewPanel.innerHTML = preview;
}
};
}
The issue with that, is the loop I have
var limit = this.max < this.fileCount ? this.max : this.fileCount;
console.log('glp', this.max, this.fileCount);
for (i = 1; i <= limit; i++) {
console.log('glp i', i);
getLicensePreview(i);
}
Does not iterate correctly for part of it, I have narrowed the issue down to, wpLicense.onchange = licenseSelectorCheck; which is rewriting the event handler to only check the last num.
Thanks to help from Barmar, I was able to solve this by making the wgUploadLicenseObj variable local rather then global window.wgUploadLicenseObj.
My final function ended up being:
wgAjaxLicensePreview=true;
function getLicensePreview(num) {
window.licenseSelectorCheck = function () {
var selector = document.getElementById("license" + num);
var selection = selector.options[selector.selectedIndex].value;
if (selector.selectedIndex > 0) {
if (selection == "") {
// Option disabled, but browser is broken and doesn't respect this
selector.selectedIndex = 0;
}
}
var wgUploadLicenseObj = {
'responseCache': {
'': ''
},
'fetchPreview': function (license) {
if (!mw.config.get('wgAjaxLicensePreview'))
return;
for (cached in this.responseCache) {
if (cached == license) {
this.showPreview(this.responseCache[license]);
return;
}
}
$('#license' + num).injectSpinner('license' + num);
var title = document.getElementById('imagename' + num).value;
if (!title)
title = 'File:Sample.jpg';
var url = mw.util.wikiScript('api')
+ '?action=parse&text={{' + encodeURIComponent(license) + '}}'
+ '&title=' + encodeURIComponent(title)
+ '&prop=text&pst&format=json';
var req = sajax_init_object();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
wgUploadLicenseObj.processResult(eval('(' + req.responseText + ')'), license);
}
};
req.open('GET', url, true);
req.send('');
},
'processResult': function (result, license) {
$.removeSpinner('license' + num);
this.responseCache[license] = result['parse']['text']['*'];
this.showPreview(this.responseCache[license]);
},
'showPreview': function (preview) {
var previewPanel = document.getElementById('mw-license-preview' + num);
if (previewPanel.innerHTML != preview)
previewPanel.innerHTML = preview;
}
};
// We might show a preview
wgUploadLicenseObj.fetchPreview(selection);
};
var wpLicense = document.getElementById('license' + num);
if (mw.config.get('wgAjaxLicensePreview') && wpLicense) {
// License selector check
wpLicense.onchange = licenseSelectorCheck;
// License selector table row
var wpLicenseRow = wpLicense.parentNode.parentNode;
var wpLicenseTbody = wpLicenseRow.parentNode;
var row = document.createElement('tr');
var td = document.createElement('td');
row.appendChild(td);
td = document.createElement('td');
td.id = 'mw-license-preview' + num;
row.appendChild(td);
wpLicenseTbody.insertBefore(row, wpLicenseRow.nextSibling);
}
}

jQuery plugin/library for this table to simplify code

https://jsfiddle.net/51Le6o06/48/
please take a look at the jsfiddle the code is getting to complicated and my functions aren't working correctly.
can anyone tell me what I could use instead of standard jQuery and javascript to make this easier to build (with a show more style pagination method).
I need to sort, filter and page existing html as in the jsfiddle.
thanks.
$(document).ready(function() {
$('.filter-gift').each(filterItems);
});
function filterItems(e) {
var items = [];
var table = '';
tableId = $(this).parent().parent().attr('tag')
var listItems = "";
listItems += "<option value=''> -Select- </option>";
$('div[tag="' + tableId + '"] table.internalActivities .information').each(function (i) {
var itm = $(this)[0].innerText;
if ($.inArray(itm, items) == -1) {
items.push($(this)[0].innerText);
listItems += "<option value='" + i + "'>" + $(this)[0].innerText + "</option>";
}
});
$('div[tag="' + tableId+ '"] .filter-gift').html(listItems);
$('.filter-gift').change(function () {
if($(this).val()!= "") {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
} else {
$(this).parent().parent().find('table tr').show();
}
});
}
jQuery.fn.sortPaging = function(options) {
var defaults = {
pageRows: 2
};
var settings = $.extend(true, defaults, options);
return this.each(function() {
var container = $(this);
var tableBody = container.find('.internalActivities > tbody');
var dataRows = [];
var currentPage = 1;
var maxPages = 1;
var buttonMore = container.find('.seeMoreRecords');
var buttonLess = container.find('.seeLessRecords');
var buttonFree = container.find('.filter-free');
var tableRows = [];
var maxFree = 0;
var filterFree = buttonFree.is(':checked');
function displayRows() {
tableBody.empty();
var displayed = 0;
$.each(dataRows, function(i, ele) {
if( !filterFree || (filterFree && ele.isFree) ) {
tableBody.append(ele.thisRow).append(ele.nextRow);
displayed++;
if( displayed >= currentPage*settings.pageRows ) {
return false;
};
};
});
};
function checkButtons() {
buttonLess.toggleClass('element_invisible', currentPage<=1);
buttonMore.toggleClass('element_invisible', filterFree ? currentPage>=maxFreePages : currentPage>=maxPages);
};
function showMore() {
currentPage++;
displayRows();
checkButtons();
};
function showLess() {
currentPage--;
displayRows();
checkButtons();
};
function changedFree() {
filterFree = buttonFree.is(':checked');
if( filterFree && currentPage>maxFreePages ) {
currentPage=maxFreePages;
};
displayRows();
checkButtons();
};
tableBody.find('.product-data-row').each(function(i, j) {
var thisRow = $(this);
var nextRow = thisRow.next();
var amount = parseFloat(thisRow.find('.amount').text().replace(/£/, ''));
var isFree = thisRow.find('.free').length;
maxFree += isFree;
dataRows.push({
amount: amount,
thisRow: thisRow,
nextRow: nextRow,
isFree: isFree
});
})
dataRows.sort(function(a, b) {
return a.amount - b.amount;
});
maxPages = Math.ceil(dataRows.length/settings.pageRows);
maxFreePages = Math.ceil(maxFree/settings.pageRows);
tableRows = tableBody.find("tr");
buttonMore.on('click', showMore);
buttonLess.on('click', showLess);
buttonFree.on('change', changedFree);
displayRows();
checkButtons();
})
};
$('.sort_paging').sortPaging();
The best solution when it comes to tables with all the filter, sorting, pagination features and much more is one and only.
jQuery Datatables
Just check out the link, It's Easy and Highly Customizable.
Maybe you could use this jquery plug-in DataTables

Sharepoint javascript list form validation on presaveaction

I have a Function named "ViewItem" that calls 2 more functions: "success" and "failed". When "success" is called it goes and check if a value exists and return true if the value exists or false if the value doesnt exist. Lastly I have a 4th function called "PresaveAction" what this function does is check if a value is "yes" or "no", if "no" it returns true and allows me to save and what I want to achieve is if the value is "yes" call the "success" function from before and depending if "success" returns true or false allow me to save. So how do I pass to the PreSaveAction function what "success" return?
function ViewItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('demoTrainingRoom2');
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, time2)');
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
for(var i = 0; i < this.allItems.get_count(); i++){
var item = this.allItems.get_item(i);
console.log(item.get_item('time2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('time2')){
alert('There is an event with the same Start Date on DemoTrainingRoom2' + ' ' + item.get_item('time2') + ' - ' + currentTitle );
return true; // or item
}
}
return false;
}
function failed(sender, args) {
alert("failed. Message:" + args.get_message());
}
function PreSaveAction() {
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
alert(time + " Current Start Time");
if(SPUtility.GetSPField('demoField').GetValue() == "no")
{
alert('No need for validation');
return true; // save file
}
else
{
alert('Need to validate date');
//here is where i need to call the result from success
return false; // don't save file
}
}
#Thriggle are you suggestion something like this
var result; //global variable
function ViewItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('demoTrainingRoom2');
var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, time2)');
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
for(var i = 0; i < this.allItems.get_count(); i++){
var item = this.allItems.get_item(i);
console.log(item.get_item('time2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('tiempo2')){
alert('There is an event with the same Start Date on DemoTrainingRoom2' + ' ' + item.get_item('time2') + ' - ' + currentTitle );
var result = "Yes";
return true; // or item
}
}
var result = "No";
return false;
}
function failed(sender, args) {
alert("failed. Message:" + args.get_message());
}
function PreSaveAction() {
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
alert(time + " Current Start Time");
if(SPUtility.GetSPField('demoField').GetValue() == "no")
{
alert('No need for validation');
return true;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes" && result == "Yes")
{
alert(result);
//return false;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes" && result == "No")
{
alert(result);
//return false;
}
}
This is how i did it
var originalSaveButtonClickHandler = function(){};
$(document).ready(function () {
var saveButton = $("[name$='diidIOSaveItem']") //gets form save button and ribbon save button
if (saveButton.length > 0) {
originalSaveButtonClickHandler = saveButton[0].onclick; //save original function
}
$(saveButton).attr("onclick", "PreSaveAction2()"); //change });
});
//override the default PreSaveAction
//custom PreSaveAction
function PreSaveAction2(callback) {
alert("iniciando validacion");
var time = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
if(SPUtility.GetSPField('demoField').GetValue() == "no") {
alert('No need for validation');
originalSaveButtonClickHandler();
//return true;
}
else if(SPUtility.GetSPField('demoField').GetValue() == "yes") {
var resultado1 = ViewItem('demoTrainingRoom2').then(
function(allItems) {
var currentTitle = SPUtility.GetSPFieldByInternalName('EventDate').GetValue();
var res = "No";
for (var i = 0; i < allItems.get_count(); i++) {
var item = allItems.get_item(i);
console.log(item.get_item('tiempo2') + ' - ' + currentTitle );
if (currentTitle == item.get_item('tiempo2')){
res = "Si";
console.log('There is an event with the same Start Date on DemoTrainingRoom2'
+ ' ' + item.get_item('tiempo2') + ' - ' + currentTitle);
}
}
if (res == "Si") {
alert(res + " there's an event on room 2");
//return false;
} else {
alert(res + " no event on 2");
originalSaveButtonClickHandler();
//return true;
}
},
function (sender, args) {
alert("failed. Message:" + args.get_message());
}
);
}
}
function ViewItem(listTitle) {
var deferred = $.Deferred();
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var query = SP.CamlQuery.createAllItemsQuery();
var allItems = list.getItems(query);
context.load(allItems, 'Include(Title, EventDate, tiempo2)');
context.executeQueryAsync(
Function.createDelegate(this,
function () { deferred.resolve(allItems); } ),
Function.createDelegate(this,
function (sender, args) { deferred.reject(sender, args); }));
return deferred.promise();
}

working with array(s) in JQuery

I am inputting values into an array in jQuery like 1,4,7,3. But when I am displaying the array values, it displays like 1,3,4,7.
i need like 1,4,7,3 as it is when they were inserted. This is my code.
var selectedValues = [];
var $ctrls = $("[id*=chkProcessRoutes] input:checkbox");
$("[id*=chkProcessRoutes] input:checked").each(function () {
var l = parseFloat(($ctrls.index($(this))));
var ll = parseFloat(l) + 1;
selectedValues.push(parseFloat(ll));
});
if (selectedValues.length > 0) {
alert("Selected Value(s): " + selectedValues.toString());
} else {
alert("No item has been selected.");
}
Try this:
var selectedValues = $("[id*=chkProcessRoutes] input:checked").map(function () {
return $(this).val();
});
if (selectedValues.length > 0) {
alert("Selected Value(s): " + selectedValues.toString());
} else {
alert("No item has been selected.");
}

jquery click function inside a each loop

I have this code below i am trying to get the id from within the click function but this.id does now work from within the click function i think because the code does not run until clicked does anyone know a way to get the id at the time the each loop runs?
$(html).each(function() {
if($( this ).filter('.target').html()){
window["button"+this.id] = {
text: "Edit "+$($(html).filter('#'+this.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#'+this.id).html()).filter('#B2').text());
var start = $($( html ).filter('#'+this.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#'+this.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#'+this.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#'+this.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#'+this.id).html()).filter('#A9').text();
if(PM == '1') { $('#PM').prop('checked', true); }else{ $('#PM').prop('checked', false); }
var NS = $($(html).filter('#'+this.id).html()).filter('#NS').text();
if(NS == '1') { $('#NS').prop('checked', true); }else{ $('#NS').prop('checked', false); }
var RDO = $($(html).filter('#'+this.id).html()).filter('#A12').text();
if(RDO == '1') { $('#RDO').prop('checked', true); }else{ $('#RDO').prop('checked', false); }
var OrdHours = $($(html).filter('#'+this.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#'+this.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#'+this.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#'+this.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#'+this.id).html()).filter('#A7').html();
$("#total").html(totalhrs +"<br />" +total);
adjustmentID = $($(html).filter('#'+this.id).html()).filter('#B1').text();
no_adjustment = false;
$( this ).dialog( "close" );
}
}
newArray.push(window["button"+this.id]);
}
});
Define this as a variable to keep your scope
var self = this;
full example below
$(html).each(function() {
var self = this;
if ($(self).filter('.target').html()) {
window["button" + self.id] = {
text: "Edit " + $($(html).filter('#' + self.id).html()).filter('#A1').text(),
click: function() {
$('#2').html($($(html).filter('#' + self.id).html()).filter('#B2').text());
var start = $($(html).filter('#' + self.id).html()).filter('#A1').text();
$("#start").val(start);
var finish = $($(html).filter('#' + self.id).html()).filter('#A2').text();
$("#finish").val(finish);
var breaktime = $($(html).filter('#' + self.id).html()).filter('#A3').text();
$("#break").val(breaktime);
var grade = $($(html).filter('#' + self.id).html()).filter('#A4').text();
$("#grade").val(grade);
var PM = $($(html).filter('#' + self.id).html()).filter('#A9').text();
if (PM == '1') {
$('#PM').prop('checked', true);
} else {
$('#PM').prop('checked', false);
}
var NS = $($(html).filter('#' + self.id).html()).filter('#NS').text();
if (NS == '1') {
$('#NS').prop('checked', true);
} else {
$('#NS').prop('checked', false);
}
var RDO = $($(html).filter('#' + self.id).html()).filter('#A12').text();
if (RDO == '1') {
$('#RDO').prop('checked', true);
} else {
$('#RDO').prop('checked', false);
}
var OrdHours = $($(html).filter('#' + self.id).html()).filter('#A5').text();
$("#ordhrs").val(OrdHours);
var x150 = $($(html).filter('#' + self.id).html()).filter('#A11').text();
$("#OTx150").val(x150);
var departmentID = $($(html).filter('#' + self.id).html()).filter('#A6').text();
$("select#ChangeDeparment").val(departmentID);
total = $($(html).filter('#' + self.id).html()).filter('#A8').html();
totalhrs = $($(html).filter('#' + self.id).html()).filter('#A7').html();
$("#total").html(totalhrs + "<br />" + total);
adjustmentID = $($(html).filter('#' + self.id).html()).filter('#B1').text();
no_adjustment = false;
$(self).dialog("close");
}
}
newArray.push(window["button" + self.id]);
}
});

Categories