【问题标题】:Javascript to copy text from select field to text fieldJavascript将文本从选择字段复制到文本字段
【发布时间】:2017-06-10 02:46:09
【问题描述】:

我正在尝试将值从选择字段复制到文本字段

我遇到了这个

http://jsfiddle.net/f23uP/

但是当我使用以下内容创建测试页面时它不起作用,我显然把它放在一起错误:(

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <script type="text/javascript" src="//code.jquery.com/jquery-compat-git.js"></script>

<title>Test copy select</title>
<script type='text/javascript'>
  $('select').change(function(){

  $('input[type=name]').val($('option:selected',this).text());
  $('input[type=price]').val($(this).val());
  });
</script>
</head>

<body>
  <form>
    <select>
      <option value="10">Apple</option>
      <option value="20">Orange</option>
    </select>

    <input type="name" />
    <input type="price" />
  </form>
</body>
</html>

我该如何解决这个问题?

谢谢

【问题讨论】:

    标签: javascript select text


    【解决方案1】:

    $(document).ready() 中包装你的javascript:

    $(document).ready(function() {
      $('select').change(function(){
    
        $('input[type=name]').val($('option:selected',this).text());
        $('input[type=price]').val($(this).val());
      });
    });
    

    更多解释请见this post

    【讨论】:

    • 如果/当在本地运行时,还将httphttps 添加到src。有时它可能会导致问题并且无法加载所需的库。我之前遇到过这个问题,因此建议您添加到您的答案中。
    • 您当然可以添加另一个答案,或者在 OP 的帖子中添加评论。
    • 感谢您的帮助和链接
    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 2020-08-30
    • 2013-07-04
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多