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
Related
The example I would like to replicate is this: https://jsfiddle.net/bindrid/hpkqxto6/ . I need to load data from the server, form a grouping of them and when selecting one item from one group all other items inside this particular group would become disabled. The difference is that I must load data from the server using an ajax call inside select2, instead of listing the < option > elements inside the select element and form a grouping this way. I have trouble selecting all available items in the dropdown list during the javascript manipulation in order to disable items from the same group (line 29 in the above example fails due to there being no < option > elements in html, instead I think they are loaded later and javascript is not able to find them).
The html part looks as follows:
<select class="form-control attributoSelect2" name="attributiSelezionati" id="attributoSelect2" value="#Model.AttributiSelezionati"></select>
There are no < option > items inside < select > because the ajax call takes care of populating the list, like this:
$('.attributoSelect2').select2({
placeholder: "Cerca Attributo",
multiple: true,
allowClear: true,
minimumInputLength: 0,
ajax: {
dataType: 'json',
delay: 150,
url: "#Url.Action(MVC.Configurazione.Attributi.CercaAttributi())",
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: data.map(function (item) {
return {
id: item.Id,
text: item.Descrizione,
children: item.Children.map(function (itemC) {
return {
id: itemC.Id,
groupid: itemC.GroupId,
text: itemC.Descrizione,
};
})
};
})
};
}
}
});
Finally my javascript looks as follows:
$('.attributoSelect2').on("select2:selecting", function (evt, f, g) {
disableSel2Group(evt, this, true);
});
$('.attributoSelect2').on("select2:unselecting", function (evt) {
disableSel2Group(evt, this, false);
});
function disableSel2Group(evt, target, disabled) {
var selId = evt.params.args.data.id;
var group = evt.params.args.data.groupid;
var aaList = $(".attributoSelect2 option");
$.each(aaList, function (idx, item) {
var data = $(item).data("data");
var itemGroupId = data.groupid;
if (itemGroupId == group && data.id != selId) {
data.disabled = disabled;
}
})
}
The problem is that this line:
var aaList = $(".attributoSelect2 option");
does not load all the option elements because they are not loaded yet. They would be loaded later on using the ajax call. Does anyone have an idea of how to resolve this problem?
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
I was looking in several threads about retrieving values from a drop down box to use the values for a later time in the casperjs script.
So my issue is that I can't fetch the values from my drop down box and actually use it in my next step, for now just to echo it out.
This is how my drop down box looks in my web page:
I did tried some examples but it just doesn't work, what am I doing wrong?
casper.then(function() {
var options = this.evaluate(function() {
var options = document.getElementById('selectedNetworkElementOrGroup_TD').children;
return [].map.call(options, function(opt) {
return { val: opt.value, text: opt.textContent };
});
});
this.echo(JSON.stringify(options));
});
One problem could be that the drop down box has no id!
You need a basic CSS selector like this one: #selectedNetworkElementOrGroup_TR select:
var options = this.evaluate(function() {
var options = document.querySelector('#selectedNetworkElementOrGroup_TR select').children;
return [].map.call(options, function(opt) {
return { val: opt.value, text: opt.textContent };
});
});
this.echo(JSON.stringify(options));
I have the following javascript when my script is loaded:
var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
//removes the hover color from the previous selected
current_selected_note.removeClass('hover active');
// sets the currently selected equal to the selected note
current_selected_note = $(this);
// adds the hover active to the currently selected
current_selected_note.addClass('hover active');
//adds the title of the currently selected to the title input field
$('#txt_new_note_title').val($(this).find('Strong').text());
selected_note_id = $(this).get(0).id;
getNote(selected_note_id);
load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );
Now AFTER this is loaded i click one of my buttons which has the following javascript:
$('#note-item-lists').on('click','.close',function(){
var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
if(r == true){
deleteNote($(this));
$( "#note-item-lists").find('li').first().click();
}
})
function deleteNote(button){
var id = button.closest('li').get(0).id;
$.ajax({
type: 'POST',
url: '/solo/ajax_delete',
dataType: 'json',
data: {
id: id
},
success: function (data) {
}
});
button.closest('li').remove();
}
When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again.
Anyone tried this before?
Try this, It will call one time.
$('#note-item-lists .close').on('click',function(){
alert("Hello");
});
Try using .off()
$('#note-item-lists').on('click', '.list-group-item', function () {
$(this).off(); //add this here
I want add some items to a selectized input after user clicks on a button. The input data are loaded via Ajax. When I call addItem(value) no thing happens. But if I try to type some string in the input it loads data and after this addItem(value) will works.
https://github.com/brianreavis/selectize.js/blob/master/docs/api.md
This plugin does not attempt to load an item metadata from the server. You need to first add an option using addOption() method. Next, you can use addItem().
v.selectize.addOption({value:13,text:'foo'}); //option can be created manually or loaded using Ajax
v.selectize.addItem(13);
You can add options like this:
var $select = $(document.getElementById('mySelect')).selectize(options);
var selectize = $select[0].selectize;
selectize.addOption({value: 1, text: 'whatever'});
selectize.refreshOptions();
This only adds the option as possible selection. Now you can use addItem to add the new option to the list:
selectize.addItem(1);
This does not need a refresh function. You do not need to use "refreshOptions" if you add the new option immediately.
Try this.
$('.select-ajax-city').each(function() {
if (this.selectize) {
for(x=0; x < 10; ++x){
this.selectize.addOption({value:x, text: x});
}
}
});
Try This
var $select = $(document.getElementById('Your-element-id'));
var selectize = $select[0].selectize;
selectize.addOption({value: '2', text: 'test'});
selectize.addItem('2');
If you want to be more flexible then you can use the length like this.
var $select = $(document.getElementById('Your-ID'));
var selectize = $select[0].selectize;
var count = selectize.items.length + 1;
selectize.addOption({ value: count, text: 'value-here' });
selectize.addItem(count);
$('#id').selectize({
create: function(input,callback){
$.ajax({
url: "",
type: "POST",
data: {value : input},
success: function(res) {
callback({value: res, text: input});
}
});
}
});
For adding new options dynamically is neccesary to call clearOptions for clean the options, adding the new list options using addOption and call refreshState function after all.
var listItems = [{id: 1, value: 'Element1'},{id: 2, value: 'Element2'}]
/* Initialize select*/
var $select = $('#element').selectize();
var control = $select[0].selectize;
control.clear()
control.clearOptions();
/* Fill options and item list*/
var optionsList = [];
var itemsList = [];
$.each(listItems, function() {
optionsList.push( {
value: this.id,
text: this.value
});
itemsList.push({
value: this.id,
text: this.value
});
});
/* Add options and item and then refresh state*/
control.addOption(optionsList)
control.addItems(itemsList);
control.refreshState();
/* Add element 1 selected*/
$.each(result, function() {
if (this.id == 1) {
control.addItem(this.Tax.id,this.Tax.title);
}
});
This is another way you can add items manually if you have set other values to your select:
$('select').selectize({
create: true,
sortField: "text",
hideSelected: false,
closeAfterSelect: false,
options:[
{
text:'<text goes here>',
value:'<value goes here>',
}
]
});