Calling a javascript function from a php dropdown, loaded with jquery
Now if the heading isn't enough to put you off, then you probably know the answer to this question.
And first of all, thank you to everyone who's been offering help to me over the last couple of questions, but a special thanks to Bazmegakapa for all his he开发者_运维知识库lp.
Here's the final problem (for now):
I have a dropdown box written in PHP that populates itself from a MySQL database. The dropdown box is pulled into my HTML / Javasccript page using jQuery.load What I now need to happen is that when someone selects one of the options from the dropdown, it calls a javascript function, passing it the value of the selected item from the dropdown.
Can't work out how to do this - and it's probably very simple (but so am I)
Thanks all!
Rob.
Quick working example for doing something on a selectbox with its value
<select id="dropdown">
<option value="1">foo</option>
<option value="2">bar</option>
<option value="3">bla</option>
<option value="4">test</option>
</select>
<script>
function start(value) {
//do something with the value
}
$('#dropdown').change(function() {
//do something with this value like calling a function etc.
//$(this).val() returns the value of the selected element
start($(this).val());
});
</script>
The select
is inserted through .load()
, so you have to define a callback to run when the .load()
operation is complete and successful. You can do it like this (jQuery load() doc):
$('#i_want_my_select_here').load('/temp/select.php', function () { //callback
$('select', this).change(function () { //catch onchange event of select
//call your function here, pass the selected value
start($(this).val());
});
});
All you need in Javascript (not jQuery in particular) is an onclick event for the dropdown where you call a function with this.value
as the parameter.
精彩评论