如何根据从下拉菜单中选择的选项以HTML格式显示文本?

时间:2017-06-10 05:38:20

标签: javascript html

所以我一直试图做的是有一个带有选项的下拉菜单,并根据选择的选项显示一些文字。

我得到了使用HTML和JavaScript来完成它的结论,但我遇到了麻烦。

对于HTML,我有这个 -

<select id="selectDay">
<option>Choose a Day</option>

对于JavaScript我有这个 - “

var select = document.getElementById("selectDay");
var response1 = ("Response if a Day between Monday through Friday is Selected");
var response2 = ("Response if Saturday or Sunday are selected");

var days = ["Sunday", "Monday", "Tuesday", "Wednesday" , "Thursday", "Friday", "Saturday"];

for(var i = 0; i < days.length; i++) 
{
var opt = days[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);

}

我主要是通过使用Google来实现这一目标,但我现在很难过。我只是想这样做,所以我可以说我完成了一个项目。我甚至不确定我是否正确地做到了。

4 个答案:

答案 0 :(得分:1)

您想要创建一个侦听事件的函数 - 例如select的onChange事件。

var dropDown=document.getElementById("selectDay");
dropDown.onchange=function (){
  alert(dropDown.value);
}

然后在alert()语句所在的函数内部,您可以选择您的回复。

答案 1 :(得分:1)

我们需要在下拉列表中附加一个onchange事件,该下拉列表将获取下拉列表值,并根据该事件显示response1response2。以下是示例代码:

&#13;
&#13;
var select = document.getElementById("selectDay");
var response1 = ("Response if a Day between Monday through Friday is Selected");
var response2 = ("Response if Saturday or Sunday are selected");

var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

for (var i = 0; i < days.length; i++) {
  var opt = days[i];
  var el = document.createElement("option");
  el.textContent = opt;
  el.value = opt;
  select.appendChild(el);
}

function getResponse(eleme) {
  var e = document.getElementById("selectDay");
  var strUser = e.options[e.selectedIndex].value;
  if (strUser == 'Saturday' || strUser == 'Sunday') {
    console.log(response2)
  } else {
    console.log(response1);
  }
}
&#13;
<select id="selectDay" onchange=getResponse()>
<option>Choose a Day</option>
</select>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

在组合框中添加更改事件侦听器,在更改事件内,您将能够获取所选值

$("#selectDay").change(function() {
alert(this.value);//depending upon selected Value choose action});

答案 3 :(得分:0)

foreach ($array1 as $val) {
    if(!isset($array2[$val['Franchise']])) {
       $array2[$val['Franchise']] = array('Inherent' => 0, 'Acquired' => 0);
    }
    $array2[$val['Franchise']][$val['Superpower']]++;
}

print_r($array2);
 for(a=2;a<7;a++)menu.querySelectorAll('option')[a].onclick=function(){
alert('Response if a Day between Monday through Friday is Selected')};
 snd.onclick=strd.onclick=function(){
confirm('Response if Saturday or Sunday are selected')}