Dropdown change event not working for one option in dropdown - javascript

I am dynamically adding a select tag ,and appending option from the data comming from server and on change of the dropdown i have to put the selected data in textbox,
But if there is only one option onchange event will not work what should i do please help
My problem will be more clear by below example
var dynamicHtmlDisplay = "<input type=\"button\" Value=\"" + strAf_Manual + "\" class=\"btnAddManual\" /> </br>"
dynamicHtmlDisplay += "<select class=\"Test form-control\"><option>--</option></select>"
And after a server call i am fillin the dropdown
$('.Test').empty();
$.each(Result, function (i, p) {
$('.Test').append($('<option></option>').val(JSON.stringify(p)).html(p.Text));
});
And on change event i am entering the selected text in an textbox
$(".Test").change(function () {
var selectedObject = JSON.parse($('option:selected', this).val())
});
But if only one value is there in dropdown my change does not work is there anything else instead of onchange event ,Something like onselect event.

As you can read from the documentation for https://api.jquery.com/change/
It only works when you change the value of the dropdown, is there is only one value you didn't "change" it.
A solution is to add a blank value which is deleted after your first change call
<option value="0"></option>
<option value="1">First option</option>
$("#select1").change(function(){
// You delete the blank value for the first call
$("#select1 option[value=0]").remove();
...

Normally Dropdown change event will not fire if you select the same dropdown option.So it will not work for a single value.

Parshuram,
I assume that you are going to load select control using code behind and the below code would still work if you maintain classes and on function.
I hope this will help you. All you need is on function. Enjoy!
$(function(){
var Result = [{id:'1', value:'One'},{id:'2',value:'Two'}];
$('.Test').empty();
$.each(Result, function (i, p) {
$('.Test').append($('<option></option>').val(p.id).html(p.value));
});
$('.form-wrapper').on('change','.Test',function(){
console.log('You have selected: ' + $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-wrapper">
<input type="button" Value="Add Option" class="btnAddManual" /> </br>
<select class="Test form-control"><option>--</option></select>
</div>

Related

How to update a dropdown list dynamically using JQuery?

I have a dropdown list which is initially empty:
<div>
<label>Boarding Point </label>
<select title="Select pickup city" id="boardingDropdown">
</select>
</div>
I want to update it from the json data obtained from an API.
I can print the data obtained from API in the console, but I cannot
add it to the dropdown using jquery.
here is my jquery code
$.getJSON(busApi, function(boardingPoints) {
$.each(boardingPoints, function(index, value){
let $boardingOption = $("<option>" + value + "</option>");
$("#boardingDropdown").append($boardingOption);
});
});
The dropdown just shows undefined without any other data.
I have tried other similar questions (like this and this) but they did not solve my problem.
Could somebody tell me what am I doing wrong?
Thanks.
Edit:
console.log(value) shows the output
Kathmadnu
Birgunj
Pokhariya
Langadi Chowk
Bhiswa
Birgunj
which is the expected output from the api.
I created a list with this data
let buses=["Kathmadnu",
"Birgunj",
"Pokhariya",
"Langadi Chowk",
"Bhiswa",
"Birgunj"
];
Now the list still show undefined initially, but if I click on it, it shows the dropdown list as expected.
Does it mean there is problem with the API? But I can see the data obtained from the API in the console?
Try this solution:
$.each(items, function (i, value) {
$('#boardingDropdown').append($('<option>', {
value: value_value,
text : text_value
}));
});
The output should be something like this:
<select title="Select pickup city" id="boardingDropdown">
<option value="value_value">text_value</option>
</select>
Instead of:
let $boardingOption = $("<option>" + value + "</option>");
you should use:
let boardingOption= "<option>" + value + "</option>";
And in your code:
$(#boardingDropdown").append($boardingOption);
you missed a quote mark, it should be: $("#boardingDropdown")
Finally, according to my corrections, it should become:
$("#boardingDropdown").append(boardingOption);
Found the problem:
I had given id to the <select> tag and was adding the options to this tag.
<select title="Select pickup city" id="boardingDropdown">
</select>
Instead, what I did was to create a <div> tag above the <select> tag, and append <select>, then <option> and then </select> from the jquery.
<div>
<label>Boarding Point </label>
<div id="boardingDropdown"></div>
</div>
Then in the jquery, I appended the <select> tag as well:
$.getJSON(busApi, function (boardingPoints) {
let opt = '<select>';
$.each(boardingPoints, function (index, value){
opt += '<option value="' + index + '">' + value + '</option>';
});
opt += '</select';
$("#boardingDropdown").append(opt);
});
Now it is working as expected. :)

Remove Value When an option is deselected

Edit:: What I am trying to achieve is I am getting each option text not the value, so I can send it to an API. Getting the text from the select works perfectly. I want to remove it when I deselect an option from the input value when I click it again. For example if I select multiple I get Medit-4-packs, Swiss-Gear-Bag When I click it one by one it removes it but when I deselect multiple I get the value of another. I want to replace the value as empty when deselected like usual. Hope it helps to clarify
Any help on using jquery to deselect Select option from input value? These are what I have tried so far. Thanks for help
Trying to remove the values in the <input> when option gets deselected.
<input class="form-check-input" type="text" value="" id="equipment" name="equipmentitems" >
<select multiple class="image-picker show-labels show-html" data-limit="16" name="packages[]" id="group_psoft">
<option value=" " data-img-class="first" selected></option>
<option data-img-src="/images/" data-img-label="Scanner Tips(4Pcs)" name="packs" data-img-alt="KeepSame" value="400" >Medit-4-packs</option>
<option data-img-src="/images/" data-img-label="SwissGear Bag" name="bagoriginal" data-img-alt="Aggresive" value="200"> Swiss-Gear-Bag</option>
</select>
Js
$('.image-picker').imagepicker({
show_label: true,
limit: 15,
//This is setting the text in the input
selected: function($items) {
$('#equipment').val($(this).find('option:selected').text());
},
// Here I want to remove it if clicked again
changed: function(){
$('#equipment').val($(this).unbind('option:selected').text()); // This removes it but add all the other options text in the input
$('#equipment').val($(this).unbind('option:selected').val( )); // Here It removes it but I get the value of the next selected option.
$('#equipment').val($(this).unbind('option:selected').text(' ' )); This I get Js [object,object]
}
});
I solved it when I move the code outside the function. I also changed unbind() to on() method.
$('.image-picker').on('change', function() {
$('#equipment').val($(this).find('option:selected').text());
});
Try this and see if it works out.
$('.image-picker').imagepicker({
show_label: true,
limit: 15,
//This is setting the text in the input
selected: function($items) {
$('#equipment').val($(this).find('option:selected').text());
},
// Here I want to remove it if clicked again
changed: function(){
var equiValue = $('#equipment').val();
var selectedValue = $(this).find('option:selected').text();
if(equiValue === selectedValue) {
$('#equipment').val("");
}
}
});

Get value from dynamically created droplist

I my code I create droplists and hidden field for each of them to be able to catch selected value in code behind. I do have a problem set hidden value to the value of selected item in droplist probably because I am not able to create correct selector.
Name of my droplist are dropTypeXXY where XX stands for two alphanumeric characters and Y stands for number for example.
dropTypeU19, dropTypeBB22, dropTypeAG71
hidden fields for them are hdnY where Y stands for number
hdn9, hdn22, hdn71
In both cases these values are IDs of given html elements.
My question is how can I assign list item value to hidden field when droplist selection is changed.
My jQuery
$(document).ready(function(){
$("select[id^='dropType']").on("change",function () {
alert("HI"); //Just to test the selector itself.
});
});
Edit:
My problem is that the selector is not working and alert is not even called. Whey I try to apply similar approach to droplist that I create in code behind it works but not for droplists created by jQuery.
var list = $("<select id = dropType" + response.d[i].TypeId+ i + "/>");
var valueField = $("<input type='hidden' id = 'hdn" + i + "' name ='hdn" + i + "' value=-1 />");
...
$("#<%=grdUsers.ClientID%>").after(list, valueField);
I create them based on AJAX call. I am able to display them in console and display them to user and even give them items but I am not able to run .change() event on them.
Sorry I did not mentioned it earlier.
This doesn't work for them as well. Is there a problem with html tags that are not part of DOM from the beginning of page life?
$("select").on("change", function () {
alert("hi");
});
Edit 2
I looks like my answer lies here. It actually works and alert is raised. Thank you very much guys I'll try to implement the data-target and class trick.
With Dynamically created controls it is easier to select them by class since you cannot use ClientID. Go give them a unique CssClass in code behind when creating the Control.
DropDownList ddl = new DropDownList();
ddl.Items.Insert(0, new ListItem("Value A", "0", true));
ddl.Items.Insert(1, new ListItem("Value B", "1", true));
ddl.CssClass = "DynamicDropDown";
Panel1.Controls.Add(ddl);
Now you can select them with jQuery like this
$(document).ready(function () {
$(".DynamicDropDown").on("change", function () {
alert("HI");
});
})
You can use a class selector ("select" for example) (instead of an id) and add an attribute data-target in your html that say which hidden field is linked to this droplist.
And your js can be something like :
$(document).ready(function(){
$("select.select").on("change",function () {
var $target = $($(this).attr("data-target"));
$target.val($(this).val());
});
});
Or you can also use DOM navigation to find the hidden field without any id if you know the structure of your code and if it's always the same.
Pseudo html code :
<div>
<select>...</select>
<input type="hidden">
</div>
jQuery :
$(document).ready(function(){
$("select").on("change",function () {
var val = $(this).val();
$(this).parent().find("input").val(val);
});
});
You can do it by adding class to a name you specify.
<select id="dropTypeU19" class="cls-name">
<option value="a">a</option>
<option value="a1">a</option>
</select>
<select id="dropTypeBB22" class="cls-name">
<option value="b">a</option>
<option value="b1">a</option>
</select>
<select id="dropTypeAG71" class="cls-name">
<option value="c">a</option>
<option value="c1">a</option>
</select>
<input type="hidden" id="hdn19" />
<input type="hidden" id="hdn22" />
<input type="hidden" id="hdn71" />
<script>
$(function () {
$("select.cls-name").change(function () {
var selectId = $(this).attr("id");
var selectValue = $(this).val();
var hiddenId = "#hdn" + selectId.slice(-2);
$(hiddenId).val(selectValue);
alert($(hiddenId).val());
});
});
</script>
OR:
$("select[id^='dropType']").change(function () {
var selectId = $(this).attr("id");
var selectValue = $(this).val();
var hiddenId = "#hdn" + selectId.slice(-2);
$(hiddenId).val(selectValue);
alert($(hiddenId).val());
});

How to retrive selected value from string of dropdown markup?

I have a string in which i have markup of drop down.I recive the string of drop down markup from server side now i have to retrive selected value.
for example i have this
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> ";
the variable drop has the markup of dropdown and i want the value of selected text value. In this case the "Saab" is selected and i want the its value which is "saab". So how i can do this?
You can use filter() to get select tag and val() to get the selected value
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> ";
document.write($(drop).filter('select').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Since there is only select tag you can just use $(drop).val()
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> ";
document.write($(drop).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you are using jquery, and you don't mind a little bit of overhead (from jQuery compiling the string), just doing the following should work fine:
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> "
var value = $(drop).val();
val() will then return the value of the selected option.

Issue with SelectBox (country/state)

I got a problem.
I've tried to do a selectbox using boostrap form helpers.(http://js.nicdn.de/bootstrap/formhelpers/docs/state.html)
So I got a selectbox for "country" and an other for "state"
<select id="countries" class="form-control bfh-countries"></select>
<select id="states" class="form-control bfh-states" data-country="countries"></select>
If I choose a value form the country box the states appears in the states box, so everything ok.
But if I use a script
<button onclick="test()" class="btn">Load Country</button>
function test(){
document.getElementById('countries').value = "AU";
}
Nothing appends on the "states" selectbox, I should get the states of the country selected by the function test() right ?
What can I do to fix this ?
http://jsfiddle.net/xf8ech7k/1/
Thanks in advance
The problem there is that you aren't triggerent the "change" event.
Take a look at you modified code
function test(){
var select = document.getElementById('countries')
, event = document.createEvent("UIEvents");
select.value = "AU";
event.initUIEvent("change", true, true);
select.dispatchEvent(event);
}
Then, take a look at this post
As #CBroe says, you can do it in a simpler way by doing:
$("select").val("AU").trigger("change");

Categories