簡體   English   中英

從JavaScript中的多項選擇中獲取所選項目的第一價值?

[英]Get first value of selected items from a multiple select in JavaScript?

我有以下代碼可以從JavaScript中獲取選定選項的文本:

form_name.select_name.options[form_name.select_name.selectedIndex].text

例如,

<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>

當用戶選擇3時,代碼將返回3。

我的問題是,當它是多個選擇時,例如:

<select multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>

如何在JavaScript中返回第一個選定項的文本? 例如,當選擇2和3時,它將返回2。

任何幫助,將不勝感激。 謝謝!

您可以使用jQuery來做到這一點:

$('select option:selected').first().text()

見下文

<html>
<body>
<form name="myForm">
<select name="myOption" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type=submit value="Print First" onClick="printMe()">

<input type=submit value="Print All" onClick="printAll()">

</body>
<script>
function printMe() {
alert ("Selected option is " + myForm.myOption.value);
}

function printAll() {

var str="",i;

for (i=0;i<myForm.myOption.options.length;i++) {
    if (myForm.myOption.options[i].selected) {
        str = str + i + " ";
    }
}

alert("Options selected are " + str);
}


</script>
</html>

希望這就是你想要的...

我還提供了全部打印和第一個選項的打印...

祝好運

這樣的事情應該可以完成,並且很容易修改以獲取所有值或特定索引。

var selected = ''; // make this into an array to get all / specific value
var mySelect = form_name.select_name;

while(mySelect.selectedIndex != -1)
{
    if(mySelect.selectedIndex != 0)
    {
        selected = mySelect.options[mySelect.selectedIndex].text; // change this to selected.push(...) for all/specific values
    }
}

if (selected.length)
{
    // at least one thing was selected, have fun
}

的HTML

<select id="your-select" multiple="multiple">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

的JavaScript

function getFirstSelected(yourSelectId)
{
  var yourSelect = document.getElementById(yourSelectId);

  var optionLength = yourSelect.options.length;

  for (i = 0; i < optionLength; i++) {
    var option = yourSelect.options[i];

    if (option.selected) {
      return option.value;
    }
  }
  return "";
}

用法

var firstSelectedOption = getFirstSelected("your-select");

編輯

剛剛意識到,這將為您提供第一個選定的值,並且不需要該功能

var firstSelectedOption = document.getElementById("your-select").value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM