【问题标题】:javascript getting drop down box valuejavascript获取下拉框值
【发布时间】:2014-01-27 01:56:34
【问题描述】:

我想从下拉框中获取选定的值。 然后我想使用该值来更改背景图像。

我认为有用的两个代码片段:

document.observe("dom:loaded",function(){
initialize();

addTextboxes();
var sel = document.getElementById("select");
for(i = 0; i < pieces.length; i++) {
    pieces[i].observe("click",function(event){
        moveThis(event.toElement.innerHTML-1);
    });
    pieces[i].style.backgroundImage = sel.value;        
}

var e = document.getElementById("select");
alert(e.options[e.selectedIndex].value);

var value = document.getElementById("select").value;
alert(value);

});

function addTextboxes(){
var sel = document.createElement("select");
//Add the options  
sel.options[sel.options.length] = new Option("text0","url(luigi1.jpg)");  
sel.options[sel.options.length] = new Option("text1","url(luigi2.jpg)");  
sel.options[sel.options.length] = new Option("text2","url(luigi3.jpg)");  
sel.options[sel.options.length] = new Option("text3","url(luigi4.jpg)");  
//add the element to the form  
document.getElementById("overall").appendChild(sel);    
}

我已经在其中放置了两个警报来测试是否发生了某些事情,但它们甚至都没有出现。 另外,当我将 forloop 放在 addTextboxes() 函数中时,它会将背景更改为第一个选择的选项,但在更改框时不会更改。

【问题讨论】:

  • 您是否尝试在点击处理程序中放置警报以查看返回的元素?

标签: javascript dropdownbox


【解决方案1】:

我发现您的代码中有一些需要更改的地方。

  • 你不能使用getElementById("select")而不给元素选择ID。 ID 与标签类型不同,并且在整个页面中必须是唯一的。在下面的小提琴中,我为此使用了“mySelect”,以避免混淆。

  • 您不应该在每个选项上监听 click 事件。相反,您应该在整个 select 元素上监听 change 事件。更改后,选择元素的value 将是所选选项的值。

这是一个 fiddle 进行了这些更改

进行这些更改后,所选选项的值现在显示在警告框中。 从这里,您可以更改背景图片或执行其他任何操作。

【讨论】:

  • 点击事件是为了别的东西,但这正是我想要的。谢谢一堆。小提琴很有帮助。
【解决方案2】:

使用 jQuery,这里就是这一行

$( "#selectbox option:selected" ).text();

这将获取所选选项的文本,您始终可以使用此方法获取值:

$( "#selectbox option:selected" ).val();

【讨论】:

  • OP 没有使用 jQuery,因此期望包含整个库就有点过分了。
猜你喜欢
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
  • 2013-02-28
  • 2016-03-05
相关资源
最近更新 更多