Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Jquery to read from selected option with array?

I have php code bellow, I want to write a script to read option value from drop-down list and put each value in the input box when I change the selection. Please, help.

<html>
  <head> 
    <!-- Load jQuery from Google's CDN -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script>
    //I want to write a script that will read the selected value and put in the input box
    </script>
  </head>
  <body>
  <?php
    for ($i=0;$i<7;$i++)
    {
    ?>
    <select id='select$i'>
        <option value="1">Option1</option>
        <option value="2">Option2</option>
        <option value="3">Option3</option>
    </select>
      <input type="text" name="name" id="inputoption$i"  />      
    <?php }?>
    <br />


  </body>
</html>
like image 662
Ben2014 Avatar asked Mar 16 '23 02:03

Ben2014


2 Answers

Try this:

    <html>
<head>
  <script type="text/javascript" src="jquery-2.1.1.min.js"></script>
</head>
<body>
<div class="category-panel">
  <?php
  for($i = 0; $i < 7; $i++)
  {
    ?>
    <select id='select<?php echo $i; ?>'>
      <option value="1">Option1</option>
      <option value="2">Option2</option>
      <option value="3">Option3</option>
    </select>
    <input type="text" name="name" id="inputoption<?php echo $i; ?>"/>
  <?php } ?>
  <br/>
</div>
<script>
  $("select").on("change", function()
  {

    $(this).next("input").val($(this).val());
  });
</script>
</body>
</html>
like image 84
Rayon Avatar answered Mar 19 '23 04:03

Rayon


Better change the id into class :

$(function() {
  $(document).on('change', '.selectMe', function() {
    $(this).next().val($(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='selectMe'>
  <option value="1">Option1</option>
  <option value="2">Option2</option>
  <option value="3">Option3</option>
</select>
<input type="text" name="name" class="inputoption" />
<select class='selectMe'>
  <option value="1">Option1</option>
  <option value="2">Option2</option>
  <option value="3">Option3</option>
</select>
<input type="text" name="name" class="inputoption" />

like image 24
Norlihazmey Ghazali Avatar answered Mar 19 '23 03:03

Norlihazmey Ghazali