JavaScript : 드롭 다운 가치를 얻으십시오
-
13-09-2019 - |
문제
3 개의 HTML 콤보/드롭 다운 상자가 있습니다. 그들 모두는 뚜렷한 이름과 ID를 가지고 있습니다. 특정 이벤트에서 나는 세 가지의 가치를 얻고 싶습니다. 누구든지 나에게 코드 스 니펫을 줄 수 있습니까?
해결책
jQuery 사용 :
$("#dropdownID").val();
다른 팁
HTML에서 서로 옆에 설정 한 다음 jQuery의 각 () 메소드를 사용하여 반복합니다. 다음과 같은 요소를 설정합니다.
<div id="dropdownBoxes">
<select id="firstElement">
<option>cool</option>
<option>neat</option>
</select>
<select id="secondElement">
<option>fun</option>
<option>awesome</option>
</select>
<select id="thirdElement">
<option>great</option>
<option>synonym</option>
</select>
</div>
<input type="button" id="theTrigger">Push me!</input>
그런 다음 스크립트에서 :
var dropdownValues;
$("#theTrigger").click(function(){
dropdownValues.length=0;
$("#dropdownBoxes select").each(function(){
dropdownValues.push($(this).val());
});
});
jQuery를 사용하지 않는이 작업을 수행하려면 :
function getSelectValues() {
var values = [];
for (var i = 0; i < arguments.length; i++) {
var select = document.getElementById(arguments[i]);
if (select) {
values[i] = select.options[select.selectedIndex].value;
} else {
values[i] = null;
}
}
return values;
}
이 함수는 id
다음과 같이 기능으로 전달됩니다.
var selectValues = getSelectValues('id1', 'id2', 'id3');
만약 <select>
지정된 것 중 하나와 함께 id
S는 배열이 포함되어 있지 않습니다 null
그 위치의 가치를 위해.
이 작업을 수행하는 몇 가지 다른 방법이 있습니다. 기능을 배열로 전달할 수 있습니다. id
값 : getSelectValues([ 'id1', 'id2', 'id3' ])
,이 경우 기능이 변경됩니다.
function getSelectValues(ids) {
var values = [];
for (var i = 0; i < ids.length; i++) {
// ...
맵의 함수를 전달할 수도 있습니다 id
s와 값을 채우십시오 :
var myMap = { 'id1': null, 'id2': null, 'id3': null };
getSelectValues(myMap);
// myMap['id1'] contains the value for id1, etc
이것은 기능을 변경합니다.
function getSelectValues(map) {
for (var id in map) {
var select = document.getElementById(id);
if (select) {
map[id] = select.options[select.selectedIndex].value;
} else {
map[id] = null;
}
}
}
위에서 언급 한 jQuery와 같은 프레임 워크를 사용하거나 구식 방식으로 수행하십시오. document.getElementById('dropdownId').value
.
제휴하지 않습니다 StackOverflow