1

hi can someone explain why the coding below does not work but it work here but it works here http://jsfiddle.net/CDp8t/7/

    <html>
    <head>
        <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>

<script type="text/javascript">
    $("#example").focus(function() {
        var first = $(this).find("option").eq(0);
        if(first.val() === "1") {
            first.remove();
        }
    });
</script>
    </head>

    <body>

    <select id="example">
        <option value="1">First</option>
        <option value="2">Second</option>
        <option value="3">Third</option>
    </select> 
    </body>
    </html>
2
  • It works in the jsfilddle link because there the javascript part is loaded after the select tag is loaded. Commented Oct 18, 2011 at 20:37
  • Use http instead of https "ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js" if you are usin http. Using https work may not work ( IE ). Commented Oct 18, 2011 at 20:38

3 Answers 3

5

I think you just need to add your event handler when the DOM's loaded:

$(document).ready(function() {
  $("#example").focus(function() {
    var first = $(this).find("option").eq(0);
    if(first.val() === "1") {
      first.remove();
    }
  });
});

The <select> element does not exist when you're trying to attach the event to it.

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

Comments

2

You are trying to access your #example element before it is created

You could move your script tag to the bottom of your HTML or put the jquery code in a $(document).ready() function

Comments

2

I'd say the most likely cause is that the DOM isn't loaded on your page when the JavaScript runs, but is when it runs within jsfiddle's sandbox. Try wrapping it to wait for the DOM to load:

$(document).ready(function() {
  $("#example").focus(function() {
    var first = $(this).find("option").eq(0);
    if(first.val() === "1") {
        first.remove();
    }
  });
});

Comments

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.