Javascript将文本从选择字段复制到文本字段

时间:2017-06-10 02:46:10

标签: javascript select text

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

我遇到了这个

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>

我该如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:1)

将您的javascript包裹在$(document).ready()

$(document).ready(function() {
  $('select').change(function(){

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

有关详细说明,请参阅this post