Option:
<select class="form-control se" style="width: 155px;" onchange="showOptions(this)" id="tripSelect">
<option class="dd" id="opt{{$z}}" value="{{$blah}}" data-egid="{{$optionID}}">{{$event->trip_name}}</option>
</select>
I'm using this console:
function showOptions(s) {
console.log(s[s.selectedIndex].getAttribute("data-egid"));
}
and it's working but when I used the same
var trip_id = $('#tripSelect :selected').getAttribute("data-egid"));
//---------------------
$.ajax({
type: "GET",
url: "{{blah blah}}",
data: {
event_group_id: trip_id,
},
//...
});
It's now telling me that getAttribute is not a function
getAttribute() is a function on a regular DOMElement, not some jQuery-wrapped object.
You didn't show us the relevant code, but somewhere in your top sample, if that's working, s[s.selectedIndex] is a regular DOMElement.
In your lower code, $('#tripSelect :selected') returns a jQuery-wrapped array of elements, which have different functions.
If you wanted that first element, you could have probably done something like:
$('#tripSelect :selected')[0].getAttribute("data-egid");
Related
I am trying to populate a bootstrap-select control using the following AJAX call:
function loadCategories() {
$.ajax({
url: '../handlers/getcategorylist.ashx',
data: null,
method: 'post',
dataType: 'json',
success: function (data) {
alert(JSON.stringify(data));
$('#ddlCategories').html(JSON.stringify(data));
$('#ddlCategories').selectpicker('refresh');
},
error: function (e) {
console.log(e.responseText);
}
});
}
The HTML for the bootstrap-select is as follows:
<div class="row mb-2">
<div class="col-lg-10 offset-lg-1">
<select id="ddlCategories" name="ddlCategories" data-width="25%" class="form-control selectpicker">
<option value="select">Select From The List</option>
</select>
</div>
</div>
The AJAX call executes and is successful. Using JSON.stringify() I get the following data back (shown in an alert):
For whatever reason, the bootstrap-select doesn't populate. It displays empty. What am I missing here?
Hi it seems like you're setting the inner HTML of your select element to a array of objects. You probably have to .forEach() through all the objects inside of your response array and append them to the select element (like described in the following StackOverflow answer. If you'd also like to remove existing content from the select element consider setting the html to blank.
So something along the lines of:
data.forEach(entry => {
$('#ddlCategories').append(`<option value=${entry['ID']}> ${entry['Name']} </option>`);
});
I've been trying to implement a solution proposed in How do you select a particular option in a SELECT element in jQuery? to no avail. Either the addition of Chosen to the mix makes the solution invalid, or I've made some coding error that is beyond my compiler and me to find.
My html:
<select name="superType" class="chosen-select chosen-select-creation-allowed" id="superType" style="width: 300px; display: none;" onchange="loadInheritance()" multiple="">
<option style="padding-left:20px;" value=""></option><option style="padding-left:0px" value="28">concept</option>
<option style="padding-left:20px" value="30">human</option>
</select>
When I place the following after this, I expect one of them will add to the value="30" option above a 'selected' attribute:
//$('#superType option[value="30"]').prop('selected', true);
$('#superType option[value="30"]').attr('selected', 'selected');
$('.chosen-select').trigger("chosen:updated");
Instead, nothing happens as according to the DOM model inspector and visual presentation.
What I want is to have this selection happen inside a function, but when I try to build the reference to the option above I get the error:
Syntax error, unrecognized expression: '#superType option[value="30"]'
Here is the javascript generating that (procs on 'cid'):
//now go back through and select the ones this CommonNoun already had from before
$.ajax({
url: '/BackToTech/server?function=getExistingSuperTypes',
type: 'POST',
success: function (response){
// var target = $("#superType");
var target = "#superType";
selectOptions(response, target, 0);
$('.chosen-select').trigger("chosen:updated");
}
});
...
function selectOptions(obj, target) {
var concepts = obj;
$.each(concepts, function(concept, value) {
alert(concept, value);
if (concept == "cid") {
optionValue = obj[concept].oid;
$("'" + target + " option[value=\"" + optionValue + "\"]'").attr('selected', 'selected');
} else {
selectOptions(value, target);
}
});
}
You don't need the single quotes around the css selector.
$(`${target} option[value="${optionValue}"]`).attr('selected', 'selected');
I'm fetching some data using ajax from my database, the problem is when I append an option to a select with a value containing these data, the append ends the first word with " thus the rest is left outside the value tag.
Here's the empty select:
<select name="Sender" id="SenderNames" class="form-control" style="width: 100%;"></select>
This is the jQuery code:
$('#SenderSelect').on('change', function() {
$.ajax({
type: "POST",
url: 'operations/inner-operations/getNamesByService.php',
data: { action :"getService", "serviceName" : $("#SenderSelect option:selected").val() },
success: function(data) {
var responseObj = jQuery.parseJSON(data);
console.log(responseObj);
$.each(responseObj, function(i, value) {
$("#SenderNames").append('<option value='+value+'>'+value+'</option>');
});
}
});
});
The appended option should look like this:
<option value="First Second">First Second</option>
However, it is appended like this:
<option value="First" second="">First Second</option>
I just realised that I'm not closing the string properly. The append should be like this:
$("#SenderNames").append('<option value="'+value+'">'+value+'</option>');
the value tag must be wrapped by "".
Here is my js function;
function getCountryRegions() {
var postData = "id="+$("#selectedCountryId").val();
$.ajax({
url:"/region",
data: postData,
dataType:"html",
type:"POST",
success: function(data){
$("#selRegion2").html(data);
$("#selRegion")== $("#selRegion2").html($(data).find("#selRegion"));
}});}
The 'data' come exactly like this;
<label>Bölge</label>
<select name="selRegion" id="selRegion">
<option value="0" selected="selected" >-- tümü</option>
<option value="4140104">Adana</option>
<option value="4141360">Adrasan</option>
<option value="4137856">Afyon</option>
</select>"
My aim is to get selRegion element and pass it to an Array of Objects. Each object has value and text
I tried this line to make it;
$("#selRegion")== $("#selRegion2").html($(data).find("#selRegion"));
If your data is coming through in perfect HTML format, one trick you can use is this:
var $data = $("<data />").html(data);
Then you can get elements from it like:
$data.find("select").each(function(i) { /* DO WORK */ });
What this does is create a jQuery Element object Tagged <data>. Thus you're able to act upon it like any other jQuery element like $("div") or $("select")
I have a jQuery/Ajax function that is appending 2 <option>s to a <select>.
function addOption() {
var author = $("#authors").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$.ajax({
type: "post",
url: "books.php",
data: { author:author },
success: function(response){
$('#books').append(response);
}
});
}
response comes back as -
<option value="bookA">Book A</option>
<option value="bookB">Book B</option>
and now books is -
<select id="books">
<option value="">Please Select</option>
<option value="bookA">Book A</option>
<option value="bookB">Book B</option>
</select>
This works great.
Now I want to set the selected option using .val() after calling addOption() -
$('#authors').change( function(){
addOption();
$('#books').val('bookB');
});
This does not make Book B selected.
If I hard code the .append() it works -
function addOption() {
var author = $("#author").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$('#books').append('<option value="bookA">Book A</option>\n<option value="bookB">Book B</option>);
}
$('#authors').change( function(){
addOption();
$('#books').val('bookB');
});
Is there a reason why my option(s) appended in the .ajax function cannot be selected using .val(), put it can if I append them directly?
That's because the AJAX call is asynchronous, so when you try to select the options, it hasn't been added to the select yet.
Use a callback in the function, so that you can do something when the response has arrived:
function addOption(callback) {
var author = $("#authors").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$.ajax({
type: "post",
url: "books.php",
data: { author:author },
success: function(response){
$('#books').append(response);
callback();
}
});
}
Usage:
$('#authors').change( function(){
addOption(function(){
$('#dropdownB').val('bookB');
});
});
AJAX is asynchronous, meaning that when you call the addOption() method, it might (and probably will) return before the Ajax call has actually been made, so you are calling $('#dropdownB').val('bookB'); before the Ajax callback has been triggered to append the options.
Try putting the $('#dropdownB').val('bookB'); into the success callback of the ajax call and you should see it working.
Ajax is asynchronous, when you set the value, there is no option with that value, you can put your code in your success callback.
success: function(response){
$('#books').append(response);
// ...
}
Or set that value of async property of your Ajax request to false;
This is because ajax is asynchronous. That is, by the time it returns and appends the new options to the select list, the browser engine has already continued and tried to set the value (which wasn't yet added). Try moving the value setting logic to work as part of the ajax response.
1) You should put $('#dropdownB').val('bookB'); inside the success-event of your ajax-call, because AJAX is asynchronous and your request may not be done when you try to change the selected item, so there is no item to select yet.
2) You append to #books but change the selected item of #dropdownB. Those are two different ids and hence two different DOM elements.