AJAXed Select form element defaults to first option even if changed - javascript

Updated: The DOM is creating a second select instance of #dockhouse-reservation-vessel. It's overriding the first which is the "real" one with the right value
The events are triggered, data retrieved and replaced. #dockhouse-reservation-vessel's value shows in an alert() but not in $_POST. If I comment out the second block of jQuery, the problematic select's value is remembered correctly.
$('form').delegate('#dockhouse-reservation-owner','change', function(){
$.ajax({
url: '/dockhouse/ajax/vessels/' + $(this).val() + '/',
success: function(data){
$('#dockhouse-reservation-vessel').empty();
$('#dockhouse-reservation-vessel').append(data);
}
});
});
data represents option elements:
<!DOCTYPE html>
<option value="">Choose a vessel</option>
<option value="1744">Stinkpot</option>
<option value="1726">Poopy Snoop</option>
<option value="1704">Catchup</option>
The data below represents a table.
$('form').delegate('#dockhouse-reservation-vessel','change',function(){
$.ajax({
url: '/dockhouse/ajax/locations-by-reservation-criteria/' + $(this).val() + '/',
success: function(data){
$('#assign-location').empty();
$('#assign-location').append(data);
}
});
});
Any ideas?

As you are removing and reinserting the whole select box, the state is removed.
You can save the old value in a temp variable and apply it in the callback:
$('form').delegate('#dockhouse-reservation-vessel','change',function(){
// save the value
var oldValue = $(this).val();
$.ajax({
url: '/dockhouse/ajax/locations-by-reservation-criteria/' + oldValue + '/',
success: function(data){
$('#assign-location').empty();
$('#assign-location').append(data);
// select the old value
$('#dockhouse-reservation-vessel').val(oldValue);
}
});
});

WOW, stupid mistake. There was a select field with the same name being pulled in with the table ajax response. Walks away in shame...

Related

execute command to new loaded content from ajax jquery

I got some problem with jquery.
<select class='my-select' id='exist_select'></select>
<div id='target'></div>
<script>
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select = '<select class="my-select" id="select'+data[key]+'"></select>';
}
$('div#target').html(select);
$('.my-select').append($('<option>', {
value: 100,
text: 'Added option',
}))
})
})
</script>
The selects was successfully loaded. As you see, I tried to make HTML selects. Then append spesific option manually for each select.
Unlucky, It doesn't work. But it works on #exist_select.
I have no idea. Please help me.
First wrap your code in a document ready statement, second your loop only gets the first element, you need to use concatenation to append the rest,3th you can append the option directly in the select:
$(function(){
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select += '<select class="my-select" id="select'+data[key]+'"><option value="100">Added option</option></select>';
}
$('div#target').html(select);
})
})
})
Event listeners can only be attached to elements that are in the DOM, not elements that don't exist at the time.
For dynamically created elements, you need to use the .on function:
$('body').on('change', '.my-select', function(){
alert('here');
});

How to refresh select option list after AJAX response

I use fastSelect plugin http://dbrekalo.github.io/fastselect/
I have input tag, when change value i do a call ajax to php server.
My problem is that When I inspect the item and I look in the options, I see the data I just added, but in the browser it does not display, sorry for the quality of my English
any help please ?
Enclosed my code
<select id="Recherche_log_commune" name="Recherche[log_commune][]" class="multipleSelectDepCom" multiple="multiple">
<optgroup label="Communes">
</optgroup>
</select>
<script> $('.multipleSelectDepCom').fastselect({maxItems: 10,noResultsText: 'Pas de résultat'}); </script>
<script>
$("#leftBlockDashboard .fstQueryInput").on("change paste keyup", function(event) {
event.preventDefault();
getCommuneAndDepartement($(this).val());
});
function getCommuneAndDepartement(expression) {
var dataString = {expression: expression};
$.ajax({
url: '{{path('get_commune_departement')}}',
type: "POST",
data: dataString,
success: function(data){
$("#Recherche_log_commune").find('optgroup[label="Communes"]').empty();
$.each(data, function(){
var option = '<option value="'+ this.com_id +'">'+ this.com_libelle +'</option>';
$("#Recherche_log_commune").find('optgroup[label="Communes"]').append(option);
});
$('.multipleSelectDepCom').fastselect({
maxItems: 10,
noResultsText: 'Pas de résultat',
});
}
})
}
</script>
ok solved , very rude but works ... on ajax callback here is what i do:
1) get a reference to original node ...
in my case it is
var cc = $('#categories');
2) check if .fstElement exists
var fsexist = $(".fstElement").length > 0;
3) if exists remove it and reappend the original node
if (fsexist) {
$('.fstElement').remove();
$('#categories_div').append(cc);
}
4) reinit fastselect
$('#categories').fastselect({maxItems: 10,
noResultsText: 'Choose categories'});
You will need to reattach the control after the options are loaded:
$('.selector').fastselect();
Even more complicated (to keep the selected value):
$('.selector').fastselect({
onItemSelect: function($item, itemModel) {
//load your stuff
$('.selector').fastselect();
}
});
You Will need to refresh the select2 after ajax call like this.
setTimeout(function(){
$('#select2_id').fastselect();
},500);

When i use data-rel="chosen" json ajax data not binding with Dropdown list

My Ajax function
$.ajax({
type: "POST",
contentType: 'application/json;charset=utf-8',
dataType:'json',
url: 'getSites',
data: JSON.stringify(),
success: function(json)
{//alert("success")
$.each(json,function(i,obj)
{
// alert(obj.value+":"+obj.text);
var div_data="<option value="+obj[0]+">"+obj[1]+"</option>";
//alert(div_data);
$(div_data).appendTo('#work_site');
});
}
});
and my dropdown list
<select name="priority" required="required" data-rel="chosen" id="work_site">
<option value="">--Select--</option>
</select>
If i remove "data-rel="chosen" from select option it should work perfectly. I really want to display a searchable dropdown list. What should i do?
http://jsfiddle.net/sCyYn/2/ this is i really want with dynamic content from my ajax function.
The options are being added to the <select> element after the chosen object is instantiated. The chosen object has no idea that new options were added, so you have to tell it. You can do that by using .trigger("chosen:updated");
var div_data = "";
$.each(json,function(i,obj) {
div_data += "<option value="+obj[0]+">"+obj[1]+"</option>";
});
var $work_site = $('#work_site');
$(div_data).appendTo($work_site);
$work_site.trigger("chosen:updated");

cascaded dropdown prepopulate knockout MVC

I am on the Update details screen and I have a Country and a state dropdown .I want to pre populate State dropdown on the basis of the selected Country.
On the initial page load I do have the selected Country,Country Collection and Selected State all I need is to fetch the State Collection using AJAX.
Country List: <select id="CountryDropdownList" data-bind="options: viewModel.CountryCollection,optionsText:'CountryName',optionsValue:'CountryName',value:viewModel.SelectedCountry"></select>
State List: <select id="StateDropdownList" data-bind="options: viewModel.StateCollection,optionsText:'StateName',optionsValue:'StateName',value:viewModel.SelectedState"></select>
<script>
var viewModel = ko.mapping.fromJS(#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
console.log(viewModel.SelectedState()); //State3 the initial value
viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
alert(newSelectedCountry);
console.log(viewModel.SelectedState()); //undefined why?
$.ajax({
url: 'Home/GetStateList?Country=' + newSelectedCountry,
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data)());
console.log(viewModel.SelectedState()); //state0 why?
}
})
});
ko.applyBindings(viewModel);
$(function () {
viewModel.SelectedCountry.valueHasMutated();
})
</script>
But when I try to fetch the state list through AJAX request the Selected State value gets reset and the first value in the list becomes the default selected value. I am confused, why does KO update my selected State value when I am not changing it at all?
But if I set the Selected State again in AJAX Success callback it works fine
viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
alert(newSelectedCountry);
$.ajax({
url: 'Home/GetStateList?Country=' + newSelectedCountry,
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data.StateCollection)());
viewModel.SelectedState(data.SelectedState);
}
})
});
I am looking for a reason for this strange behavior.
I have tried simplifying the code as directed by you and now I think it might help you to point out the issue.
<script>
var viewModel = ko.mapping.fromJS(#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
console.log(viewModel.SelectedState()); // o/p state3
$.ajax({
url: 'Home/GetStateList?Country=' + viewModel.SelectedCountry(),
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data)());
console.log(viewModel.SelectedState()); // o/p state0
}
})
ko.applyBindings(viewModel);
</script>

Multiple ajax content requests in a loop

I'm trying to load some ajax content into a table, unfortunately it's only loading the last row multiple times instead of loading each new rows.
This is the code I'm using:
function periodicRefresh()
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayLastEvent",
success: function(msg){
var newid = msg;
current = $("#list tr:first").get(0).id;
if(newid != current){
while (current<newid)
{
current++;
addToList(current);
}
}
}
});
}
function addToList(x)
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayRow&row="+x,
success: function(msg){
$("#list").prepend(msg);
$("#list tr:first").highlightFade({
speed:3000
});
lastrow = x-20;
$('#'+lastrow).remove();
}
});
}
displayLastEvent returns the id of the last row.
displayRow returns the last row
You need to push your xmlHttps into an array or abstract data type, which you can then attach events handlers. Seems jquery doesn't do that for you.
I would address this issue by encouraging you to change your approach since it looks like you're likely making more AJAX requests than necessary whenever more rows need to be added to the list (2+ instead of just 2).
I would update include/ajaxActions.php?action=displayRow to accept a CSV of ids (or whatever it is you're passing in), and returning a set of row data, instead of data for just one row.
I think that:
current = $("#list tr:first").get(0).id;
return always the same result as jQuery remember only the page when it was first loaded.
For example, if you have a single tr[id=0]:
pass 1 : current = 0; msg = 1 -> 1 tr prepended with id = 1;
pass 2 : current is always 0 (not 1); msg = 1 -> 1 tr prepended with id = 1;
...
what you should do, is make jQuery recognize your page structure after adding your messages, or store the last index in a different way: using hidden input for example:
HTML:
<input type="hidden" value="0" id="lastId"/>
script:
initialize #lastId value when the page is loaded:
$(document).ready(function(){
$("#lastId").val(0);//or by using your displayLastEvent action
});
modify periodicRefresh to read #lastId value:
function periodicRefresh()
{
$.ajax({
type: 'GET',
url: 'include/ajaxActions.php',
data: "action=displayLastEvent",
success: function(msg){
var newid = msg;
var current = $("#lastId").val();
if(current<newid) $("#lastId").val(newid);
if(newid != current){
while (current<newid)
{
current++;
addToList(current);
}
}
}
});
}

Categories

Resources