On a project I'm currently working on, I'm using radio buttons and AJAX to change the posts displayed on a custom WordPress template page. It works perfectly, however, the client would like it to be checkboxes instead of radio inputs so that each time a user selected a new category, it adds to the posts being displayed instead of replacing it.
For example: currently, if you click category1, category1 posts show up. Click category2, and category2 posts replace the category1 posts. The client would like BOTH category1 and category2 to show up if both checkboxes are selected.
Here's my JS currently:
jQuery(document).ready(function ($) {
// AJAX Post Filter scripts
var $checkbox = $("#filter input:checkbox");
var $checked = $("#filter input:checkbox:checked");
var $unchecked = $("#filter input:checkbox:not(:checked)");
$checkbox.change(function () {
if ($checked) {
var catID = $(this).val();
$.ajax({
type: 'POST',
url: afp_vars.afp_ajax_url,
data: {
"action": "load-filter",
category__in: catID
},
success: function (response) {
$(".filter-section").empty().html(response);
return false;
console.log('success!');
}
});
console.log(catID);
}
});
});
I'm pretty sure I need to do something with .map() with my variable catID as I've seen in some other threads, but I haven't been able to find a solution that works quite right for me.
edit: I realized I needed to clarify what I have tried.
I've used the following code:
var catID = $(this).map(function () {
return $(this).val();
}).get();
But all it does is replace the variable value with the new checkbox value. I need to add to the value without erasing the already checked values. Then if a checkbox is unchecked, I need to remove the value from the array.
I would try something like this:
let categoryIDs = [];
$('.checkbox').click((e) => {
let id = e.currentTarget.id
$(selector).html('')
categoryIDs.indexOf(id) === - 1 ? (
categoryIDs.push(Number(id))
) : (
categoryIDs = categoryIDs.filter((item) => item !== id )
)
console.log(categoryIDs)
categoryIDs.forEach((item) => {
//ajax calls here
//$.ajax({blah blah}).done(res => {
//$(selector).append(res)
//})
console.log(item);
})
})
See it in action here:
https://jsfiddle.net/mwypd9ve/
This way the IDs you want to display are always in the array, and every time the array changes the page will reflect only the content matching the IDs in the array (because you clear the section .html('') then in the loop append each ajax response
Related
I have a data, when I update the data (using modal), select option work correctly
When I close the modal, and I click the edit button again, something wrong with select option:
This is my edit modal ajax:
// Function for edit modal plan schedule
$('body').on('click', '.editPlanSchedule', function() {
var Item_id = $(this).data('id');
$.get("/quotation/getEditPlanSchedule" + '/' + Item_id, function(data) {
console.log(data['product_plan']);
$('.modal-title-edit').html("Edit Plan Schedule Item");
$('#saveBtn').val("Update");
$('#updatePlanSchedule').modal('show');
$('#id').val(data['data'].id);
$('#qno').val(data['data'].qno);
$('#b_amount').val(data['data'].b_amount);
// $('#product_plan_edit').val(data.product_plan);
data['product_plan'].forEach(function(item, index) {
$('#product_plan_edit').append($('<option>', {
id: item.id,
value: item.productplanID,
text: item.productplanID
}));
if(data['data'].product_plan == item.productplanID){
$('#'+item.id).attr('selected',true);
}
});
})
});
This is the method from controller:
public function getEditPlanSchedule($id)
{
$item['data'] = QuotationPlanSchedule::find($id);
$item['product_plan'] = ProductPlan::orderby('id', 'asc')->get();
return response()->json($item);
}
You have to clear all options before adding again:
$("#product_plan_edit").empty();
Either .empty the container or don't use append (better for the DOM update)
I am a little confused about your use of data['data'].product_plan to test the ID. In any case you can see the principle
$('#product_plan_edit').html(
data['product_plan'].map(item => `<option value="${item.productplanID}">${item.productplanID}</option>`).join('')
);
$('#product_plan_edit').val(data['data'].product_plan); // select item.productplanID === data['data'].product_plan
QUESTION
Currently, I have a working ajax script which when a value in the first drop down is selected, it runs the ajax script to populate the second drop down. However, the second select does not actually run/populate until you click on that second drop down - the first time you click it, it will say "no results", and then you click on it again, and it loads the list, rather than populating immediately when the first drop down value is selected.
How might I go about making the second drop down populate immediately, or alternatively go about adding a spinner or disable pet_breed or something similar until the second drop down loads the values so 'no results' doesn't show after the type_taxonomy value has been selected?
I'm sorry but I have very little experience with javascript...
taxonomy setup
// Custom Taxonomy (First Select Box) - type_taxonomy
parent => false
values => Cat
Dog
// Custom Taxonomy (Second Select Box) - breed_taxonomy
parent => Cat
child => Cat Breed 1
Cat Breed 2
Etc...
parent => Dog
child => Dog Breed 1
Dog Breed 2
Etc...
existing code - audp-select-breed.js
(function( $ ) {
'use strict';
$(function($) {
$('#pet_type').on('change', function() {
var petType = $(this).val();
if ( petType != '' ) {
var data = {
'action': 'audp_select_pet_breed',
'pet_type': petType
}
$.post(audp_select_pet_breed_obj.ajaxurl, data, function(response) {
$('#pet_breed').html(response);
});
}
});
});
})( jQuery );
I just added disabled functions in the appropriate code lines to ensure that the select box could not be accessed until the data had loaded.
(function( $ ) {
'use strict';
$(function($) {
$('#pet_type').on('change', function() {
$('#pet_breed').prop('disabled', true); // Disables While Values Load
var petType = $(this).val();
if ( petType != '' ) {
var data = {
'action': 'audp_select_pet_breed',
'pet_type': petType
}
$.post(audp_select_pet_breed_obj.ajaxurl, data, function(response) {
$('#pet_breed').html(response);
$('#pet_breed').prop('disabled', false); // Enables After Values Load
});
}
});
});
})( jQuery );
I have a Jquery DataTable with multiselect ability. Moreover there is a button and a div element:
<script>
$(document).ready(function() {
var tablemovChAf = $('#movChAf').DataTable({
//multiselect
$('#movChAf tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
} );
})
</script>
<button name="sbmsimulate" class="button-input btn btn-info" id="sbmsimulate" style="info" type="button" >
<div id="divAccMovement"></div>
What I want is to send all the selected rows to "accMovement.jsp" by clicking on the button.
$('#sbmsimulate').click( function () {
$('#divAccMovement').load('accMovement.jsp',{
mode:"2",
arrayData:tablemovChAf.rows('.selected').data()
});
} );
my jsp accMovement.jsp looks like this;
<%
String str_mode=request.getParameter("mode").toString();
String[] arrayData=null;
if (str_mode.equals("2")) {
arrayData=request.getParameterValues("arrayData[]");
}
%>
I tried the solution of : Passing javascript array to servlet (In fact, that is what I have done) but it didnt work for me. Nothing happens when I click the button.
I was debugging, and it seems the problem is with:
arrayData:tablemovChAf.rows('.selected').data()
because, if it is commented (and the "if" statement in the jsp is commented also) it is working. However what I need is to send the selected rows to the jsp page.
What is the correct way to send the array from the client and receive the array on the server?
Thanks in advance.
I found a solution not so smart for my case (following this jQuery DataTables Getting selected row values), it does not exactly what I need, but I can add some statements later in order to achive my goal
$('#sbmsimulate').click( function () {
var ids = $.map(tablemovChAf.rows('.selected').data(), function (item) {
return item[11]
});
$('#divAccMovement').load('accMovement.jsp',{
mode:"2",
arrayData:ids
});
} );
The column of index 11 is the id of my dataTable, so in the server side I can get all the information about every row.
However I would like to avoid that step:
var ids = $.map(tablemovChAf.rows('.selected').data(), function (item) {
return item[11]
});
and specify everything in the parameter, something like this :
arrayData:tablemovChAf.rows('.selected').data()
So I have this gridview:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'symptoms-grid',
'selectableRows'=>1, //ability to select one symptom at a time
'dataProvider'=>$model->search(),
'htmlOptions'=>array('id'=>'symptomsSearchgrid'),
'columns'=>array(
'symptomCode',
'title',
'inclusions',
'exclusions',
'symptomCategory',
),
)); ?>
And this javascript....script:
Yii::app()->clientScript->registerScript('search', "
$( document ).ready(function() {
$('#symptomSelectDiv').hide();
$('#categorySelectDropDown').change(function(){
$('#symptomSelectDiv').show();
$('#symptoms-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
$('#symptomsSearchgrid table tbody tr').on('click', function() {
var firstColVal = $(this).find('td:first-child').html();
$('#symptomToBeSearched').val(firstColVal);
});
});
");
My problem is that I can only either get the
$('#symptoms-grid').yiiGridView('update', {
data: $(this).serialize()
});
function to work or the:
$('#symptomsSearchgrid table tbody tr').on('click', function() {
var firstColVal = $(this).find('td:first-child').html();
$('#symptomToBeSearched').val(firstColVal);
});
one, and it seems quite random too. Basically in order to get the other function to "start working" I have to change the id (either the grid id or the DOM id) of one function to something different for the other function to work (while the other doesn't).
So let's say at first the update function works and the click function doesn't. Then I change the ID of update to something wrong and click works. Then I change the id of update back to the correct one, but it still doesn't work, yet click works. THen I change click to a wrong id and update starts working correctly. But again, if I change click to the correct id it doesn't work.....
Any ideas what I'm doing wrong?
I think your issue is that your are giving your grid two id's one when creating it and one in htmloption.
I'm trying to sort out this problem but have yet to get results. I tried to get the exact id values of the row which I edit in order to perform an update.
I can get get my current cell value but I can't get the corresponding id values of the cell. I iterate over the table id value which in turn get's all the id values of the table.
I'm using this jquery code for iteration:
$('#table').ready(function() {
$(this).find('.filename').each( function() {
alert($(this).html());
})
})
Then I tried this simple JavaScript:
var fid= document.getElementById("filename").textContent;
It gets only the first id value of the table.
For example, if I edit the first row the id value is 53.
If I edit the second row the id value should be 52 but it gets only 53.
See this link, I have posted this question previously.
getElementById gets the element and not the id. The id is what you are providing as parameter.
You could simply do:
$('#table').ready(function() {
$(this).find('.filename').each( function() {
alert(this.id);
}) ;
});
Instead of cluttering the DOM with id's (which should always be unique) you could always use the data-attributes of elements:
<tr data-identifier="53"><td></td></tr>
$('#table').ready(function() {
$(this).find('.filename').each( function() {
// if this is the row
alert($(this).data('identifier'));
}) ;
});
I am not quite sure that i understand your question but this will give you ids of all cells within a table:
$("#table > td").each(function(){
alert($(this).attr("id"));
});
hi thanks for ur response ,i tried a different script and it was working as i thought
here is the code
function doubleclick(table,id1)
{
table.innerHTML="<input type=text name=tab onBlur=\"javascript:submitNewName(this,'"+id1+ "');\" value=\""+table.innerHTML+"\">";
table.firstChild.focus();
// alert(id1);
}
function submitNewName(text,id2)
{
text.parentNode.innerHTML=text.value;
$.ajax({
url: 'update',
data:{text1:text.value,fileid1:id2},
type:"POST",
dataType:"json",
error:function(data){
//alert('error')
},
success: function(data) {
//alert('updated!')
}
});
}
html:
//when double clicked it will pass both ${item.filedesc},${item.id}
<td ondblclick="javascript:doubleclick(this,${item.id});" >${item.filedesc}</td>