views:

92

answers:

4

Here's what I have so far:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>

<script type="text/javascript" src="/js/jquery.js"></script>

 <script type="text/javascript"> 

$(document).ready(function() { 
    $("#weight").change(onSelectChange);
}); 

function onSelectChange(){
        var selected = $('#weight').val();
        $.post("tship.php", {weight: selected},
            function(data){
                $("#ship").html(data.ret_html);
                }, "json");
} 

 </script>   


</head>
<body>

<select id="weight">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>

<br />

<div id="ship">
</div>

</body>
</html>

I want to change it so that onSelectChange accepts a single parameter. I need to be able to call the function for other events as well - not only when the select box value changes. Here is my attempt, not working:

<script type="text/javascript"> 

$(document).ready(function() { 
    $("#weight").change(onSelectChange($('#weight').val()));
}); 

function onSelectChange(parm){

        $.post("tship.php", {weight: parm},
            function(data){
                $("#ship").html(data.ret_password);
                }, "json");
} 

</script>
+2  A: 

You should add another function:

$("#weight").change(function(){
      onSelectChange($('#weight').val());
}); //close the anonymous function

Note that in your original code you've passed onSelectChange as a reference, you didn't start it - onSelectChange(). With the code as it is, you start the function once instead of binding it.

Kobi
ty! Very similar to Mike Robinson's answer. I marked yours because of the explantion, thanks again!
jriggs
+3  A: 

Try this:

$("#weight").change(function(){
 onSelectChange($(this).val());
});
Mike Robinson
+1  A: 

You were calling a function within another function, so I think that if you amend your code to the following it should work okay (assuming your onSelectChange() function works properly:

$(document).ready(function() { 
    $("#weight").change(
        function() {
            $(this).onSelectChange($('#weight').val()));
        }
    );
});
David Thomas
+1  A: 

You can't do that, the onSelectChange gets called by jQuery's change function so it chooses what params to pass.

In your case however, this is simple, jQuery will bind 'this' to the item that you've applied that event handler to, so you can reference that value in your onSelectChange using:

$(this).val();
brad