Reputation: 4349
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>
Upvotes: 1
Views: 68
Reputation: 219117
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();
}
});
});
Upvotes: 2
Reputation: 36965
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.
Upvotes: 5
Reputation: 2628
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
Upvotes: 2