I am trying to set the first option of a dropdown select based on the URL parameter provided.
I am grabbing the URL parameters using the following code:
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
The URL may read as follows:
https://development.mycompany.com/project/home.php?profile=profile1,profle2®ion=&rep=JOHN%20BEASLEY
I then can call the getUrlParameter() function to grab the rep parameter:
var rep = getUrlParameter('rep');
console.log(rep);
$('#rep').val(rep); // <-- my attempt to set the first option of the dropdown
I can see the rep variable in the console. However, when trying to set the first option of the dropdown select, it remains blank.
Here is the dropdown:
<select class="form-control rep" id="rep"></select>
I should be able to see 'JOHN BEASLEY' as the selected option in the dropdown.
The dropdown contains 'JOHN BEASLEY', as well as other reps, but it should appear as initially selected. I am perplexed as to why this is not working.
What am I doing wrong and how can I fix it?
*** EDIT ***
I am initially populating the dropdown using the following function:
function initializeSelect($select, uri, adapt){
$.getJSON( uri, function( data ) {
$select.empty().append($('<option>'));
$.each(data, function(index, item) {
var model = adapt(item);
var $option = $('<option>');
$option.get(0).selected = model.selected;
$option.attr('value', model.value)
.text(model.text)
.appendTo($select);
});
});
};
Then I populate the dropdown like this:
initializeSelect($('#rep'), 'api/getReps.php', function (item){
return {
value: item.fullname,
text: item.fullname,
style: 'color:black'
}
});
Using the above, the dropdown is successfully populated with all of the options in my dB table.
The option JOHN BEASLEY is available in the dropdown list.
<select>shown is empty? Are you trying to create such an<option>or does one already exist with that value?<option>html also as per minimal reproducible example. Another possibility is you are running code shown before the<select>exists