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);
});
})
})
Related
I try to load the options of a select with an AJAX request. The AJAX request is correct and return what I want. Here is my code :
new Ajax.Request(url, {
method: 'post',
parameters: {foldertype_id: foldertype},
onSuccess: function(answer) {
var folders = JSON.parse(answer.responseText).folders;
var selectToFill = $('my_select_box');
for(var i = 0; i <= folders.length; i ++){
selectToFill.append('<option id="' + folders[i].value + '" value="' + folders[i].ID + '">' + folders[i].label + '</option>');
}
}
});
The option are well added nto the select, but they didn't appear in the dropdown. In Chrome I can see there is no color syntax in the option text. See this screenshot to understand well : http://imgur.com/a/4NZB5
As you can see, the grey options are those added by AJAX, and I can't see those one into my select dropdown
Why this is happen ?
Thanks in advance
got an answer here: https://arstechnica.com/civis/viewtopic.php?t=209624
Typically DOM insertion is using .insert
Example:
new Ajax.Request(url, {
method: 'post',
parameters: {foldertype_id: foldertype},
onSuccess: function(answer) {
var folders = JSON.parse(answer.responseText).folders;
var selectToFill = $('my_select_box');
for(var i = 0; i <= folders.length; i ++){
selectToFill[0].insert({after: '<option id="' + folders[i].value + '" value="' + folders[i].ID + '">' + folders[i].label + '</option>'});
}
}
});
From the code above, you should be pointing to any last option inside your select element which where you will going to append after, example your index 0 or 1
Example Snippet
const test = ["test1","test2"];
test.forEach(function(index,item){
const sel = $('my_select');
sel[0].insert({after: "<option value='"+item+"'>"+item+"</option>"});
});
<script src="https://fastcdn.org/Prototype/1.7.3/prototype.js"></script>
<select id="my_select" placeholder="test">
<option value="test">test</option>
</select>
I hope that helps.
Try this
var htmlToAppend ="";
for(var i = 0; i <= folders.length; i ++){
htmlToAppend += "<option id='" + folders[i].value + "' value='" + folders[i].ID + "'>" + folders[i].label + "</option>";
}
selectToFill.append(htmlToAppend);
I'm having a problem with a script that is part borrowed and part my own, it is javascript and php that populates two dropdown lists, with options in the second being dependent on what the user selects in the first. For some reason, it won't load the options in the second dropdown when the initial option is selected in the first, either on page load or if it is selected manually (if the options were 'a, b, c, d, e...etc', it won't load anything for 'a').
I think it might be something to do with the javascript document ready function, but I'm afraid I know very little about javascript. This is the javascript code:
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctProxy").change();
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});
Change event is only fired, when selection is changed - not when filled ;-)
Try adding $("#slctOutcome").trigger("change"); at pre-last line
Have fun :-)
Try the below. Second function wasn't being called in first function.
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctOutcome").change(); //<-Here
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});
I'm trying to get the values of my dynamically filled select list in a global variable. This is how I get and fill the select list:
My dropdown.js script:
$(document).ready(function () {
$("#slctTable").change(function()
{
$.getJSON("dropdown_code/get_fields.php?table=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#slctField").html("");
$("#slctField").append(options);
$("#slctField").change();
});
});
});
So after this I tryed this code in my main.js scgript to get the values of the select lists:
$('#slctField > option').each(function(){
console.log(this.value); // Use this.value to get the value of the option
});
var options = [];
$('#slctField > option').each(function(){
options.push(this.value);
});
console.log(options);
But when I run my scripts this the result I get back:
But when I copy and paste the code in firebug and run it. I get the result i want.So I think the select lists aren't filled yet when i try to get the values. But I'm stuck on this for a long time and I don't know what to do at the moment.
Because getJSON is asynchronous, to solve your problem you can trigger a custom event when the select is completed (at the end of getJSON success).
In my example I used this slctFieldFilled new event.
This is a different approach. Another possible solution can be based on callbacks: at the end of an asynchronous function execute the callback function, like the getJSON does.
My snippet:
$(function () {
$.getJSON('https://api.github.com/users', success = function (data) {
var options = '';
for (var i = 0; i < data.length; i++) {
options += "<option value='" + data[i].id + "'>" + data[i].id + "</option>";
}
$("#slctTable").append(options);
$("#slctTable").change();
});
$("#slctTable").on('change', function(e) {
var par1 = $(this).val();
$.getJSON("https://api.github.com/users", success = function(data) {
var options = "";
for(var i = 0; i < data.length; i++) {
options += "<option value='" + data[i].id + "'>" + data[i].id + "</option>";
}
$("#slctField").html("");
$("#slctField").append(options);
$("#slctField").change();
//
// Now, the slctField is filled, so trigger your custom event
//
$('#slctField').trigger('slctFieldFilled', options);
});
});
$("#slctField").change(function() {
var par1 = $(slctTable).val();
var par2 = $(slctField).val();
$.getJSON("https://api.github.com/users", success = function(data) {
var options = "";
for(var i = 0; i < data.length; i++) {
options += "<option value='" + data[i].id + "'>" + data[i].id + "</option>";
}
$("#slctAttribute").html("");
$("#slctAttribute").append(options);
$("#slctAttribute").change();
});
});
// listen on custom event...
$('#slctField').on('slctFieldFilled', function(e, optionVariable) {
var options = [];
$(optionVariable).each(function(index, element){
options.push(this.value);
});
$('#log').text(options);
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<select id="slctTable"></select>
<select id="slctField"></select>
<select id="slctAttribute"></select>
<p id="log"></p>
You're very correct! Your GET is asynchronous and will likely complete long after your main.js code has finished executing. You'll want to make sure your modifications to the global variable is tied to your callbacks in some way so its guaranteed to run afterwards.
var options = [];
$("#slctField").change(function()
{
$.getJSON("dropdown_code/get_attributes.php?table=" + $(slctTable).val() ,"field=" + $(slctField).val() , success = function(data)
{
...
//Option 1: Append the values inside your callback.
//Use window.options because you have another local variable options(window.XX calls any global XX)
for(var i = 0; i < data.length; i++)
{
...
window.options.push(data[i]);
}
//Option 2: Basically the same thing as 1, call a function that does the same thing at the end of your callback
populateOptions();
});
});
function populateOptions(){
$('#slctField > option').each(function(){
options.push(this.value);
});
}
There's plenty of other ways to do it as well as long as you guarantee it executes after your GET. If you have any questions, post a comment. Be careful about the scope of options since you have multiple variables named options(or consider different names so that you can't be confused later on!).
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>');
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.