使用选择框的文本(非值)填充文本字段

时间:2015-10-25 18:48:55

标签: javascript html drop-down-menu

我目前有一个填充文本字段(id = costcenter)的选择框(id = title)的值。当我使用选择框的VALUE来触发成本中心字段的填充时,它可以正常工作。但我需要使用选择框的TEXT,而不是值。

这是我目前的代码。如何使用下拉列表的TEXT(而不是VALUE)来触发成本中心字段的填充。

谢谢大家! 瑞克

JAVASCRIPT:

<script language="Javascript">
var com_costcenter = new Array();

com_costcenter["Assistant Director"] = "2043000010";
com_costcenter["Clinical Specialist"] = "2044600011";
com_costcenter["Clinical Apps"] = "2044600011";
com_costcenter["select"] = "";

function setTitle(){
  var text = document.getElementsByName('title')[0].options[document.getElementsByName('title')[0].selectedIndex].value;
  document.getElementsByName('costcenter')[0].value = com_costcenter[text];
}
</script>

HTML:

<select name="title" id="title" onchange="setTitle()">
<option value="Assistant Director">Assistant Director - 2043000010</option>
<option value="Clinical Specialist">Clinical Specialist - 2044600011</option>
<option value="Clinical Apps">Clinical Applications - 2044600011</option>
</select>


<input name="costcenter" type="text" id="costcenter" size="10" maxlength="10" pattern="\d{10}" title="Enter exactly 10 digits"/>

2 个答案:

答案 0 :(得分:1)

试用.innerHTML

    var com_costcenter = new Array();
    
    com_costcenter["Assistant Director"] = "2043000010";
    com_costcenter["Clinical Specialist"] = "2044600011";
    com_costcenter["Clinical Apps"] = "2044600011";
    com_costcenter["select"] = "";
      
    function setTitle(){
      var title = document.getElementsByName('title')[0];
      var text = title.options[title.selectedIndex].innerHTML;
      var number = text.split(" - ")[1];
      document.getElementsByName('costcenter')[0].value = number;
    }
    <select name="title" id="title" onchange="setTitle()">
    <option value="Assistant Director">Assistant Director - 2043000010</option>
    <option value="Clinical Specialist">Clinical Specialist - 2044600011</option>
    <option value="Clinical Apps">Clinical Applications - 2044600011</option>
    </select>
    
    
    <input name="costcenter" type="text" id="costcenter" size="25" maxlength="10" pattern="\d{10}" title="Enter exactly 10 digits"/>

答案 1 :(得分:-1)

我并不完全明白你在寻找什么,但我认为这可能会有所帮助。

<script language="Javascript">
function setTitle(){
    Title = document.getElementById('title');
    TitleText   = Title.options[Title.selectedIndex].text;
    TitleNumber = TitleText.split(" - ")[1];
    document.getElementsByName('costcenter')[0].value = TitleNumber;
}
</script>