Select with editable-select class not work on appending - ajax

I have a select option that will populate options with the help of ajax and jsonencode. My code works fine, however if I add a class editable-select, which is super helpful in my project, append doesn't work.
here is my code without editable select, working fine
<select name="UM" id="UM" class="form-control" required></select>
and here is when I add a class editable-select
<select name="UM" id="UM" class="form-control editable-select" required></select>
and below is my ajax to populate
$('#UM').on('click',function(e){
$.ajax({
url: '/Files/populate_units',
type: 'get',
success:function(response){
var data = $.parseJSON(response);
var len = data.length;
$("#UM").empty();
for( var i = 0; i<len; i++){
var um = data[i]['UM'];
$("#UM").append("<option value='"+um+"'>"+um+"</option>");
}
}
});
});
below is my code for getting the values from database, this is working fine
public function PopulateUnits(Request $request){
$units = Units::all();
$um = [];
foreach($units as $unit){
$um[] = [
'id' => $unit->id,
'UM' => $unit->UM,
];
}
echo json_encode($um);
}
does the class editable-select has something to do why .append doesn't work ? because if I remove them the encoded json works fine and append perfectly on my select option. pls help me, thanks

Related

Can't set multiple selected value select2 on edit mode

I'm trying to load selected values from db and set it on the select2. i'm using the select2 4.0.10 version. im loading the data using ajax and set the select option to the select2 element after the document is ready.
so, i tried using the $("#area").val(selectedValues).trigger("change"); but nothing seems to be selected.
here is some code of my view.
<input class="form-control" type="text" id="sourceValues" value="CMS,KDY,RWG">
here is my select2 element
<div class="form-group row">
<label class="col-md-3" for="area">Area Tagih Kolektor</label>
<div class="col-md-9">
<select id="area" class="js-example-basic-multiple form-control" name="area[]" multiple="multiple" required>
</select>
</div>
</div>
and here is my script for set the selected values.
<script>
$(document).ready(function(){
nav_active();
var selectedValues = ["CMS","KDY","RWG"];
$('.js-example-basic-multiple').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true
});
console.log(selectedValues);
//Date picker
$('#tgl_berlaku').datepicker({
autoclose: true
})
//Prevent enter to submit
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
alertify.error('Untuk melakukan submit form, tekan tombol "Simpan"!');
return false;
}
});
$.ajax({
url: "<?php echo base_url();?>ama/c_agency/populate_dropdown_cabang",
type: 'GET',
success: function(data) {
var html = '';
var j;
data = JSON.parse(data);
for(j=0; j<data.length; j++){
html += '<option value="'+data[j].GroupBranchID+'">'+data[j].branch+'</option>';
}
var posisi = "#area";
$(posisi).append(html);
}
});
$("#area").val(selectedValues).trigger("change");
});
function nav_active(){
var d = document.getElementById("nav-ama-agency");
d.className = d.className + "active";
}
</script>
there is no error when im running the script.
You need to change the way you are appending options to Select Box in your ajax success callback.
Instead of following way to append options.
data = JSON.parse(data);
for(j=0; j<data.length; j++){
html += '<option value="'+data[j].GroupBranchID+'">'+data[j].branch+'</option>';
}
You need to append options using the following method
for(j=0; j<data.length; j++){
var option = new Option(data[j].branch, data[j].GroupBranchID );
$("#area").append(option);
}
Document states that
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control:
Here is the JS Fiddle which adds New Option to Select Box on a Click Event. In your case, Click Event fires an AJAX Call and remotely fetches data.

How can I implement a dynamic form in TYPO3?

I have created a extension to manage some courses and now I want to add some dynamic to one of my forms. This form contains two select fields. The first select field specify a course category and the second one a course. Currently I get always all categories and all courses no matter which category is selected.
Now I would like that a user can only select a course which belongs to a selected category, but I don't know how I can implement this.
I have tried to use a typeNum and some ajax, but I don't know how I can change the form model with the ajax call and without a page reload.
My template for this form looks like the following:
<f:layout name="Default" />
<f:section name="main">
<div class="sidebar-view">
<a id="form"></a>
<f:form action="list" name="form" object="{form}" section="form">
<fieldset>
<f:render partial="FormErrors" arguments="{field: 'form.category'}" />
<f:form.select class="category" property="category" options="{categoryOptions}" optionValueField="key" optionLabelField="value" prependOptionLabel="{f:translate(key: 'LLL:EXT:courses/Resources/Private/Language/locallang_db.xlf:tx_courses_domain_model_form.category')}" />
<f:render partial="FormErrors" arguments="{field: 'form.course'}" />
<f:form.select property="course" options="{courseOptions}" optionValueField="key" optionLabelField="value" prependOptionLabel="{f:translate(key: 'LLL:EXT:courses/Resources/Private/Language/locallang_db.xlf:tx_courses_domain_model_form.course')}" />
<f:form.hidden class="id" property="pageId" />
<f:form.submit name="send" value="{f:translate(key: 'LLL:EXT:courses/Resources/Private/Language/locallang_db.xlf:tx_courses_domain_model_form.submit')}" />
</fieldset>
</f:form>
</div>
</f:section>
As you can see it is a simple form with two select fields, a submit button and a hidden field which stores the page id. I don't want to submit the form when the category is changed so I think there is no way to implement this dynamic without ajax.
For this reason I have implemented the following typenum:
obj.ajaxPrototype = PAGE
obj.ajaxPrototype {
typeNum = 0
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type: text/plain
xhtml_cleaning = 0
debug = 0
no_cache = 1
admPanel = 0
}
}
ajaxCall < obj.ajaxPrototype
ajaxCall {
typeNum = 1001
10 < tt_content.list.20.courses_p1
}
After that I have added some javascript (jQuery) to execute a controller action via ajax when the select field is changed:
$(document).ready(function() {
$('.tx-courses select:first-of-type').on('change', function() {
$.ajax({
method: "POST",
url: "index.php?id=" + $('.id').val(),
data: "type=1001&tx_courses_p1[action]=check&tx_courses_p1[form][category]="+$('.category').val(),
success: function(msg) {
alert(msg);
}
});
});
});
Simple action:
/**
* check action
*
* #return void
*/
public function checkAction() {
return 'ajax call fired';
}
If I change the select field I get the message "ajax call fired". So my controller action will be executed and I might implement some "get courses by requested category id" logic and so on now, but how can I update the form from above which will be rendered by my sidebarAction with the ajax call and without a page reload?
Ok, I found a way to get it work.
At first I changed the ontent type of my typeNum from above to json, because I want to work with json.
additionalHeaders = Content-type: application/json
Then I changed my ajax call:
$(document).ready(function() {
var arr;
var ajaxCall = function() {
$.ajax({
method: "POST",
url: "index.php?id=" + $('.id').val(),
data: "type=1001&tx_courses_p1[action]=check&tx_courses_p1[form][category]="+$('.category').val(),
success: function(msg) {
$('.tx-courses .course option:not(:first-child)').remove();
arr = $.map(msg, function(el) { return el });
arr.sort();
$.each(arr, function(i, val) {
$('.tx-courses .course').append('<option value="'+val+'">'+val+'</option>');
});
}
});
};
// init (if someone submitted the form, but forgot to select a category)
ajaxCall();
// someone changed the category
$('.tx-courses .category').on('change', function() {
ajaxCall();
});
});
And my controller action for this ajax request looks as follows:
/**
* check action
*
* #return string
*/
public function checkAction() {
// get arguments
$args = $this->request->getArguments();
// create container for courses which are depended on selected category
$coursesBySelectedCategory = array();
// check if category was posted and category exists
if (isset($args['form']['category']) && $this->courseRepository->categoryExists($args['form']['category'])) {
// get all courses which belongs to this category
$courses = $this->courseRepository->findByCategoryId($args['form']['category']);
} else {
// get all courses
$courses = $this->courseRepository->findAllNotExpiredCourses();
}
// store course names
foreach($courses as $course) {
$coursesBySelectedCategory[] = $course->getName();
}
// remove double entries
$coursesBySelectedCategory = array_unique($coursesBySelectedCategory);
return json_encode($coursesBySelectedCategory);
}
Your feedback is welcome :).

The parameter is not passed from the view to the action

Here is the dropdownlist which contains the parameter (selected value) that I would like to pass to the view:
<select id="sltBiblioSite" name="sltBiblioSite">
<option>Sélectionnez un BiblioSite</option>
#*Iterating BiblioSite Model*#
#foreach (var item in Model)
{
<option>
#item.NomSite
</option>
}
</select>
Here is where I tried different things (see commented code below) to pass the parameter to the fucntion:
var selectedBiblioSiteName;
$("#sltBiblioSite").change(function () {
//selectedBiblioSiteName = $("#sltBiblioSite").val();
//selectedBiblioSiteName = $("#sltBiblioSite").val().trim();
//selectedBiblioSiteName = $("#sltBiblioSite option:selected").text();
//selectedBiblioSiteName = $("#sltBiblioSite > option:selected").attr("value")
...
}
});
and here is one of the functions who is supposed to pass the parameter by calling the partial view.
function getReservationTable() {
$.ajax({
// Get Reservation PartialView
url: "/Home/ReservationsToPartialView",
type: 'Get',
data: { biblioSiteName: selectedBiblioSiteName },
success: function (data) {
$("#reservationDetailTable").empty().append(data);
},
error: function () {
alert("something seems wrong");
}
});
}
I tried to hardcode the parameter in the action and it's working.
The problem seems to be in the view but I don't know where, please help me to fix this problem.
public ActionResult ReservationsToPartialView(string biblioSiteNom)
{
//biblioSiteNom = "La feuille de chene";
var reservationByBiblio = ReservationLinq.GetReservationByBiblioSite(biblioSiteNom);
return PartialView("ReservationPV", reservationByBiblio);
}
I haven't done this in a long time, so I might be completely wrong but I think you are passing wrong parameter name. In your ajax request you have biblioSiteName and in your actions its biblioSiteNom.
Also try some alert before calling the ajax to see whether the read parameter biblioSiteName is correct.

Filtering data in controller by drop downs of view

I have a large dataset, which I am trying to filter in the controller itself and send only the relevant data to the view ( index.gsp; client side)
View1:
<form>
<g:select from="['AFFILIATES', 'SEO', 'SEM','DISPLAYADS']" name="mv"
onchange="${remoteFunction(
controller:'Pgtyp',
action:'ajaxGetMv',
params:'\'mv=\' + (this.value)',
onSuccess: 'printpgtyp(data)')}">
</g:select>
</form>
Controller1:
def ajaxGetMv = {
def pgtyp = Pgtyp.executeQuery("select p.visits,p.mv from Pgtyp p where p.mv = ?",[params.mv])
//console.log(params.id)
render pgtyp as JSON
}
Now, this part works perfectly after printing on console, it's filtering data for specific "mv".
But, I have multiple drop downs(5) which are independent to each other, I want all these 5 values passed to my controller always and then filtered data accordingly to come to the view, but I am not able to implement this.
I implemented it using "html - document.getElement " but the data is too heavy to be handled on the client side(browser crashes)
Hence, I need the filtering to happen on the groovy controller side.
I tried for 2 filters via 2 drop downs :
View2:
<form>
<g:select from="['AFFILIATES', 'SEO', 'SEM','DISPLAYADS']" name="mv"
onchange="${remoteFunction(
controller:'Pgtyp',
action:'ajaxGetMv',
params:'\'mv=\' + (this.value)',
onSuccess: 'printpgtyp(data)')}">
</g:select>
</form>
<form>
<g:select from="['INTERNET EXPLORER', 'MOZILLA', 'GOOGLE CHROME','MOZILLA' ,'OTHERS','SAFARI']"
name="browser"
onchange="${remoteFunction(
controller:'Pgtyp',
action:'ajaxGetMv',
params:'\'browser=\' + (this.value)',
onSuccess: 'printpgtyp(data)')}">
</g:select>
</form>
Controller2:
class PgtypController {
def ajaxGetMv = {
def pgtyp = Pgtyp.executeQuery("select p.visits, p.mv, p.browser from Pgtyp p where p.mv = ? and p.browser = ?",[params.mv & params.browser])
render pgtyp as JSON
}
def index() { }
}
Error:
POST http://localhost:8082/marchmock2/pgtyp/ajaxGetMv 500 (Internal Server Error)
send
x.extend.ajax
onchange
Any suggestions will be appreciated.
Also, let me know if this is not feasible in grails, but I think it mostly should be.
Change
[params.mv & params.browser]
to
[params.mv, params.browser]
in your hql query (Controller2).
Yes you are getting filtered data. A list of list(contains p.visits, p.mv, p.browser). You can get the p.visits like
jQuery.ajax({
url: '${createLink(controller: 'myController', action: 'myAction')}',
success: function(data){
for (var idx = 0; idx <= data.length - 1; idx++) {
console.info(data[idx][0])
}
}
});

on check box check send value to partial view and update it mvc 3

i have two partial view one is having a 5 checkbox (for filtering) and another will display the filtered data.
<input type="checkbox" data-toggle="checkbox" id="2000-5000"/>Rs.2000-Rs.5000
<input type="checkbox" data-toggle="checkbox" id="2000-5000"/>Rs.2000-Rs.5000
and with help of jquery am sending the request to controller..
public PartialViewResult PhonesPartail(int? id,string where)
{
var list = paginateRsult(id, "", where).ToList();
ViewData["totalpages"] = totalPages;
return PartialView("_phonelist",list);
}
and the jquery
$(document).on("change", ".price-checkbox input[type=checkbox]", function () {
if ($(this).is(":checked")) {
var prange = $(this).attr("id");
var parray = prange.split('-');
var whereclause = "price>=" + parray[0] + " and price <=" + parray[1];
$.ajax({
url: '../../Phones/PhonesPartail',
data: { where: whereclause },
type: 'POST',
success: function (data) {
$("#phone-list").append(data);
}
});
}
});
now the list which is returned , is getting added to the div with entire html page.. means again the html page is getting added in the div..
any solution..
Thanks in advance...
use html() function of jquery
It will paste data returned by partial view in to a div rather then appending it to div
$("#phone-list").html(data);

Resources