I’ve got this odd problem with jQuery. I’m trying to let the change of an html select, trigger a post to a .php that returns new replacement html data for another select element.
I succeed in replacing the select html with just the post part, but when I add the .change part it stops working.
Here’s my test page html(it’s a .php page)
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<select id=control6>
<option selected="selected" value="normal">normal</option>
<option value="change">change</option>
</select>
<select id=sortedselect6>
<option selected="selected" value="alphabetic">alphabetic</option>
<option value="grammatic">grammatic</option>
<option value="assessment">assessment</option>
<option value="maximatch">maximatch</option>
</select>
<select id=dummyselect6>
<option selected="selected" value="dummy1">dummy1</option>
<option value="dummy2">dummy2</option>
</select>
</body>
</html>
the ajax.js
jQuery("select#control6").change(function() {
jQuery.post('verwerker.php', {
currentselect: jQuery("select#control6").val()
}, function(htmldata) {
jQuery("select#sortedselect6").html(htmldata);
});
});
verwerker.php
<?php
echo '<option value="alphabetic">alphabetic</option>
<option selected="selected" value="grammatic">grammatic</option>
<option value="assessment">assessment</option>
<option value="maximatch">maximatch</option>';
?>
Now if I only put the following in ajax.js then it changes the sortedselect6 to grammatic as selected instantly. So it must be something with the .change part that messes up?
jQuery.post('verwerker.php', {
currentselect: jQuery("select#control6").val()
}, function(htmldata) {
jQuery("select#sortedselect6").html(htmldata);
});
You can view the last piece of code (the one without the .change) at work here http://www.tarile.net63.net/thebirdistheword.php
P.S.: the {currentselect:jQuery(“select#control6”).val()} is for later, it has no purpose right now
Solved! The problem was that my jQuery couldn’t load some of the elements because the page wasn’t yet fully loaded. Damn I feel really dumb to have made that mistake, really dumb. xD here’s the fixed code:
jQuery(document).ready(function(){
jQuery("#sortedselect6").change(function() {
jQuery.post('verwerker.php',{selection:jQuery("select#control6").val()}, function(newSelectdata) {
jQuery("select#sortedselect6").html(newSelectdata);
});
});
});
Your basic change and ajax code works fine in this jsfiddle. Note that data is slightly different simply due to fiddle requires you to send the actual html in order to test ajax
http://jsfiddle.net/up6fG/
Make sure you are wrapping your code in ready event so that the elements exist when code fires