jQuery를 사용하여 드롭 다운 목록의 선택한 값 변경
알려진 값이있는 드롭 다운 목록이 있습니다. 내가하려는 것은 jQuery를 사용하여 존재하는 특정 값으로 드롭 다운 목록을 설정하는 것입니다. 일반 JavaScript를 사용하여 다음과 같이합니다.
ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
그러나 선택기 (어리석은 ASP.NET 클라이언트 ID ...)에 CSS 클래스를 사용하고 있기 때문에 jQuery로이 작업을 수행해야합니다 .
내가 시도한 몇 가지 사항은 다음과 같습니다.
$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
jQuery로 어떻게 할 수 있습니까?
최신 정보
그래서 처음에는 다음과 같이 옳았습니다.
$("._statusDDL").val(2);
경고를 바로 위에 놓으면 제대로 작동하지만 경고를 제거하고 최고 속도로 실행하면 오류가 발생합니다.
선택한 속성을 설정할 수 없습니다. 잘못된 색인
jQuery 또는 Internet Explorer 6 (Internet Explorer 6)의 버그인지 확실하지 않지만 매우 성가신 일입니다.
jQuery의 문서 상태 :
[jQuery.val] 은 모든 라디오 버튼, 확인란 및 값 세트와 일치하는 선택 옵션을 확인하거나 선택 합니다.
이 동작은 jQuery
버전 1.2
이상입니다.
아마도 이것을 원할 것입니다.
$("._statusDDL").val('2');
숨겨진 필드를 사용하려면 다음과 같이 사용해야합니다.
$("._statusDDL").val(2);
$("._statusDDL").change();
또는
$("._statusDDL").val(2).change();
참고로이 작업을 수행하기 위해 CSS 클래스를 사용할 필요는 없습니다.
클라이언트에서 올바른 컨트롤 이름을 가져 오려면 다음 코드 줄을 작성할 수 있습니다.
$("#<%= statusDDL.ClientID %>").val("2");
ASP.NET은 jQuery 내에서 컨트롤 ID를 올바르게 렌더링합니다.
그냥 시도
$("._statusDDL").val("2");
그리고
$("._statusDDL").val(2);
이러한 솔루션은 드롭 다운 목록의 각 항목에 드롭 다운 목록 에서의 위치와 관련된 val () 값 이 있다고 가정하는 것 같습니다 .
그렇지 않은 경우 상황은 조금 더 복잡합니다.
드롭 다운 목록에서 선택한 색인 을 읽으 려면 다음을 사용합니다.
$("#dropDownList").prop("selectedIndex");
드롭 다운 목록의 선택된 인덱스 를 설정 하려면 다음을 사용합니다.
$("#dropDownList").prop("selectedIndex", 1);
점을 유의 소품 () 기능은 JQuery와 V1.6 이상이 필요합니다.
이 두 가지 기능을 어떻게 사용하는지 살펴 보겠습니다.
월 이름 드롭 다운 목록이 있다고 가정합니다.
<select id="listOfMonths">
<option id="JAN">January</option>
<option id="FEB">February</option>
<option id="MAR">March</option>
</select>
현재 선택된 드롭 다운 목록 항목을보고 이전 / 다음 달로 변경하는 "이전 달"및 "다음 달"단추를 추가 할 수 있습니다.
<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />
다음은이 버튼이 실행되는 JavaScript입니다.
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);
}
}
다음 사이트도 JSON 데이터로 드롭 다운 목록을 채우는 방법을 보여주는 데 유용합니다.
http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm
휴 !!
도움이 되었기를 바랍니다.
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)
);
});
}
});
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"
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.
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="MyDropDown" runat="server" />
Use $("select[name$='MyDropDown']").val()
.
<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", "");
참고URL : https://stackoverflow.com/questions/499405/change-the-selected-value-of-a-drop-down-list-with-jquery
'Programing' 카테고리의 다른 글
substr과 substring의 차이점은 무엇입니까? (0) | 2020.09.29 |
---|---|
문자열 내에서 문자열 (실제로 문자)의 발생 횟수를 어떻게 계산합니까? (0) | 2020.09.29 |
파이썬 프로그램 실행 시간을 어떻게 얻습니까? (0) | 2020.09.29 |
시간 초과로 Redux 작업을 전달하는 방법은 무엇입니까? (0) | 2020.09.29 |
키로 사전을 정렬하려면 어떻게해야합니까? (0) | 2020.09.29 |