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());
});
I have dropdownlist on a webform. I need a 'hidden' variable per item in the dropdown list which I can retrieve clientside using the onchange event.
So on the page load I'm setting a custom attribute after I databind the dropdownlist:
For i = 0 To cboNameAL.Items.Count - 1
cboNameAL.Items(i).Attributes.Add("Charge_Rate", usernamesAdapterDataTable.Item(i).ChargeRate)
Next
This works and when I look at my rendered page I see this markup for each item in the dropdownlist
<option value="05ab8c45-f7ce-4250-8458-1421e79e8a51" charge_rate="32">dave</option>
My javascript function is firing fine from the onchange event, however I can't retrieve the attribute value for Charge_Rate.
I've tried every combination of:
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").selectedItem.attributes('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").attributes('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>")attr('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").getAttributes('Charge_Rate');
Each with either ('Charge_Rate') or ("Charge_Rate") or .Charge_Rate
I've debugged and the best I can do is for my variable lCharge_Rate to be null.
Any ideas? Happy to rework if it can't be done this way...
You can use the following code to get the value of your custom attribute
//This line will load the DOM of dropdown
var cboNameAL = document.getElementById("<%=cboNameAL.ClientID%>");
//This will return the selected option
var selectedOption = cboNameAL.options[cboNameAL.selectedIndex];
//This will give you the value of the attribut
var charge_rate = selectedOption.attributes.charge_rate.value;
You need to select the options first before you can get the attribute.
var e = document.getElementById("client_id"),
lCharge_Rate = e.options[e.selectedIndex].getAttribute('charge_rate');
document.write("Charge Rate = "+lCharge_Rate);
<select id="client_id">
<option value="05ab8c45-f7ce-4250-8458-1421e79e8a51" charge_rate="32">dave</option>
</select>
Create a variable that equals the value of your custom attribute, then use it as you desire. See my example and adjust as needed.
var $divAtribut = $("div").attr("Charge_Rate");
alert($divAtribut);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div Charge_Rate="4424">Click on run to get the attribute</div>
<code>
<!– my html –>
<select name="custom-select-two">
<option value="1" data-monthvalue="31">Jan</option>
<option value="2" data-monthvalue="28">Feb</option>
<option value="3" data-monthvalue="31">Mar</option>
<option value="4" data-monthvalue="30">Apr</option>
<option value="5" data-monthvalue="31">May</option>
<select>
<!– Get value of option’s custom attribute value from dropdown or select box –>
<script type="text/javascript">
$(document).ready(function(){
var monthvalue = $('.custom-select-two :selected').data('monthvalue');
alert(monthvalue); // here comes your dropdown option's custom attribute value
});
</script>
</code>
I have a datalist with options and a custom attribute.
<input list="selectedItems" class="selectedItemsList"></input>
<datalist id="selectedItems">
<option value="test11" oldvalue="f1"></option>
<option value="test12" oldvalue="f2"></option>
</datalist>
It is displayed on a popup. When a popup closes the value and custom attribute value must be used in a function...
I tried:
alert($("#selectedItems option:selected").val());
alert($("#selectedItems option:selected").attr("oldvalue"));
$('.selectedItemsList option').each(function() {
if($(this).is(':selected')){
alert($(this).val());
}
});
for (var i=0; i<document.getElementById('selectedItemsList').options.length; i++)
{
if (document.getElementById('selectedItemsList').options[i].value == document.getElementsByName("selectedItems")[0].value)
{
alert(document.getElementById('selectedItemsList').options[i].value);
break;
}
}
Nothing works.
I can get the values using on-event but that is not an option for me.
$('.selectedItemsList').on('input', function() { ...
alert($(this).val());
$(function(){$("input[name=selectedItems]").on('input', function(){// selects which array raw is edited
for (var i=0; i<dList.length; i++) if(dList[i].ItemName===$(this).val()) { num = i;
$(".selectedItems option[value="+dList[num].ItemName+"]").val($(this).val());
dList[num].ItemName=$(this).val();
});
});
So, I use datalist oninput event to get the selected value. Then, I edit a raw of an array of values that represents the datalist values.
var dList=[];num=0;
dList.push({ItemName: $(this).attr('value'), ViV: vs[0], NU: vs[1], ItemKey: $(this).attr('key')});
Essentially, I believe the problem is related to your selector use. I'm making the assumption that you're trying to get the old value from the datalist. On closing your popup, you should get the value of the input first
var inputval= $(".selectedItemsList").val();
alert(inputval);
then grab the associated oldvalue based on the value of the input.
var oldval= $('datalist#selectedDevices option[value='+inputval+']').attr('oldvalue');
if (oldval)
alert(oldval);
I created a jsfiddle for you here to play around with.
http://jsfiddle.net/jornjjt6/
I've got a multiple select that I want to use to pick which elements show up in an HTML template window. So I have several options that I want to iterate over, and based on whether it's been selected, make the preview elements visible or hidden.
I'm going for something like this:
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
$(??????).css($css);
});
As you can see, I'm just iterating over each option (I'm pretty sure that syntax works) in my area_select menu, but I don't know how to make the css get applied to the corresponding piece.... how can I reference my preview elements via my options?
An easier way to go is to call .val() on the multiple select. That returns an array of selected values that you can iterate over.
var array = $('#area_select').val()
$.each(array, function(i,val) {
// your code
});
So as far as showing the elements is concerned, it would depend on what type of data is stored in the value of the select options.
For an ID, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('#' + value).css('visibility','visible');
});
Or if they are class names, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('.' + value).css('visibility','visible');
});
Give each of the options a name corresponding to the ID of the correct piece.
e.g.
<select>
<option value="whatever">Whatever</option>
<option value="whatever2">Whatever 2</option>
</select>
Then each of you elements will be contained in a a div like this:
<div id="whatever-preview">
<!-- Whatever -->
</div>
Then your Javascript
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
var div_name = "#" + $(this).attr('value') + "-preview";
$(div_name).css($css);
});
Give each option an id referencing the id of the corresponding element in the preview window.
for instance:
<option id="option-1">This turns on the first option element in the preview window</option>
<option id="option-2">This turns on the first option element in the preview window</option>
and give the preview window elements similar-ending ids:
<div id='window-1'>corresponding window preview element</div>
Then in the javascript:
$("#window-" + $(this).attr('id').split('-')[1]).css($css);
First, give the elements to hide or show the same class but id's matching the options values:
<div class="something" id="val_1">content1</div>
<div class="something" id="val_2">content2</div>
<div class="something" id="val_3">content3</div>
<div class="something" id="val_4">content4</div>
<select id="area_select">
<option value="val_1">val 1</option>
<option value="val_2">val 1</option>
<option value="val_3">val 1</option>
<option value="val_4">val 1</option>
</select>
then, when the select choosen option changes hide all the stuff and show the selected
$('#area_select').change( function(){
var val = $(this).val();
$('.something').hide();
$('#'+val).show();
return false;
});
Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
<Select id="mySelect" size="9"> </Select>
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)
$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
EDIT: selected answer was close to what I needed. This worked for me:
$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
But both answers led me to my final solution..
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
why not just use plain javascript?
document.getElementById("selectID").options.length = 0;
If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:
$('#mySelect').find('option:not(:first)').remove();
I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.
The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.
$('#mySelect')[0].options.length = 0;
Not sure exactly what you mean by "add one and select it", since it will be selected by default anyway. But, if you were to add more than one, it would make more sense. How about something like:
$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();
Response to "EDIT": Can you clarify what you mean by "This select box is populated by a set of radio buttons"? A <select> element cannot (legally) contain <input type="radio"> elements.
$('#mySelect')
.empty()
.append('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected")
;
$("#control").html("<option selected=\"selected\">The Option...</option>");
Just one line to remove all options from the select tag and after you can add any options then make second line to add options.
$('.ddlsl').empty();
$('.ddlsl').append(new Option('Select all', 'all'));
One more short way but didn't tried
$('.ddlsl').empty().append(new Option('Select all', 'all'));
Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including "selected" in the option that I wanted selected.
$(function() {
$('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
$("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
// Bind click event to each radio button.
$("input[name='myRadio']").bind("click",
function() {
switch(this.value) {
case "1":
$('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
break ;
case "2":
$('#mySelect').find('option').remove() ;
var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
var options = '' ;
for (var i = 0; i < items.length; i++) {
if (i==0) {
options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
}
else {
options += '<option value="' + items[i] + '">' + items[i] + '</option>';
}
}
$('#mySelect').html(options); // Populate select box with array
break ;
} // Switch end
} // Bind function end
); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input name="myRadio" type="radio" value="1" /></label>
<label>Two<input name="myRadio" type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>
I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.
var ClearOptionsFast = function(id) {
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
More info here.
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');
The first line of code will remove all the options of a select box as no option find criteria has been mentioned.
The second line of code will add the Option with the specified value("testValue") and Text("TestText").
Building on mauretto's answer, this is a little easier to read and understand:
$('#mySelect').find('option').not(':first').remove();
To remove all the options except one with a specific value, you can use this:
$('#mySelect').find('option').not('[value=123]').remove();
This would be better if the option to be added was already there.
How about just changing the html to new data.
$('#mySelect').html('<option value="whatever">text</option>');
Another example:
$('#mySelect').html('
<option value="1" selected>text1</option>
<option value="2">text2</option>
<option value="3" disabled>text3</option>
');
Another way:
$('#select').empty().append($('<option>').text('---------').attr('value',''));
Under this link, there are good practices https://api.jquery.com/select/
First clear all exisiting option execpt the first one(--Select--)
Append new option values using loop one by one
$('#ddlCustomer').find('option:not(:first)').remove();
for (var i = 0; i < oResult.length; i++) {
$("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
}
Uses the jquery prop() to clear the selected option
$('#mySelect option:selected').prop('selected', false);
This will replace your existing mySelect with a new mySelect.
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
You can do simply by replacing html
$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
I saw this code in Select2 -
Clearing Selections
$('#mySelect').val(null).trigger('change');
This code works well with jQuery even without Select2
Cleaner give me Like it
let data= []
let inp = $('#mySelect')
inp.empty()
data.forEach(el=> inp.append( new Option(el.Nombre, el.Id) ))
save the option values to be appended in an object
clear existing options in the select tag
iterate the list object and append the contents to the intended select tag
var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};
$('#selectID').empty();
$.each(listToAppend, function(val, text) {
$('#selectID').append( new Option(text,val) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I used vanilla javascript
let select = document.getElementById("mySelect");
select.innerHTML = "";
Hope it will work
$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
var d = data[i];
var option = $('<option/>').val(d.id).text(d.title);
select.append(option);
}
select.val('');
Try
mySelect.innerHTML = `<option selected value="whatever">text</option>`
function setOne() {
console.log({mySelect});
mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9">
<option value="1">old1</option>
<option value="2">old2</option>
<option value="3">old3</option>
</Select>
The shortest answer:
$('#mySelect option').remove().append('<option selected value="whatever">text</option>');
Try
$('#mySelect')
.html('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected");
OR
$('#mySelect').html('<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
<option value="7">Value 7</option>
<option value="8">Value 8</option>')
.find('option:first')
.prop("selected",true);