0

Hello
I am learing Jquery
I want to display the Text from select box using the Jquery code. When will I click option from hotel1 then only selected text from hotel1 shall be printed and when I will select any option from hotel2 then only select option from hotel2 shall be printed.
But ths is not happening with my code given below. It is printing from both the select box. And It also print when page is loaded.
Where is my logic failed? Please guide.

<!DOCTYPE html>
<html>
<head>
  <style>

  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <select id="hotel1">
    <option>Burgur</option>
    <option>Hot Dog</option>
    <option>Icecream</option>
    <option>Biscute</option>
    <option>Puff</option>
    <option>Pizza</option>
  </select>

  <select id="hotel2">
    <option>Burgur</option>
    <option>Hot Dog</option>
    <option>Icecream</option>
    <option>Biscute</option>
    <option>Puff</option>
    <option>Pizza</option>
  </select>

   <div></div>
<script>
   $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .change();
</script>

</body>
</html>
2
Contributors
1
Reply
5
Views
5 Years
Discussion Span
Last Post by pritaeas
1
$("select").change(function () { }); 

This code is executed for each select box. Unfortunately, the change is also triggered when you first load the page. If you want to target a single select box, then use something like this:

$('#hotel1').change(function() { });
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.