簡體   English   中英

如何使用JavaScript訪問表單選擇標簽的value屬性的內容或其內部文本?

[英]How can I acces to the content of the value attribute of a form select tag or to its inner text using JavaScript?

我絕對不是JavaScript新手,在處理表單驗證腳本時遇到一些問題。

所以在我的頁面中,我有一些輸入字段,例如:

<input id="kmProjectInfo_name" class="" type="text" value="" size="19" name="kmProjectInfo.name">

並且我使用以下函數使用document.getElementById('kmProjectInfo_name')。 value從此輸入字段獲取值,並檢查此值是否對我的目的相當有效:

function validateForm() {

    alert(document.getElementById('selectCountry').value)

    // VALIDAZIONE DEL PROJECT NAME:
    if( document.getElementById('kmProjectInfo_name').value == "" )
    {
        alert( "Please provide a valid project name" );
        //document.myForm.Name.focus();
        document.getElementById('kmProjectInfo_name').focus();
        return false;
    }

好的,這個工作很好,但是在我的表單中,我還有一個需要驗證的字段:

<select id="selectStatus" onchange="checkStatus(this)" name="kmProjectInfo.status.idProjectInfoStatus">
    <option value="0">-- Please Select --</option>
    <option id="aui_3_2_0_1240" value="1">Closed</option>
    <option id="aui_3_2_0_1226" value="2">Active</option>
    <option value="3">Testing</option>
    <option value="4">Starting</option>
</select>

因此,現在我需要訪問value屬性中的 (例如0、1、2、3、4)或選項標簽的內部文本(例如:“-Please Select-”,“ Closed “,”有效“,”正在測試“,”正在啟動“)。

我可以使用JavaScript進行此操作嗎? 我該如何實施?

TNX

純Java腳本

這允許訪問innerHtml屬性及其內容。

var myInnerHtml = document.getElementById("forloop").innerHTML;

使用JQuery

.text().html()而不是.innerHTML

是的,您可以獲取select元素的所選索引,然后基於該索引獲取option值:

var select = document.getElementById("kmProjectInfo_name");
var index = select.selectedIndex;

var value = select.options[index].value; //0, 1, 2, 3, 4

嘗試這個

  var el = document.getElementById("selectStatus");

  var value = el.options[el.selectedIndex].value;  // get value (1, 2, 3, ...)
  var text  = el.options[el.selectedIndex].text;  // get text (Closed, Starting....)

暫無
暫無

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

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