2

I'm new to javascript, jquery, and ajax and need help making my code more efficient. I have the following javascript/jquery function that works fine:

 <script type="text/javascript">
    $(document).ready(function()
    {
        $("#promo1").change(function() //select menu id that triggers script on change
        {
           //data here

            $.ajax
            ({
               //ajax stuff here
                {
                    //individual values from json array


                    //set each value textbook value
                    $("#discprice1").val(disc);
                    $("#itemprice1").val(total);
                    $("#tax").val(tax);
                    $("#grandtotal").val(grand);
                }
            });

        });

    });
    </script>

I change my original function to this after a suggestion:

 <script type="text/javascript">
    $(document).ready(function()
    {
        var setupCalculation = function(index) {

            $("#promo" + index).on("change", function() //select menu id that triggers script on change
            {
 //rest of the function is here....

and change my select to this:

   <select name="promo<?php echo $i; ?>" id="promo<?php echo $i; ?>" 
onchange="setupCalculation('<?php echo $i; ?>');">

However, it is not working. What am I missing?

However, I need to do the same thing 10 times for 10 different rows of calculations. How can I make it so I can use this function generically and just pass the "id" of the select box to the function and not repeat this code 10 times for each of the selectors, e.g. #promo1, #promo2, #promo3, etc....

I'm assuming I need to add onchange="javascript function here();" to the html code, but I can't get it to work.

Thanks!

2
  • I updated the original description based on changes suggested by dbaseman. Commented Oct 20, 2012 at 19:54
  • good rule of thumb if you plan on using jQuery... forget that inline code exists like onclick or onchange and use jQuery unobtrusive methods exclusively Commented Oct 20, 2012 at 23:36

4 Answers 4

2

This is a case when you should write a little plugin. Take a look how it can look like (I did'nt get what exectly you need but you will grasp the idea):

$.fn.myFirstPlugin = functin() {
    return this.each(function() {
        // This is currect select box  
        var $select = $(this);

        // Change event
        $select.change(function() {
            // Do something for this select box; $(this) will point to current select element
            $.ajax({ ... })
        });
    })
};

Then you would use it like:

$('#promo1, #promo2, #promo3').myFirstPlugin();
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of using an "onchange" attribute inline, I would use your current approach to wireup the event handler. That way you can define a function setupCalculation that wires up the logic for a given select list.

$(document).ready(function() {

    var setupCalculation = function(id) {
        $("#" + id).on("change", function() {
            // ajax/calculation logic
        });
    }

    setupCalculation("promo1");
    setupCalculation("promo2");
    // ...etc
});

If the result elements are different (eg discprice2, discprice3, etc), then it may be better to pass an index to the function instead, and hard-code the name part of the ids:

var setupCalculation = function(index) {
    $("#promo" + index).on("change", function() {

        // ajax stuff 
        $("#discprice" + index).val(disc);
        // etc
    });
}

Edit Using the form onchange=setupCalculation(), the function should look like this (no need to wire up the change event):

$(document).ready(function()
{
    window.setupCalculation = function(index) {
       //rest of the function is here....

9 Comments

There is no onchange-attribute!?
I'll try this approach and see if I can implement it. Each result element is a different value and I'm not always using all 10 select menus (it is up to the user for how much data is entered) so I thnk the second approach is good. I'll see if i can get it.
How do I pass the index to the SetupCalculation function without using something like onchange="SetupCalculation('1')" or do I still use onchange?
Dbaseman - will you look at my change to the original question above? I think I'm close, but the new function won't work.
|
0

sounds like your select boxes look like

<select id="promo1">...</select>
<select id="promo2">...</select>

add a class to each one

<select id="promo1" class="promo">...</select>
<select id="promo2" class="promo">...</select>

so that you can select all the boxes with one simple selector for the change event function:

$(".promo").change(function() {
    ...
});

Comments

0

You could set up a jQuery function and call it from the selected object:

$.fn.changePromo = function() {
    /* return this jQuery object to allow chaining and execute in an 'each()' to allow multiple elements */
    return this.each( function() {
        $( this ).change( function() {
            /* your ajax call here */
        } );
    } );
}

/* call examples */
$( '#promo1' ).changePromo();
$( '#promo1,#promo2' ).changePromo();

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.