dynamically generating checkbox list from json - javascript

I'm dynamically generating a list of checkboxes based on the contents of json data:
Format of tempfairway:
[{"FairWay":"A"},{"FairWay":"B"}, {"FairWay":"C"}, {"FairWay":"D"}]
var topics = tempfairway;
var topicContainer = $('ul#fairway_list');
$.each(topics, function (iteration, item) { topicContainer.append(
$(document.createElement("li")).append(
$(document.createElement("input")).attr({
id: 'topicFilter-' + item,
name: item,
value: item,
type: 'checkbox',
checked: true
})
//onclick
.click(function (event) {
var cbox = $(this)[0];
alert(cbox.value);
})
).append(
$(document.createElement('label')).attr({
'for': 'topicFilter' + '-' + item
}).text(item)
)
)
});
The checkboxes generate fine with the correct number but i'm getting [object Object] instead of the name of the fairway.
Any ideas on how to fix this?
Couple of more questions to add to this:
-What if i wanted to display ONLY unique values in tempfairway?
-.Click is set to get the value of that single checkbox, what if i want to iterate through all the checkboxes and get the value of all the ones that were selected in the case that the user unselected any of them?

In the line:
> $.each(topics, function (iteration, item) {
item is an object like {"FairWay":"A"}, so where you have:
> .text(item)
you probably want:
.text(item.FairWay)
and similarly for other uses of item. Or you could store the value in a variable and use that:
var fairwayName = item.FairWay;
...
.text(fairwayName);

Related

jQuery get all rows using table.rows().data().each with pagination

I can't find a solution online for this. I have my code like this
$('.validation-summary-table').dataTable({ paging: true, ordering: false });
const conflictsArray = pushConflictDatas('#conflict .validation-summary-table tbody tr.odd');
function pushConflictDatas(dataTableTr) {
let radioButtonsConflicts = new Array();
$(dataTableTr).each(function() {
const currentRow = $(this).closest("tr"); // CSV row
const nextRow = currentRow.next(); // DB row
let currentRowObj = {
Name: currentRow.find('td:eq(0)').text().trim(),
isChecked: currentRow.find('td:eq(1) input[type="radio"]').is(':checked')
}
let nextRowObj = {
Name: nextRow.find('td:eq(0)').text().trim(),
isChecked: nextRow.find('td:eq(1) input[type="radio"]').is(':checked')
}
radioButtonsConflicts.push([currentRowObj, nextRowObj]);
});
return radioButtonsConflicts;
}
This worked fine until I found out it wasn't getting all table rows on the next pages when I click a button, only the current page and nothing else. I need to get all the rows and push them to an array for my ajax request. So I found this code from their docs:
var table = $(conflictTable).DataTable();
table.rows('.odd').data().each(function (value, index) {
console.log('index: ', index)
console.log('value: ', value)
} );
However this only selects <tr> on the current page, just like what the old function does. If I move to the next page, it will "append" it. If I remove the selector .odd, it would get all the rows from all paginated pages, but I'm writing a code that targets the next row and I want to only select rows with a specific class name before I do such. How do I do this?
You can use the following code to get all table data:
let table_data = table.rows({ search: 'applied'}).data();

Set the field values to the values from the selected record in tree Extjs

In my application, the two components Ext.tree.Panel and Ext.form.Panel
When I click on the tree entry I need to set the field values ​​to the values ​​from the selected record.
When I click on the entry, the event handler function in the controller is triggered:
...
showDataFields: function(view, record, item, index, event) {
//got a form with fields
var panel = view.up('mainpanel');
var formfield = panel.down('mainform');
//got the selected entry in the tree
sel = view.getSelectionModel().getSelection()[0];
console.log(sel)
//How to assign values from selected record to form fields?
}
...
How can i do this?
Example in fiddle
The showDataFields method in the controller file on line 37
You can use loadRecord, which will map your record data to your form by name property. First retrieve form and then set your record to it:
showDataFields: function(view, record, item, index, event) {
...
var form = panel.down('storagepaneltype');
form.loadRecord(record);
}
Also, you need to change "name" property from name to text to make form match record property. In Fiddle.view.StoragePanel:
items: [{
xtype: 'textfield',
name: 'text', //<-- here
fieldLabel: 'Наименование',
itemId: 'name_field',
value: '',
//bind: '{person.name}'
}
Here's the FIDDLE

How to perform .delete() queryset in Django in a ListView?

Here is what I've done so far:
1.) I've made a javascript function that gets all the id's of the items (using checkbox select) in the database like so (this is DataTables):
function () {
// count check used for checking selected items.
var count = table.rows( { selected: true } ).count();
// Count check.
// Count must be greater than 0 to delete an item.
// if count <= 0, delete functionality won't continue.
if (count > 0) {
var data = table.rows( { selected: true } ).data();
var list = [];
for (var i=0; i < data.length ;i++){
// alert(data[i][2]);
list.push(data[i][2]);
}
var sData = list.join();
// alert(sData)
document.getElementById('delete_items_list').value = sData;
}
}
It outputs something like 1,2,5,7 depending on what rows I have selected.
2.) Passed the values inside a <input type="hidden">.
Now, I've read a post that says you can delete data in Django database using a checkbox, but I'm not sure how exactly can I use this.
I'm guessing I should put it in the ListView that I made, but how can I do that when I click the "Delete selected items" button, I can follow this answer?
I'm trying to achieve what Django Admin looks like when you delete items.
My ListView looks like this:
Yes you can use linked example. Django Admin do it the same way, You send selected ids and django do filtering by given values and after django apply selected action for selected items.
UPDATE
For example.
class List(ListView);
def post(self, request, *args, **kwargs):
ids = self.request.POST.get('ids', "")
# ids if string like "1,2,3,4"
ids = ids.split(",")
try:
# Check ids are valid numbers
ids = map(int, ids)
except ValueError as e:
return JsonResponse(status=400)
# delete items
self.model.objects.filter(id__in=ids).delete()
return JsonResponse({"status": "ok"}, status=204)
And html:
<button id="delete-button">Del</button>
<div id="items-table">
{% for object in objects_list %}
<div class="item" data-id="{{object.id}}">{{ object.name }}</div>
{% endfor %}
</div>
<script>
$(function(){
$('#delete-button').on('click', function(e) {
// Get selected items. You should update it according to your template structure.
var ids = $.map($('#items-table item'), function(item) {
return $(item).data('id')
}).join(',');
$.ajax({
type: 'POST',
url: window.location.href ,
data: {'ids': ids},
success: function (res) {
// Update page
window.location.href = window.location.href;
},
error: function () {
// Display message or something else
}
});
})
})();
</script>

.show() not working jquery

I have a filter class that filters products residing inside the page.There is a function that works if someone checks the filters.
Filters are check-boxes where every check box contains different value.
What my filter function do is that it checks all the checked checkboxes from the page and then uses the data-* global variable present on the list tages to decide what element to show.
DOM structure of the items will be:
<body>
<ul class="products">
<li class="product" data-company="something" data-flavour="something"></li>
<li class="product" data-company="something" data-flavour="something"></li>
.
.
.
.
<li class="product" data-company="something" data-flavour="something"></li>
</ul>
</body>
Below one shows the the function that does the job.
this.filterGridProducts = function() {
$.ajax({
type: 'POST',
url: 'test12.php',
data: category,
success: function(data) {
$('#limitpage').html(data);
// $('.product').hide();
var filteredProducts =$('.product');
//filter by colour, size, shape etc
var filterAttributes = $('input[type="checkbox"]');
var selectedFiltersValues = [];
// for each attribute check the corresponding attribute filters selected
filterAttributes.each(function() {
if (this.checked) {
var currentFilter = $(this);
selectedFiltersValues.push("[data-" + currentFilter.attr('name') + "='" + currentFilter.val() + "']");
filteredProducts = filteredProducts.filter(selectedFiltersValues.join(','));
}
});
filteredProducts = filteredProducts.filter(function() {
return ($(this).attr('data-price') > first && $(this).attr('data-price') <= second);
});
//console.log($('.product').show());
filteredProducts.each(function(e) {
console.log($(this).html().show()); // not working
$(this).show(); // not working
})
filteredProducts.show(); // this one is not working as well.
}
});
};
filteredProducts does contain the elements that need to be filtered but I can't seem to show it.
Ajax call in the above functions loads all the elements present inside the db, The products that come from it are all hidden.
What could be the possible reason for the .show() to not work?
Update:

How the rails select box selected option is giving from coffee file

In a js.coffee file after an ajax success, i need to put values to a select box with selected a particular name.
_form.html,erb :
<%= f.select(:user_id, Item.find(session[:login_users_item_id]).try(:users).order_by_fullname.collect {|u| [ u.full_name, u.id ] }, selected: current_user.id)%>
items.js.coffee:
$.ajax '/users.json',
type: 'GET', data: {"from_prod_bu" : selecteditemId},
success: (data) ->
userSelectBox = $('#prod_user_id')
userSelectBox.html('')
if data.length == 0
userSelectBox.append($('<option>').text('').attr('value', ''))
else
$.each data, (index,el) ->
userSelectBox.append($('<option>').text(el.firstname+' '+el.lastname).attr('value', el.id))
Now, the user fullname is listing in the select box, but how can i give the selected option for displaying a particular username .
Thanks
The selected option is set by using the selected attribute.
Suppose that the id of the user to be selected is stored in the selectedUserId variable within your JavaScript - then the following code should work:
success: (data) ->
userSelectBox = $('#prod_user_id')
userSelectBox.html('')
if data.length == 0
userSelectBox.append($('<option>').text('').attr('value', ''))
else
$.each data, (index, el) ->
option = $('<option>')
.text(el.firstname + ' ' + el.lastname)
.attr('value', el.id)
if el.id == selectedUserId
option.attr 'selected', 'selected'
userSelectBox.append option
See here for more details on setting the selected attribute with jQuery.

Categories

Resources