1

Hello everyone I'm trying to do when user select an option, another option will appear. Yes, I did it but when user select other options, I wanna display text but it does not work here is my code:

<html>
  <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script></script>
    <script type="text/javascript">
      $(document).ready(function() {

        $(".select-box").change(function() {
          if ($(".select-box option[value='3']").attr('selected')) {
           document.getElementById("demo").innerHTML="<select class='select-box'><option value='4'>a</option><option value='5'>b</option></select>";
          if ($(".select-box option[value='5']").attr('selected')) {
          document.write("Hello")
          }
          }

        }); 

      });
    </script>
  </head>
  <body>
    <select class="select-box">
      <option>Select an option</option>
      <option value="1">no alert</option>
      <option value="2">no alert too</option>
      <option value="3">alert</option>
    </select> 
    <p></br>
    <div id="demo"></div>

  </body>
</html>
3
  • what exactly do you want? when should be your 'Hello' written? Commented Sep 10, 2012 at 11:54
  • You don't have an option with a value of 5 like the second if is looking for. Commented Sep 10, 2012 at 11:56
  • When youu click alert option, another option appears that has option values "a" and "b" then when you click b option it will display "Hello" Commented Sep 10, 2012 at 11:57

2 Answers 2

3

You need to use jQuery's on() function, since you want to add eventhandler to the second select, which is added to the DOM dynamically.

$(document).ready(function() {

    $('#main').on('change', '.select-box', function() {

        if ($(this).val() == 3) {
            $('#demo').html("<select class='select-box'><option value='4'>a</option><option value='5'>b</option></select>");
        }

        if ($(this).val() == 5) {
            alert("Hello");
        }
    });

});​

See the DEMO.

I have wrapped your element with a div and attached the change handler to it.

Also notice, that I have replaced your javascript getElementById with jQuery selectors, and I have simplified your value checks.

Sign up to request clarification or add additional context in comments.

Comments

1

It doesn't work as at the moment when the script is running there is only one element in the DOM matching selector .select-box. So after creating the second one, you have to bind the event listener one more time.

1 Comment

I suggested the theoretical part of solution, but Michal's answer is the pratical implementation of what I said, so use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.