Based on an AJAX query I appended some options to a list.
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="mySelectElementOption_' + data['id'] + '" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#mySelectElement').append(option);
}
Now when the user interacts on the page i want to select on of the just appended options and i tried the following (both possibilities don't work for me):
$('#mySelectElementOption_' + id).attr('selected', 'selected');
and
var option = document.getElementById('mySelectElementOption_' + id);
option.selected = true;
So I'm stuck, because I don't know how to select my option. Do you have any idea(s) how I can solve this?
Thanks!
P.S.: When I try second possibility in Google Chrome it works perfectly.
Greetings, Joseph
var opts = {
success: function(data)
{
//do everything here first before appending it,
//including adding event bindings
}
}
$.ajax(opts)
Use prop instead of attr:
$('#mySelectElementOption_' + id).prop('selected', true);
or
$('#mySelect').val($('#mySelectElementOption_' + id).val());
http://jsfiddle.net/uG88d/
Try this:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<select id="mySelectElement">
<option id="oldoption" >Old option</option>
</select>
</body>
</html>
JS:
//demo data
options = [{id:0, value:"aaa"},{id:1, value:"bbb"},{id:2, value:"ccc"}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="mySelectElementOption_' + data['id'] + '" class="interactable" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#mySelectElement').append(option);
}
//This is what you need:
$("#mySelectElement :not([class])").attr("disabled","disabled");
Explanation:
$("#mySelectElement :not([class=interactable])") - This tells jquery to find any option element in the #mySelectElement that does not have the 'interactable' class.
Then it disables it: .attr("disabled","disabled");
Try it out:
jsBin
Edit:
$("#mySelectElement .interactable:first").prop('selected', true);
Try it out
Related
I need to select first option of select with jQuery. My code is a bit complex and can't figure out how to make it work. Thanks
Html:
'sortingHtml': '<select id="bc-sf-filter-top-sorting-select">{{sortingItems}}</select>'
Javascript:
BCSfFilter.prototype.buildFilterSorting = function() {
if (bcSfFilterTemplate.hasOwnProperty('sortingHtml')) {
jQ(this.selector.topSorting).html('');
var sortingArr = this.getSortingList();
if (sortingArr) {
// Build content
var sortingItemsHtml = '';
for (var k in sortingArr) {
sortingItemsHtml += '<option value="' + k +'">' + sortingArr[k] + '</option>';
}
sortingItemsHtml = '<option disabled="disabled" selected>Sort by</option>' + sortingItemsHtml
var html = bcSfFilterTemplate.sortingHtml.replace(/{{sortingItems}}/g, sortingItemsHtml);
jQ(this.selector.topSorting).html(html);
// Set current value
jQ(this.selector.topSorting + ' select').val(this.queryParams.sort);
}
}
};
Code to select the first option:
$("#bc-sf-filter-top-sorting-select").val($("#bc-sf-filter-top-sorting-select option:first").val());
$("#bc-sf-filter-top-sorting-select option:first").prop("selected", true);
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 have a simple table that is populated using an array:
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#results-table').append('<tbody><tr><td>' + object.get('Name') + '</td><td>' + object.get('Description') + '</td><td><button class="button" onclick="goToClass()">View Class</></tr></tbody>');
})(jQuery);
Ideally I would like the goToClass() function to give me the object.ID for that individual row that was selected.
So for example, if I select the button on the first row in the table it would give me the object.ID for that class.
How would I do this?
Try this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<table id="results-table">
</table>
</body>
<script>
results = [
{Name:1,Description:"one",ID:1111},
{Name:2,Description:"two",ID:2222},
{Name:3,Description:"Three",ID:3333}
]
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#results-table').append('<tbody><tr><td>' + object['Name'] + '</td><td>' + object['Description'] + '</td><td><button class="button" onclick="goToClass('+object['ID'].toString()+')">View Class</></tr></tbody>');
})(jQuery);
}
function goToClass(id) {
console.log(id)
}
</script>
</html>
When I click the buttons, the console gives me the correct id in each case.
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);
});
})
})