Preventing X numbers from select - javascript

I have a script running to show a number in the select list options when the user check one specific value it will display a number refering to how much times he can pay his bill.
Note this code:
var tabelaParcelas = [2,3,4,6,8,10,12];
$(document).ready(function(){
update();
});
$('input[type=checkbox]').click(function(){
update();
})
function update(){
var list = $('#instNum2'); // use selector only once whenever possible for better performance
// clear any existing options from the dropdown list
list.html("")
// count checked boxes
var checked_boxes = 0
$(".check_list").each(function(){
if(this.checked){
checked_boxes++;
}
});
// append options to the select list
for(var i=0;i<checked_boxes;i++){
var option = $("<option>", {value: tabelaParcelas[i], "text": tabelaParcelas[i]});
list.append(option);
}
}
That's correct! But the thing is, I need to display 1x as well, and that's what's not showing at all, 1x should be visible always no matter how much boxes you select, and other thing, when I select more than 7 boxes, the option keep producing empty options, while it should only keep displaying 12x without appending any new...

var tabelaParcelas = [2,3,4,6,8,10,12];
$(document).ready(function(){
update();
});
$('input[type=checkbox]').click(function(){
update();
})
function update(){
var list = $('#instNum2'); // use selector only once whenever possible for better performance
// clear any existing options from the dropdown list
list.html("")
// count checked boxes
var checked_boxes = 0
$(".check_list").each(function(){
if(this.checked){
checked_boxes++;
}
});
//add limit to check_boxes
//This section was not in original code
// Could also do if(checked_boxes > tabelaParcelas.length) {checked_boxes = tabelaParcelas.length;}
//Would make it more dynamic.
//This is added to limit the number of options added to the length of the array at the top.
//This will prevent blank options from being added as requested in the question.
if(checked_boxes > 6) {
checked_boxes = 6;
}
//add 1x option to empty list
//This was not in original code
//This was added as the list was cleared when this function is run and they always wanted 1x to appear as an option.
list.append("<option value='1' selected>1</option>");
// append options to the select list
for(var i=0;i<checked_boxes;i++){
var option = $("<option>", {value: tabelaParcelas[i], "text": tabelaParcelas[i]});
list.append(option);
}
}

Related

EditableGrid - How to make every column header into individual filter

I am using EditableGrid (http://www.editablegrid.net/) Which creates some nice looking Editable tables
I'm Trying to modify the table header to make them into Individual filters like in example - https://phppot.com/demo/column-search-in-datatables-using-server-side-processing/
Current Filter textbox works very nicely but has a limit for searching one value for all columns.
I find many solutions for an individual column filter but I don't want to use other tables as they do not provide inline table editing functionality with dropdown and date picker, Is there a way I can implement it in EditableGrid?
I have also Asked this Question on Github (https://github.com/webismymind/editablegrid-mysql-example/issues/66) but the thread is not been active for a long time so I have very little hope of getting a solution from there.
In index.html update this code: see where //new code ---- starts and //new code ---- ends, try it out..
<script type="text/javascript">
var datagrid;
window.onload = function() {
datagrid = new DatabaseGrid();
//new code ---- starts
var list = document.getElementsByTagName("thead")[0];
for(var i = -1; i < list.childNodes.length; i++){
var input = document.createElement("input");
input.type = "text";
input.className = "filter";
list.getElementsByTagName("th")[i+1].appendChild(input);
}
var z = document.getElementsByClassName('filter')
for(var i = 0; i< z.length; i++){
z[i].addEventListener("input", function(e){
datagrid.editableGrid.filter( e.target.parentNode.querySelector("input").value, [i]);
})
}
//new code ---- ends
// key typed in the filter field
$("#filter").keyup(function() {
datagrid.editableGrid.filter( $(this).val());
// To filter on some columns, you can set an array of column index
//datagrid.editableGrid.filter( $(this).val(), [0,3,5]);
});
$("#showaddformbutton").click( function() {
showAddForm();
});
$("#cancelbutton").click( function() {
showAddForm();
});
$("#addbutton").click(function() {
datagrid.addRow();
});
}
$(function () {
});
</script>

how to get previously selected rows of a bootstrap dataTable while searching

I have used a bootstrap DataTable to show data. At the same time i have a HTML checkbox as a column of that dataTable. I have a submit button to get the selected checkbox's value to do some stuff. I am fetching the following problem while select checkboxes under searching.
When i select all checkboxes and Click Save button I got all the values. It works as my expectation.
But Unexpected occures when i search via built-in search box of bootstrap dataTable.Here is the pictorial view
In this case when i press Save i got just the two value though all other values are still selected. How can i get all the selected values while searching
Here is my jquery code of Save button of getting the checkboxes value
$("#btnSave").click(function () {
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
....
//Other stuff
....
}
Please help me.
When you are doing a search, it is going to check only for the rows, that satisfy the given criteria. So your search logic works like this
if(searchCriteria==true)
{
showValue
}
Even if you had previously selected values it won't be showing all of them, because they don't satisfy the given criteria. Now in this case when you click on Save, it is taking only those rows in the datatable which are checked and satisfy the given criteria, as per your java script.
Now if you still wish, that all selected values should be taken in, there is one way you can try, put the selected values in some kind of List or Set, and place the list object in session. So everytime you click on Save, you can retrieve the List from the session. But I really don't see why you would want to do it, unless you need to retrieve the selected values every time.
I got my job done like this
var table = $('#tblReportList').dataTable();
When i was searching through dataTable, i was getting just the selected values matching the search criteria. But the previously selected values was disappeared. To get the previously selected value i used the following code...
table.$('input[type="checkbox"]').each(function () {
if (!$.contains(document, this)) {
if (this.checked) {
previousVal = previousVal + ',' + this.value;
}
}
});
Now, for getting the selected values of search I used the previous code posted before. And that was
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
So all selected checkbox's values are
var allValues=previousVal+vals;

javascript counter increment is a bit wrong

I have the following javascript http://jsfiddle.net/847Kf/4/ that contains a counter at line 14 and 36. The code works but when i delete an item that i added and add a new item the counter continues from where it left.
For example: i insert 4 items 1 , 2 , 3 , 4 now i delete the second item and add a new item so i will have 1 , 3 , 4 , 5. How can i make that counter when i delete an item the counter should reset and redisplay the values according the example:
1, 3, 4, 5 - deleted an item and now the counter should change the values for the remaining item to: 1, 2, 3, 4.
HTML:
<ul class="tags" data-prototype="<div><label class=" required">__name__</label><div id="task_tags___name__"><div><label for="task_tags___name___name" class=" required">Name</label><input type="text" id="task_tags___name___name" name="task[tags][__name__][name]" required="required" maxlength="255" /></div></div></div>">
</ul>
Javascript:
// setup an "add a tag" link
var $addTagLink = $('Add a tag');
var $newLinkLi = $('<li></li>').append($addTagLink);
jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
var $collectionHolder = $('ul.tags');
// add the "add a tag" anchor and li to the tags ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see code block below)
addTagForm($collectionHolder, $newLinkLi);
});
});
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
// Replace '$$name$$' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<li></li>').append(newForm);
// also add a remove button, just for this example
$newFormLi.append('x');
$newLinkLi.before($newFormLi);
// handle the removal, just for this example
$('.remove-tag').click(function(e) {
e.preventDefault();
$(this).parent().remove();
return false;
});
}
The main problem is on how you count the elements.
When creating a new tag, you update the quantity on the data, but it doesn't get noticed when deleting.
You have two options:
Update on the removal the value $collectionHolder.data('index', index - 1)
take the quantity on each creation, not setting it on document ready
I've noticed another issue with deleting. When you you create every element, you are attaching a delete event to every .remove-tag in the DOM, on the 3rd creation, the first element would have 3 events attached, and the 2nd two.
Two avoid that I'd do something like:
$('ul.tags').on('click','.remove-tag',function(e){
e.preventDefault();
$(this).parent().remove();
})
What that means is something like "Look on dom for ul.tag, and if a click event is triggered on a .remove-tag do this" so it keeps alive and active for the new tags created.
Because you have so many id's / name's / class's etc which incorporate the index. I would recommend regenerating the list on delete.
ie:-
function regenerateTagList(){
var vals = $('.tags li.tag input').toArray().map(function(v, i) { return v.value; });
$('.tags li.tag').remove();
$('ul.tags').data('index', 0);
for(var i = 0; i < vals.length; i++){
addTagForm($('ul.tags'), $newLinkLi);
$('.tags li.tag input:last').val(vals[i]);
}
}
And add a class to the li for the tag so you can select them from the add link:-
var $newFormLi = $('<li></li>', { class:"tag" }).append(newForm);
then call after you remove:-
$('.remove-tag').click(function(e) {
e.preventDefault();
$(this).parent().remove();
regenerateTagList();
return false;
});
Working Fiddle
This modification will do the change without regenerating the whole thing:
$('.remove-tag').click(function(e) {
e.preventDefault();
$(this).parent().remove();
var count = 0;
$('.tags li').each(function() {
$(this).find('div label').first().text(count);
count++;
});
return false;
});
It finds all the li's, then finds the first label in each li and changes it to the count variable. It could be simplified if the first label had a class called 'count'.

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

Prevent checkbox tick after Nth selection (allow more from the same category)

We have checkboxes in two columns (they denote the same category, but different subscription)
We would like to limit the selection to 4. We have a jQuery code to disable the checkbox selection after the user selected 4.
But now we need to have the following logic:
Allow the user to choose both values from the same rows (aka: subscribe to both subscriptions from the same category) and do not count in the 4 limit we have if they have chosen more from the same row.
So if you look in the following screencast, we would like to be able to select the first checkbox (1st row).
The code we used was:
$("input:checkbox").click(function() {
var bol = $("input:checkbox:checked").length >= 4;
$("input:checkbox").not(":checked").attr("disabled",bol);
});
A jsFiddle has been created to reflect the current state of work:
http://jsfiddle.net/fFbLx/
Feel free to name the classes, inputs as you wish.
I think you would have to "categorise" them by the LI then. So count the LI's with an checked box - disable all others if more than 4 active.
See: http://jsfiddle.net/fFbLx/4/ (maybe give the UL's a class, so you can use the selector on that)
$("input:checkbox").click(function() {
var counter = 0;
$('li').each( function() {
if($(this).find("input:checkbox:checked").length)
{
$(this).addClass('active');
counter++;
} else {
$(this).removeClass('active');
}
});
var bol = counter >= 4;
$('li').not('.active').find("input:checkbox").not(":checked").attr("disabled",bol);
});
If you wrap your checkboxes in an element you can then use the jquery has selector filter to check how many have selected checkboxes:
$("input:checkbox").click(function() {
var bol = $(".myCheckboxWrapper:has(input:checkbox:checked)").length >= 4;
$("input:checkbox").not(":checked").attr("disabled",bol);
});
Try this http://jsfiddle.net/fFbLx/2/
$("input:checkbox").click(function() {
$(this).parent().find("input:checkbox:first").toggleClass("active");
var bol = $("input:checkbox:checked").length >= 4;
$("input:checkbox").not(":checked,.active").attr("disabled",bol);
});

Categories

Resources