I've a form when I click one radio button to load a subform.
Ok this work perfectly, but has 3 selectors that I need external data when only this subform loaded.
So, I did in this way:
$(document).on('focus', '#reemb', function () {
$.getJSON("/banks.php", function (json) {
$('#bank').empty();
$.each(json, function (i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code));
});
});
$.getJSON('/statecity.json', function (data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function (key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options);
$("#state").change(function () {
var options_city = '';
var str = "";
$("#state option:selected").each(function () {
str += $(this).text();
});
$.each(data, function (key, val) {
if (val.name == str) {
$.each(val.city, function (key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city);
}).change();
});
});
This work fine, but everytime that I need to change one date the selectors clear and load again.
I tried to add tag onload to start the function to load selectors in this subform, but don't works. Also tried change events to .on, but also don't work.
How I need to do this?
Thx!!
Not knowing what #reemb is, I would empty the relevant sub selects:
If the container holding the selects is ALSO emptied, you need to delegate all even handlers of objects inside too - like $(document).on("change","#bank", function() {
$(document).on('click', '#reemb', function() {
$.getJSON("/banks.php", function(json) {
$('#bank').empty();
$.each(json, function(i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code)).change();
});
});
$('#bank').on("change", function() {
$('#city').empty();
$.getJSON('/statecity.json', function(data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options).change(); // if needed
});
$("#state").on("change", function() {
var options_city = '';
var str = "";
$("#state option:selected").each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.name == str) {
$.each(val.city, function(key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city).change(); // if needed
});
});
});
Related
I have a dropdown who populate depending of selected radio button:
JS
$(function getJsonProveedores() {
var items = "";
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
}
else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("GetUnidades", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
}
});
});
It load correctly all JSON, but I have an issue removing last query, for example if i click Proveedor radio, it load:
$.getJSON("#Url.Action("GetProveedores", "Agenda")"
and next if I click Sucursal radio, it load
$.getJSON("#Url.Action("GetUnidades", "Agenda")"
The problem is I keep seeing first query result of
$.getJSON("#Url.Action("GetProveedores", "Agenda")"
instead getting only second one:
$.getJSON("#Url.Action("GetUnidades", "Agenda")"
Controller:
public ActionResult GetProveedores()
{
var listaProveedores = db.Proveedores.ToList();
return Json(listaProveedores, JsonRequestBehavior.AllowGet);
}
public ActionResult GetUnidades()
{
var listaUnidades = db.Unidades.ToList();
return Json(listaUnidades, JsonRequestBehavior.AllowGet);
}
public ActionResult GetUsuario()
{
var listaUsuarios = db.Usuarios.ToList();
return Json(listaUsuarios, JsonRequestBehavior.AllowGet);
}
What can be the problem there? Regards
The way the functions/variables are structured, items never falls out of scope. So it never gets reset. Each subsequent AJAX call is simply appending to it.
Instead, get rid of the items variable from its current scope and use one local to each scope where you need it:
$(function getJsonProveedores() {
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
var items = ""; // <--- declare it here
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
}
else if (this.value == 'Sucursal') {
// ... and so on, declaring an "items" in each scope where you need it
I am having one dropdown and when I select one item from that dropdown a list appears corresponding to that item comes from a json in the list box. But I don't want to have list box, I want to have checkboxes so that I can select multiple items. I'm trying to convert this list box into checkboxes but not getting the intended result.. Please help!!!
This is my javascript code
$('#dropdown1').change(function () {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
// var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
});
This is my html code
<form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox", multiple></select>
<br>
</form>
More js code
$(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
After filling the dropdown with what you required, when u select an option the data u get instead of making a <select> make a <div>. Then fill the div with:
<input type="checkbox" name="yourDataName" value="yourDataName">yourDataName</input>
Check this demo on jsfiddle : https://jsfiddle.net/jagrati16/s566ss58/
This is just a demo. Hope it solves your problem
Change this:
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
to this:
var check = '';
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
check += '<input type="checkbox" name="'+attr+'" value="' + attr + '">' + value[attr] + '<br>';
}
$('#listbox').append(check);
}
});
I am extremely new at writing ajax and working with a restful api... so, bear with me.
I have a Laravel 5.2 RESTful API that I am using on the backend, and I'm attempting to simply load a list of categories using Jquery / Ajax. As you click through the categories, each child category loads fine, but I cannot seem to get the "back" button to work (by this, I mean the LI I am generating, not the browser back button). When you click it, it shows the alert - and the data is correct, but that's it. The list doesn't refresh and populate with the appropriate items.
EDIT
There are no errors being thrown to the javascript console either. It just won't populate from the ajax call.
EDIT
I removed the request.abort() right after I made the original post.
EDIT
Here is the JSON returned from the URL api/categories/4 - as an example.
[{"id":6,"parent":4,"name":"sub_subcat4_1","slug":"sub_subcat4_1","description":null,"created_at":null,"updated_at":null},{"id":7,"parent":4,"name":"sub_subcat4_2","slug":"sub_subcat4_2","description":null,"created_at":null,"updated_at":null}]
EDIT
Here is the HTML for the #categories
<div class="row">
<div class="col-sm-12">
<ul id="categories">
</ul>
</div>
The Javascript
<script>
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
alert(dataID);
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + val.parent + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
Ok, I just had my variables all mixed up. I wasn't setting the correct parent id.
The new script looks like this -
<script>
var previous = null;
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
previous = val.parent;
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
previous = cat.getAttribute("data-parent");
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + previous + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
})
.fail(function(jqxhr, textStatus, error) {
console.log("Request Failed: " + textStatus + " - " + error);
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
I have 3 selects:
country, region, city
When choosing a country to be updated select the region on the country.
here's the code. like written logically. but the region is not updated
$(document).ready(function() {
$('select[name=ad_country]').change(function() {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', {country: current_country},
function(data) {
$('select[name=ad_region]').empty();
$.each(data.region, function(key, val) {
$('select[name=ad_region]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function(key, val) {
$('select[name=ad_city]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
});
}
);
}
you have an error on your clossing tags
You have missed the '}' at the end.Now try this Code :
$(document).ready(function () {
$('select[name=ad_country]').change(function () {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', { country: current_country },
function (data) {
$('select[name=ad_region]').empty();
$.each(data.region, function (key, val) {
$('select[name=ad_region]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function (key, val) {
$('select[name=ad_city]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
});
});
});
I have some onchange events setup in jQuery which are used to populate a select dropdown boxbased on what is selected in another select dropdown.
I need these to also run on page load that so that results are returned based on what the first select box is at on page load (otherwise I end up with an empty select box). I've had a look around the internets but can't find anything that fits exactly what I want to do
My jQuery code is
$(function(){
//Get Contacts for Company
$("select#ContactCompanyId").change(function(){
var url = "contactList/" + $(this).val() + "";
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteContactId").html(options);
})
})
//Get list of product Categories
$("select#ProductCategory").live('change', function(){
var url = "productList/" + $(this).val() + "";
var id = $(this).attr('name');
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
options += '<option value="0">None</option>';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteItem" + id + "product_id").html(options);
})
})
//Function to add product data into the form
$(".Product").live('change', function(){
var url = "productData/" + $(this).val() + "";
var id = $(this).attr('title');
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
$("#QuoteItem" + id + "name").val(j['Product']['name']);
$("#QuoteItem" + id + "price").val(j['Product']['price']);
$("#QuoteItem" + id + "description").val(j['Product']['description']);
})
})
})
Thanks in advance for your help
You can just trigger the event just after binding it with .trigger() like this:
$("select#ContactCompanyId").change(function(){
var url = "contactList/" + $(this).val() + "";
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteContactId").html(options);
});
}).trigger('change');
$(document).ready(function() {
$('#your_select_id').change();
});
This fires the change event for your select, with its current value. Its the equivlent of a user selecting the current value, and it will fire any events attached to it that would fire from an onchange event.