Jquery append option to select and get the selected value - javascript

Having trouble with this part.
I have a select populated with asp.net mvc and 2 other empty select that is populated by jquery
<select id="Type" onchange="GetClassification(this.value);">
#foreach (var item in Type)
{
<option value="#item.TypeID">#item.TypeName</option>
}
</select>
<select id="Classification" onchange="GetDescription(this.value);">
</select>
<select id="Description" onchange="GetDescriptionTips(this.value);">
</select>
So based on first select it populates the sencond, based on second it populates the third. First one populates right, second one populates right, third one doesn't populate on document ready.
$(document).ready(function () {
$(function () {
var type = $("#Type option:selected").val();
GetClassification(type);
});
});
function GetClassification(typeID) {
$.ajax({
type: 'GET',
url: '/types/Classification',
data: { typeID: typeID },
cache: false,
success: function (data) {
$('#Classification option').remove();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.ClassificationID).text(val.ClassificationName);
$('#Classification').append(optionTag);
});
}
});
var classification = $("#Classification option:selected").val();
GetDescription(classification);
}
function GetDescription(classificationID) {
$.ajax({
type: 'GET',
url: '/types/Description',
data: { classificationID: classificationID },
cache: false,
success: function (data) {
$('#Description option').remove();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.DescriptionID).text(val.DescriptionName);
$('#Description').append(optionTag);
});
}
});
}
After load page, if I select second one it changes the third one right, but if change the first, it only changes the second.
What I need is on load populate the second and third, then on change the first, re populate the second and third, and on change the second re-populate the third.
I can see it doesn't assign selected on any stage, so I am not sure if need assign it.
Hope I explained good.
Any help will be appreciated.

First of all try to follow this Don't repeat yourself, here is simple algo:
1.Choose all selects
2.Create only one ajax function and pass params like url, data, etc to it
3.In success function proccess your response from the server
4.find all next selects and clean them up or remove options as u wish
good luck!

Since you are using jQuery, try using the .on('chang', function(){...) event handler. Because you are changing the DOM and the on() method can detect the change event even the DOM changed after document ready.

Related

Jquery remove, add and refresh select list after ajax call (handlebars, nodejs)

i am trying to remove and add new options for a select list after user choose a value from another select box. I'm using ajax to call for the api and everything works fine. However, the html of the select list doesn't refresh at all after i remove or add new options. Am i doing wrong somehow?
My HTML generated with handlebars:
<select name="district" id="district">
<option value="">Quận/ Huyện</option>
<option value="1">District 1</option>
<option value="2">District 2</option>
</select>
<select name="street-select" id="street">
<option value="">Đường</option>
{{#each streets}}
<option value="{{name}}">{{name}}</option>
{{/each}}
</select>
My javascript:
var dropdownStreet = $('#street');
var dropdownDistrict = $('#district');
$('#district').change(function () {
dropdownStreet.empty();
dropdownStreet.html('')
var value = $('#district').find(":selected").text();
$.ajax({
type: 'GET',
url: `http://localhost:3002/api/ajaxcall/getLocation`,
data: {
'value': value
},
success: function (data) {
console.log('success');
var result = data.data.streets
var streets = [];
streets = result.map(function (a) { return a.location; });
for (var i = 0; i < streets.length; i++) {
$('select[name=street-select]').append('<option value="' + streets[i] + '">' + streets[i] + '</option>').selectmenu('refresh',true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
})
})
Thank you in advance.
I've had a bug like you, and I did the following, and it worked.
Try replacing your loop to something like this:
for (var i = 0; i < streets.length; i++) {
$('select[name=street-select]').append(
$('<option>', {
value: streets[i],
text: streets[i]
})
)
}
You can refer to here: Adding options to a <select> using jQuery?
#Tran Audi's answer was fantastic. In addition, a friend of mine found out what makes the select box doesn't reload itself.
He found out that the template of the website is using a library call Zelect. However, when i try to append the option, Zelect somehow does not reload the select box. So all i have to do is forcing Zelect to reload the selet box and everything works fine.
$(".intro.street .zelect").remove()
$('.intro.street select').zelect({})
I have to add these lines after appending the options.

Best way to avoid auto-complete drop down from appending same value multiple times?

I have a search form which has some ajax querying the database as the user types and listing similar results in a datalist. The issue I was having is as a user typed, it would continuously append a match it already found. To illustrate:
User types: "d"
Datalist: <option value = "dog">
User types: "do"
Datalist: <option value = "dog"> <option value = "dog">
User types: "dog"
Datalist: <option value = "dog"> <option value = "dog"> <option value = "dog">
I solved the issue by emptying the existing data lists on every key-up event before re-appending the current matches. It works, except that it causes the results to appear to flash in the data list as you type as it is constantly toggling between having options in the data list, having no options, then having options again. What is the better way of handling this scenario?
Current JS:
$(document).ready(function() {
$(window).on('load', function(){
var search_input = $("#listing-search-bar")
if (search_input) {
search_input.keyup(function(e){
autocomplete(e);
});
};
function autocomplete(el) {
var input = el.target;
var min_chars = 0;
if (input.value.length > min_chars) {
$.ajax({
type: 'GET',
url: "/listings/search",
data: {"query" : input.value},
dataType: "json"
}).done(function(response) {
// Delete existing results to prevent same result appending multiple times
$("#cities").empty();
response.forEach( function(city) {
// Append all matching cities to drop down
$("#cities").append(`<option value="${city}"></option>`);
});
});
};
};
});
});
You can simply check if element exist before adding it to the DOM:
if ( !$('#cities option[value="'+city+'"]').length )
$("#cities").append(`<option value="${city}"></option>`);

Append Selected Drop Down Value with Option in Laravel Blade with Jquery

I want to show the models by changing the Drop Down value....I know how to get the value of drop down with change function but my problem is that i want to send that value in route to filter the models.....Please tell me how can i send the changed value id with route from blade..
This is my Drop Down
<select class="form-control" id="category" placeholder="Select category">
<option>All</option>
#foreach($categories as $category)
<option value="{{route('contributors.index')}}?category={{ $category->id }}">{{$category->name}}</option>
#endforeach
</select>
Here i my Jquery Change Function
$('#category').change(function(){
alert($(this).val());
})
Explanation :
Please check the below picture....I want to show the models(in the same view)which are related to that category selected in the drop down.
Add this to redirect you to the specific route. For you, it refreshes the page with the selected id in URL. So, models will filter for the given category_id.
$('#category').change(function(){
window.location = "domain.com/route/" + $('option:selected', this).val();
})
Of course, you should use your own URL instead of the URL in the example.
You can use ajax call to append and send category value to your route
$( "#category" ).change(function() {
var id=$(this).val();
$.ajax({
type: 'GET',
url: your url goes here,
success: function (data) {
//here yuo can append to model div
},
error: function (data) {
console.log(data);
}
});
});
the above code is sample for ajax request

Default selected value of dropdown menu using Jquery

I have 3 nested dropdown menus which are dynamically populated from a mysql database and I use Jquery. I want to set a selected value, depending on the entry in my database.
For example:
I have a table that contains many devices. Each device has its storage place (room, shelve, box). Notice: different rooms contain different shelves which contain different boxes, thats why I use a nested dropdown menu.
Next to each device is a button "change".
What I want is that the current storage place of the device is already selected in my dropdown menu.
This is part of my JS functions (got them from another site, I'm very new to JS):
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
mySelect.append($('<option></option>').val(optionValue).html(optionText));
});
}
This is my html code:
Raum:</br></br><select name="manufacturer" id="manufacturer" >
<option value="">Auswahl:</option></select> </br></br>
Regal:</br></br> <select name="printertype" id="printertype" disabled="disabled" >
<option value="">Auswahl:</option></select> </br></br>
Kiste:</br></br><select name="printermodel" id="printermodel" disabled="disabled" >
<option value="">Auswahl:</option></select></br></br>
<div id="loading" style="display: none;"></div>
<div id="output" ></div>
Part of my ajax code:
jQuery().ready(function($){
$('#loading')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
// Ajax Called When Page is Load/Ready (Load Manufacturer)
jQuery.ajax({
url: 'man_list.php',
global: false,
type: "POST",
dataType: "xml",
async: false,
success: populateComp
});
Sorry for that much code, I hope anyone has a good solution for me, which I (the JS noob) can understand :)
You can check your server's response while populating dropdown options
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
var $opt = $('<option> </option>').val(optionValue).html(optionText);
if(/* compare current data with your device here */) $opt.attr("selected", "selected");
mySelect.append($opt);
});
}

On change on multiple select jquery with Ajax and PHP

I have a multiple selection in my HTML page which is generated in an AJAX response: the format is like this:
<div>
<select class='myselect' idselect=1>
<option value='private'>Private</option>
<option value='public'>Public</option>
</select><button idfeed=1 class='change'>Change status</button></div>
<div>
<select class='myselect' idselect=2>
<option value='private'>Private</option>
<option value='public'>Public</option>
</select><button idfeed=2 class='change'>Change status</button>
</div>......
In my jquery/Ajax I have something like that (the code which generating the HTML above):
<script>
$( document ).ready(function() {
var id= $('#idUser').val();
//console.log('findAll');
$.ajax({
type: 'GET',
url: 'http://localhost/ws/api/getUserFeeds/'+id,
dataType: "json", // data type of response
success:function(data){
//alert(data[0].URL);
$.each(data, function (i) {
var toappend="<div><select class='myselect' idselect="+data[i].id+"><option value='private'>Private</option><option value='public'>Public</option></select><button idfeed="+data[i].id+" class='change'>Change status</button></div>";
console.log(toappend);
$("#foo").append(toappend+"<div id=rss"+i+ ">"+i+"</div>");
$('#rss'+i).FeedEk({
FeedUrl: data[i].URL,
MaxCount: 1,
DateFormat: 'MM/DD/YYYY HH:mm'
});
});
}
});
});
</script>
And when I want to retrive the value of selected by user which must either private or public I use this jquery code to select,but the problem is that it select only private all time.
<script type="text/javascript">
$(document).on('change','.myselect',function(){
var selectvar = $('.myselect').val();
console.log(selectvar);
});
</script>
As you can see I display in my console the value of the selected one,and using the JQuery change event.
I try by many ways to try to make it work but it always return private(My select is composed of two choice:private and public)
Thanks for your help!!!
You made a small mistake at the end. You should retrieve your select input with $(this), not $('.myselect') :
$(document).on('change','.myselect',function(){
var selectvar = $(this).val();
console.log(selectvar);
});
Try this
DEMO
$(document).on('change','.myselect',function(){
var selectvar = $(this).val();
console.log(selectvar);
});
$(this) = > the element changed
$(".myselect") => it can be any of the two select elements in your
given html

Categories

Resources