简体   繁体   中英

Javascript to copy text from select field to text field

I am trying to copy the values from a select field to a text field

I came across this

http://jsfiddle.net/f23uP/

But when I created a test page using the following it does not work, I have obviously put it together wrong :(

<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>

How do I fix this?

Thanks

Wrap your javascript in $(document).ready() :

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

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

See this post for further explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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