获取字符串,但不从下拉列表选项中选择值

时间:2016-07-18 07:11:17

标签: javascript php select dropdown

我有两个选择框和一个隐藏文本框

<select name="name" id="name" class="form-control input-sm">
  <option value="">- Choose a Name -</option>
 <?php foreach($name as $n) { ?>
  <option value="<?php echo $n->id_name;?>"><?php echo $n->name;?></option>
 <?php } ?>
</select>

<select name="status" id="status" class="form-control input-sm">
  <option value="">- Choose a Status -</option>
 <?php foreach($status as $s) { ?>
  <option value="<?php echo $s->id_status;?>"><?php echo $s->name;?></option>
 <?php } ?>
</select>

<input type="hidden" id="message" name="message" value="">

我所知道的是这样的剧本

function inputKelurahan()
 { var name = document.getElementById("name");
   var status = document.getElementById("status");
   document.getElementById("message").defaultValue = name.value + status.value;
 }

当然,消息将是$ id_name + $ id_status。如何连接$ name + $ status?

提前致谢,

2 个答案:

答案 0 :(得分:2)

听起来你想要所选选项中的文字。然后,您可以先获取selectedIndex,然后选择innerHTML作为选项。

下面是一个简单的代码段,其中包含部分代码。

&#13;
&#13;
function inputKelurahan()
{ 
  var name = document.getElementById("name");
  var status = document.getElementById("status");
  var nameInnerHtml = name.options[name.selectedIndex].textContent; // using textContent as mentioned by james.brndwgn in comments.
  var statusInnerHtml = status.options[status.selectedIndex].textContent;
  alert("Name is: " + nameInnerHtml + ". Status is: " + statusInnerHtml);  
}
&#13;
<select name="name" id="name" class="form-control input-sm">
  <option value="">- Choose a Name -</option>
  <option value="Value1">Name 1</option>
  <option value="Value2">Name 2</option>
  <option value="Value3">Name 3</option>
</select>

<select name="status" id="status" class="form-control input-sm">
  <option value="">- Choose a Status -</option>
  <option value="StatusValue1">Status 1</option>
  <option value="StatusValue2">Status 2</option>
  <option value="StatusValue3">Status 3</option>
</select>

<button onclick="inputKelurahan()">Click me!</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

function inputKelurahan()
 { var name = document.getElementById("name");
   var status = document.getElementById("status");
   document.getElementById("message").value = name.selectedIndex.value + status.selectedIndex.value;
 }