在文本框中输入文本

时间:2013-08-09 09:17:30

标签: javascript html

任何人都可以告诉我为什么jsFiddle不起作用?

这个想法很简单,只是假设将所选文本输入到文本框中。

HTML:

<input type="text" id="teste" maxlength="50">
<select>
    <option onClick="nelson">nelson</option>
</select>

JavaScript的:

function nelson(){
    document.getElementById('teste').value =+ "nelson"; 
}

提前致谢

6 个答案:

答案 0 :(得分:8)

DEMO: jsFiddle

<强> HTML:

<input type="text" id="teste" maxlength="50" />
<select onchange="selectedItemChange(this)">
    <option value="nelson">nelson</option>
    <option value="justin">justin</option>
</select>

<强> JS:

function selectedItemChange(sel) {
    document.getElementById('teste').value = sel.value;
}

<强>解释

<option onClick="nelson">nelson</option>
  • 的更改有三个原因:

    1. onclick优先于onClick以保持一致性
    2. nelson需要更改为nelson()才能实际调用该函数。
    3. 由于我们正在处理select html元素,因此最好使用 根目录上的onchange事件。

document.getElementById('teste').value =+ "nelson";

  • 正如许多其他人指出的那样,正确的运营商是+==

要设置初始值,请执行以下操作

DEMO: jsFiddle

<强> HTML

<input type="text" id="teste" maxlength="50" />
<select id="select-people" onchange="selectedItemChange(this)">
    <option value="nelson">nelson</option>
    <option value="justin">justin</option>
</select>

<强> JS

function selectedItemChange(sel) {
    document.getElementById('teste').value = sel.value;
}

window.onload=function(){
    document.getElementById('teste').value = document.getElementById("select-people").value;
}

答案 1 :(得分:5)

没有操作符=++=就是您所需要的。

答案 2 :(得分:2)

首先,正确的运算符为+=而不是=+

这不起作用的原因是因为你的函数必须被调用:)

让关闭立即运行:

(function nelson(){
    document.getElementById('teste').value += "nelson"; 
})();

或没有任何function

document.getElementById('teste').value += "nelson";

或在任何地方打电话:

nelson();

答案 3 :(得分:1)

您错误,将=+更改为+=

尝试使用select的推荐人事件。它是change

<input type="text" id="teste" maxlength="50">
<select onchange="nelson(this.value);">
  <option>nelson</option>
</select>

和JS

function nelson(value){
  document.getElementById('teste').value += value; 
}

答案 4 :(得分:1)

这是您的完整解决方案,它将与您的代码一起使用

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<input type="text" id="teste" value="" />

    <select onchange="nelson()" id="sel_nel">
      <option value="">select</option>
      <option value="nelson">nelson</option>
    </select>


<script>
    function nelson(){              
      document.getElementById('teste').value = document.getElementById('sel_nel').value; 
    }
</script>
</body>
</html>

答案 5 :(得分:0)

看一下这个小提琴:我假设您想要根据select - 标签内的选择来更改文本输入的值。

- &GT;的 http://jsfiddle.net/mQyLG/2/

更新(说明):

  1. 我直接设置select的值。如果您真的想要+=,可以将其更改为input.value = select.value
  2. 我为每个onchange使用select事件onclick而不是option事件。像这样你可以节省很多代码;)
  3. 我在开始时调用该方法一次,以确保有一个初始值。
  4. 我更改了函数的范围以匹配window。这不是最好的主意,应该符合您的实际范围。