如何使用 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?

本文关键字:属性 文本 内部 value 访问 JavaScript 访问表 表单 标签 选择 何使用      更新时间:2023-09-26

我在 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>

所以现在我需要访问值到属性(例如 0,1,2,3,4)或选项标签的内部文本(例如:"-- 请选择 --"、"关闭"、"活动"、"测试"、"正在启动")。

我可以使用 JavaScript 来做这件事吗?我该如何实现它?

试试这个

  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....)

Pure Javascript

这允许访问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