Making an onchange event also run to pageload - javascript

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.

Related

display second menu based on first one along with value and id

I am referring to another question display select options based on previous selections
I have while loop to fill the var data and inside a foreach loop to give the sub-menu and all work fine, var data = {'B|1':['B5|1','B4|2']
now after displaying menu1 How do I display second one, am just stopped there.
my code is:
for (var i in data) {
var ii = i.split('|');
$('#menu1').append('<option value=' + ii[1] + '>' + ii[0] + '</option>');
}
$('#menu1').change(function () {
var key = $(this).val();
$('#menu2').empty();
for (var i in data[key]) {
var ii = data[key][i].split('|');
$('#menu2').append('<option value=' + ii[1] + '>' + ii[0] + '</option>');
}
}).trigger('change');
menu1 is ok, now I need to show #menu2 with the value and text ??
This may help you
$('#menu1').change(function() {
var key = $(this).val();
var keyText = $('#menu1 :selected').text();
$('#menu2').empty();
for (var i in data[keyText +"|" + key]) {
var ii=data[keyText +"|" + key][i].split('|');
$('#menu2').append('<option value='+ii[1]+'>' + ii[0] + '</option>');
}
}).trigger('change');

JQuery Dynamic Objects load selectors

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
});
});
});

How to append value " select " to the Select dropdown?

I want add "All" option to the existing dropdown as a first option. Pls help me
if(own != null)
{
var ar = own.replace("[","").replace("]","").split(",");
var output = $("#status_type");
output.empty();
for(var i=0;i<ar.length/2;i++)
{
output.append("<option value='" + $.trim(ar[i*2+1]) + "'>" + $.trim(ar[i*2+1]) + "</option>");
//alert ("val " +$.trim(ar[i*2+1]));
}
}
I want "All" to be the first option in select dropdown
Instead of empty() use .html() and pass the html of the All Option. This will clear the select first then will add all option and then will add other options, and will save you an unnecessary .empty() operation.
if(own != null)
{
var ar = own.replace("[","").replace("]","").split(",");
var output = $("#status_type");
output.html('<option value="'+all+'">All</option>');
for(var i=0;i<ar.length/2;i++)
{
output.append("<option value='" + $.trim(ar[i*2+1]) + "'>" + $.trim(ar[i*2+1]) + "</option>");
//alert ("val " +$.trim(ar[i*2+1]));
}
Try this: You can add ALL option just right after emptying the output variable as shown below -
if(own != null)
{
var ar = own.replace("[","").replace("]","").split(",");
var output = $("#status_type");
output.empty();
output.append("<option value='ALL'></option");//add here
for(var i=0;i<ar.length/2;i++)
{
output.append("<option value='" + $.trim(ar[i*2+1]) + "'>" + $.trim(ar[i*2+1]) + "</option>");
//alert ("val " +$.trim(ar[i*2+1]));
}
}
Try this:
$('#mysampledropdown').empty();
$.each(response.d, function(key, value) {
$("#mysampledropdown").append($("<option></option>").val(value.ID).html(value.text));
});
$('<option>').val("").text('--ALL--').prependTo('#mysampledropdown');

Works $(this) after $.post?

Can I use $(this).parentsUntil()... after a $.post?
I need to remember what select element from the DOM changed and then append the information collected from my PHP to next select.
//OPTION SELECTED
$('body').on('change','.provincias, .partidos', function(e) {
var idSelect = $(this).attr('id');
var dataSelect = $(this).select2('data');
var value = dataSelect.id;
$.post('php/select/script.php', {id:idSelect, id_provincia:value, id_partido:value } , function(respuesta) {
data = JSON.parse(respuesta);
if(data.control == 0){
alert(data.error)
window.location.replace(data.url);
}else{
if(idSelect == data.thisSelect){
for(var u=0; u<data.array1.length; u++){
$(this).parentsUntil('.formRow').next().children(data.nextSelect).append('<option value="' + data.array1[u].id + '">' + data.array1[u].nombre + '</option>');
}
}else if(idSelect == data.thisSelect){
for(var t=0; t<data.array1.length; t++){
$(this).parentsUntil('.formRow').next().children('".' + data.nextSelect +'."').append('<option value="' + data.array1[u].id + '">' + data.array1[u].nombre + '</option>');
}
}
}
});
});
The typical solution is to define another variable to hold the value of this, e.g. self, or in this case, you might want to call it target:
...
var target = this;
$.post('php/select/script.php', {id:idSelect, id_provincia:value, id_partido:value } , function(respuesta) {
// Use target here.
}
just save the $(this) in a variable.
$('body').on('change','.provincias, .partidos', function(e) {
var el = $(this);
...
el.parentsUntil('.formRow').next().children(data.nextSelect).append('<option value="' + data.array1[u].id + '">' + data.array1[u].nombre + '</option>');

How to pass a variable in the selector id?

I want to pass the selected value in select element in variable idd and then use it later. But it is not getting stored in the variable. I tried to check the value in the alert function but even alert function is not getting called.
<script type="text/javascript" charset="utf-8">
$(function(){
$("select.ctlJob").change(function(){
$.getJSON("select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
var idd=$(this).val();
//alert(idd);
$('select#'+ idd).html(options);
})
})
})
</script>
You are not able to get the value as the this in your context does not refer to the select. You'll need to do the following:
<script type="text/javascript" charset="utf-8">
$(function(){
$("select.ctlJob").change(function(){
var selectBox = $(this);
$.getJSON("select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
var idd=selectBox.val();
//alert(idd);
$('select#'+ idd).html(options);
})
})
})
</script>
Try this - (moved var idd=$(this).val(); outside of getJSON)
<script type="text/javascript" charset="utf-8">
$(function(){
$("select.ctlJob").change(function(){
var idd=$(this).val();
$.getJSON("select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
//alert(idd);
$('select#'+ idd).html(options);
})
})
})
</script>
This is a scoping problem, and, you only need to access the selected value once. This code accesses the value in the change handler, then uses it in the getJSON response handler, which is a child-scoped function. All child-scoped functions have access to their parent scopes, which is why val is defined in the response handler function.
$(function(){
$("select.ctlJob").change(function(){
var val = $(this).val();
$.getJSON("select.php",{id: val, ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$('select#'+ val).html(options);
});
})
})

Categories