Lance
Lance

Reputation: 4820

Getting values of select tags with jQuery

How could I do the following:

<script type="text/javascript">
    $("button").click(function() {
         var sum = 0;

         $("select").each(function() {
           sum += parseInt(this.value);
        });

       alert(sum);
    });
</script>
<?php
     for($i=0;$i<50;$i++) {
         echo "<div>
                  <select>";

         for($x=1;$x<5;$x++) {
             echo "<option value='".$x."'>".$x."</option>";
         }

         echo "</select>
               </div>";
     }
 ?>
 <button>Submit</button>

The client is to be able to edit each select tag accordingly. How can I make it so that upon click of the button, the sum for each of the user's selections will be returned?

Upvotes: 0

Views: 73

Answers (2)

Shai
Shai

Reputation: 7317

You're pretty much there. 2 changes:

  1. Wrap your button click Javascript between $(function() { and });:

    $(function() {
        $("button").click(function() {
            var sum = 0;
    
            $("select").each(function() {
                sum += parseInt(this.value);
            });
    
            alert(sum);
        });
    });
    

    so that the click handler isn't registered until after the document is ready / the button actually exists (explained in detail here).

  2. You probably also want to change:

    sum += parseInt(this.value);
    

    to

    sum += parseInt($(this).val());
    

    so that jQuery takes care of some cross-browser stuff.

Working demo: here at JSFiddle

Edit: and, of course, make sure you are including jQuery before you use it!! How jQuery Works

Upvotes: 0

claustrofob
claustrofob

Reputation: 4984

Your code is valid. You just need to wrap your javascript with $(function(){...}):

$(function(){
  $("button").click(function() {
     var sum = 0;

     $("select").each(function() {
       sum += parseInt(this.value);
    });

   alert(sum);
  }); 
});

Upvotes: 1

Related Questions