How to set dropdownlist to multiple values? - javascript

The syntax to set a dropdownlist to multiple values is as following:
$("#multiple").val(["Multiple2", "Multiple3"]);
My problem is that I don't know how many values I have. So how do I set a dropdownlist dynamicaly to multiple values with values from an array?

Your code should work as seen in this live demo.
Markup:
<select multiple="multiple" id="multiple">
<option value="1">item 1</option>
<option value="2">item 2</option>
</select>
Script:
$('#multiple').val(['1', '2']);
Result:
​

do a check to know if the array has more values:
if (array[i]) { //DO WHAT YOU NEED}

It's not clear to me what you're trying to achieve.
You can use an array as argument of val() and this is the result:
> Passing an array of element values allows matching <input
> type="checkbox">, <input type="radio"> and <option>s inside of n
> <select multiple="multiple"> to be selected. In the case of <input
> type="radio">s that are part of a radio group and <select
> multiple="multiple"> the other elements will be deselected.
That means that will affect in your case only a select with muptiple choice enabled (and not a simple dropdown list).
If, on the contrary by 'set to multiple values' means adding options to an existing select, val() is not built to do that (for this you can have a look here)

Related

Is there a way in JavaScript to use document.forms for a select tag get a if else compound condition to work

I know you can use document.forms to check if a radio button or checkbox is checked but I am not sure how you could this for a select since it has multiple options.
This is the code I thought I could use.
JavaScript:
var pick_deliv = document.forms[order]
[pick_deliv].checked;
HTML:
<form>
<select name="pick_deliv" id="pick_deliv">
<option value="pick_up">Pick up </option>
<option value="delivery">Delivery </option>
</select>
</form

Need Help to Scrape a Website [duplicate]

I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery.
Using regular JavaScript, I would do something like:
ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
However, I need to do this with jQuery, because I'm using a CSS class for my selector (stupid ASP.NET client ids...).
Here are a few things I've tried:
$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
How can I do it with jQuery?
Update
So as it turns out, I had it right the first time with:
$("._statusDDL").val(2);
When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error
Could not set the selected property. Invalid Index
I'm not sure if it's a bug with jQuery or Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying.
jQuery's documentation states:
[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
This behavior is in jQuery versions 1.2 and above.
You most likely want this:
$("._statusDDL").val('2');
Add .change() to see the option in the dropdown list frontend:
$("._statusDDL").val('2').change();
With hidden field you need to use like this:
$("._statusDDL").val(2);
$("._statusDDL").change();
or
$("._statusDDL").val(2).change();
These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.
Things are a little more complicated if this isn't the case.
To read the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex");
To set the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex", 1);
Note that the prop() feature requires JQuery v1.6 or later.
Let's see how you would use these two functions.
Supposing you had a drop down list of month names.
<select id="listOfMonths">
<option id="JAN">January</option>
<option id="FEB">February</option>
<option id="MAR">March</option>
</select>
You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:
<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />
And here's the JavaScript which these buttons would run:
function btnPrevMonth_Click() {
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
if (selectedIndex > 0) {
$("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
}
}
function btnNextMonth_Click() {
// Note: the JQuery "prop" function requires JQuery v1.6 or later
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
var itemsInDropDownList = $("#listOfMonths option").length;
// If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
if (selectedIndex < (itemsInDropDownList - 1)) {
$("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
}
}
My site is also useful for showing how to populate a drop down list with JSON data:
http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm
Just an FYI, you don't need to use CSS classes to accomplish this.
You can write the following line of code to get the correct control name on the client:
$("#<%= statusDDL.ClientID %>").val("2");
ASP.NET will render the control ID correctly inside the jQuery.
Just try with
$("._statusDDL").val("2");
and not with
$("._statusDDL").val(2);
After looking at some solutions, this worked for me.
I have one drop-down list with some values and I want to select the same value from another drop-down list... So first I put in a variable the selectIndex of my first drop-down.
var indiceDatos = $('#myidddl')[0].selectedIndex;
Then, I select that index on my second drop-down list.
$('#myidddl2')[0].selectedIndex = indiceDatos;
Note:
I guess this is the shortest, reliable, general and elegant solution.
Because in my case, I'm using selected option's data attribute instead of value attribute.
So if you do not have unique value for each option, above method is the shortest and sweet!!
I know this is a old question and the above solutions works fine except in some cases.
Like
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
So Item 4 will show as "Selected" in the browser and now you want to change the value as 3 and show "Item3" as selected instead of Item4.So as per the above solutions,if you use
jQuery("#select_selector").val(3);
You will see that Item 3 as selected in browser.But when you process the data either in php or asp , you will find the selected value as "4".The reason is that , your html will look like this.
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3" selected="selected">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
and it gets the last value as "4" in sever side language.
SO MY FINAL SOLUTION ON THIS REGARD
newselectedIndex = 3;
jQuery("#select_selector option:selected").removeAttr("selected");
jQuery("#select_selector option[value='"+newselectedIndex +"']").attr('selected', 'selected');
EDIT: Add single quote around "+newselectedIndex+" so that the same functionality can be used for non-numerical values.
So what I do is actually ,removed the selected attribute and then make the new one as selected.
I would appreciate comments on this from senior programmers like #strager , #y0mbo , #ISIK and others
If we have a dropdown with a title of "Data Classification":
<select title="Data Classification">
<option value="Top Secret">Top Secret</option>
<option value="Secret">Secret</option>
<option value="Confidential">Confidential</option>
</select>
We can get it into a variable:
var dataClsField = $('select[title="Data Classification"]');
Then put into another variable the value we want the dropdown to have:
var myValue = "Top Secret"; // this would have been "2" in your example
Then we can use the field we put into dataClsField, do a find for myValue and make it selected using .prop():
dataClsField.find('option[value="'+ myValue +'"]').prop('selected', 'selected');
Or, you could just use .val(), but your selector of . can only be used if it matches a class on the dropdown, and you should use quotes on the value inside the parenthesis, or just use the variable we set earlier:
dataClsField.val(myValue);
So I changed it so that now it
executes after a 300 miliseconds using
setTimeout. Seems to be working now.
I have run into this many times when loading data from an Ajax call. I too use .NET, and it takes time to get adjusted to the clientId when using the jQuery selector. To correct the problem that you're having and to avoid having to add a setTimeout property, you can simply put "async: false" in the Ajax call, and it will give the DOM enough time to have the objects back that you are adding to the select. A small sample below:
$.ajax({
type: "POST",
url: document.URL + '/PageList',
data: "{}",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var pages = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#locPage' + locId).find('option').remove();
$.each(pages, function () {
$('#locPage' + locId).append(
$('<option></option>').val(this.PageId).html(this.Name)
);
});
}
});
I use an extend function to get client ids, like so:
$.extend({
clientID: function(id) {
return $("[id$='" + id + "']");
}
});
Then you can call ASP.NET controls in jQuery like this:
$.clientID("_statusDDL")
Another option is to set the control param ClientID="Static" in .net and then you can access the object in JQuery by the ID you set.
<asp:DropDownList id="MyDropDown" runat="server" />
Use $("select[name$='MyDropDown']").val().
Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:
<asp:DropDownList id="MyDropDown" runat="server" />
$("[id* = 'MyDropDown']").append("<option value='-1'> </option>"); //etc
Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
<asp:DropDownList ID="DropUserType" ClientIDMode="Static" runat="server">
<asp:ListItem Value="1" Text="aaa"></asp:ListItem>
<asp:ListItem Value="2" Text="bbb"></asp:ListItem>
</asp:DropDownList>
ClientIDMode="Static"
$('#DropUserType').val('1');
In my case I was able to get it working using the .attr() method.
$("._statusDDL").attr("selected", "");
Pure JS
For modern browsers using CSS selectors is not a problem for pure JS
document.querySelector('._statusDDL').value = 2;
function change() {
document.querySelector('._statusDDL').value = 2;
}
<select class="_statusDDL">
<option value="1" selected>A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<button onclick="change()">Change</button>
If we want to find from the option name and then selected options with the jQuery please see below code:-
<div class="control">
<select name="country_id" id="country" class="required-entry" title="Country" data-validate="{'validate-select':true}" aria-required="true">
<option value=""> </option>
<option value="SA">Saudi Arabia</option>
<option value="AF">Afghanistan</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IM">Isle of Man</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JE">Jersey</option>
<option value="JO">Jordan</option>
<option value="AE">United Arab Emirates</option>
<option value="GB">United Kingdom</option>
<option value="US" selected="selected">United States</option>
</select>
</div>
<script type='text/javascript'>
let countryRegion="India";
jQuery("#country option:selected").removeAttr("selected");
let cValue= jQuery("#country option:contains("+countryRegion+")").val();
jQuery("#country option[value='"+cValue +"']").attr('selected', 'selected');
</script>
I hope this will help!

Get rid of blank entry in select tag

I have a number of items that get their data from a Json object and populate it using angular.
<select ng-model="MyCtrl.cargoList">
<option ng-repeat="cargo in MyCtrl.cargoList">{{ cargo.name }}</option>
</select>
And whenever I load the form, I get something like this in my console:
<select ng-model="MyCtrl.cargoList">
<option value="? object:25 "?></option>
<option value="">Gloves</option>
<option value="">Jacket</option>
<option value="">Shoes</option>
</select>
I can get the values to appear just fine, but I can't seem to get rid of the very first option. I don't mind the select box showing the very first element in the list, but I don't want it to be a blank line. How do I get rid of it?
You need to select 1st option by default on ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name" & ng-model name should not be same as that of your cargoList.
Markup
<select ng-model="MyCtrl.selectedCargo" ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name">
<option ng-repeat="cargo in MyCtrl.cargoList" value="cargo.name">{{ cargo.name }}</option>
</select>
Demo Plunkr
Use ngOption <option>
The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.
I have used following expression
label for value in array
HTML
<select ng-model="MyCtrl.cargo" ng-options="cargo.name for cargo in MyCtrl.cargoList">
</select>
and In your controller set model value as first element of list
this.cargo = this.cargoList[0]
Also note: You can use MyCtrl.cargoList as model as well as array So you should use another variable to hold the model value.
Use ng-options instead of ng-repeat
<select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList"></select>
You can fine tune the labels/values further if you like, check the documentation here - https://docs.angularjs.org/api/ng/directive/ngOptions
You can ng-init, or set the first value to defualt, something like
MyCtrl.selectedListItem = MyCtrl.cargoList[0]
So if you want a function to detect you have changed the value of the select you would use ng-change like so :
<select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList" ng-change="selectChanged"></select>
In your controller
$scope.selectChanged = function(){
//apply your logic
};

Set all selects lists by class

I have several input type="select" with the same class. All with the same option values. I'm iterating through an array and checking if the option value is in it. If it is then I want all those relevant option values to be selected. I tried with this JQuery but it doesn't update the select dropdown with the selected values:
JS
$(".contacts option").each(function() {
var x = $(this);
if($.inArray(x.val(), selected_values)!= -1){
x.prop('selected', true);
}
});
HTML
<select class="form-control contacts" name="publicPermissions" id="publicPermissions" multiple="multiple">
<option value="share">Share</option>
<option value="private">Private</option>
<option value="user">User Config</option>
<option value="work">Work</option>
</select>
I have several of these selects how can I update them all so they all have the relevent option values selected?
You just need to use .val() method. No need to use loop.
$(".contacts").val(selected_values);
DEMO
After you put some values in selected_values array, it should work. Here is a fiddle

Jquery, read data attribute from all divs that match proper pattern

I have html code that looks like this:
<select id="invoice_line_items_attributes_0_product_id" class="select required form-control" name="invoice[line_items_attributes][0][product_id]">
<option value=""></option>
<option value="34" data-price="123.0">asdsad</option>
<option value="35" data-price="123213.0">asd</option>
</select>
<select id="invoice_line_items_attributes_1_product_id" class="select required form-control" name="invoice[line_items_attributes][0][product_id]">
<option value=""></option>
<option value="31" data-price="1223.0">asdsad</option>
<option value="32" data-price="12333213.0">asd</option>
</select>
And now I want to iterate through all this selects and when one of this change this value alert this date-price attribute. I trying to do this with the following code:
$('[id*="product"]').each ->
$(this).change ->
alert $(this).attr("data-price")
But It gaves me undefined instead of this data-price value.
Three things:
1) You do not need to iterate over select element individually and then bind the even. Selector will do that on its own for matched elements.
2) You need to find selected option and then get data price value.
3) use .data() instead of using .attr() to get data attribute values.
Use:
$('[id*="product"]').change(function(){
alert($(this).find('option:selected').data('price'));
});
Working Demo
That is because your select doesn't have data-attr, I think you want the selected options data-attr.
And to get data-attributes jquery provides .data function.
do like bellow.
$('[id*="product"]').change(function(){
alert($(this).find(':selected').data('price'));
});
DEMO

Categories

Resources