2

Here's what I have so far:

<html xmlns="http://www.w3.org/1999/xhtml">
<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>
1
  • Thanks for the answers so far - but I really need to have the function accept a parameter so that I can call it for other events as well Commented Sep 15, 2010 at 15:45

4 Answers 4

3

Try this:

$("#weight").change(function(){
 onSelectChange($(this).val());
});
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

ty! Very similar to Mike Robinson's answer. I marked yours because of the explantion, thanks again!
1

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()));
        }
    );
});

Comments

1

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();

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.