简体   繁体   English

如何从javascript中的多个输入字段读取值?

[英]How to read values from multiple input fields in javascript?

Thanks for looking into this in advance. 感谢您提前调查。 It's basically my first week of javascript, so apologies if it is something common and I appreciate a link to a similar question. 基本上,这是我学习JavaScript的第一周,因此道歉,如果这很常见,我感谢与一个类似问题的链接。

I can't figure out how to extract values from my dropdown and text input at the same time so I can then append that information to another container. 我无法弄清楚如何从下拉菜单和文本输入中同时提取值,因此可以将该信息附加到另一个容器中。 Here is my html: 这是我的html:

<div class=“container1”>
   <select class=“options_selector”>
     <option val=“admin”>admin</option>
     <option val=“user”>user</option>
   </select>
   <input class=“user_name” type="text"/>
</div>

<div class=“container2”>
   <!— append stuff here —>
</div>

So information from container1 should get appended to container2. 因此,来自container1的信息应附加到container2。 For example, if I chose 'admin' in options_selector and typed 'freddy' in user_name input box, container2 should now have 'admin freddy' in it. 例如,如果我在options_selector中选择了“ admin”,并在user_name输入框中键入了“ freddy”,那么container2现在应该在其中包含“ admin freddy”。 When, then, I change the select box value to 'user' and the input text to 'john' - container2 should have another piece of text appended 'user john'. 然后,当我将选择框值更改为“ user”,将输入文本更改为“ john”时,container2应该在“ user john”后附加另一段文本。

I know it can be done with on change events, but i cannot figure out the general idea behind extracting both of those pieces of information together. 我知道可以通过更改事件来完成,但是我无法弄清楚将这些信息一起提取出来的总体思路。

I'm using jquery as a framework by the way. 顺便说一下,我正在使用jquery作为框架。

thanks in advance. 提前致谢。

You could write code like : 您可以编写如下代码:

$( "select" ).change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "#user_name" ).val(str);
}).change();

JSFiddle Here! JSFiddle在这里!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM