开发者

jQuery: Select Options - Adding Prices

I'm new to coding. I have a two part question:

1.Let's say I have:

#html    
<style>
    <option value="1"> Red Box </option>
    <option value="2"> Green Box </option>
    <option value="3"> Blue Box </option>
</style>
<style>
    <option value="4"> Red Circle</option>
    <option value="5"> Green Circle</option>
    <option value="6"> Blue Circle</option>
</style>

What's the best way to assign each option a Dollar value so that the value can be computed in jQuery?

2.How can jQuery be used to create these results: * The selected option prices 开发者_JAVA百科are totaled and shown to the user * The user can choose to "submit options"


The selected option prices are totaled and shown to the user

Simple, just do:

  var total = 0;
  $('select').each(function() {
      // Convert val from string to integer, so it isn't cocantenated.
      total += parseInt($(this).val());
  });
 alert('Total is: ' + total);

The user can choose to "submit options"

Well you would normally want a submit button:

<input type="submit" value="Submit" name="submit"/>

Then you can either let the browser handle the submitting of the form values. To do this each select, or any form element, must be a child of the form. You also define where the form should either post/get values to

<form name="shapes" action="/form-handler.php" method="post">
  <!-- your select elements here !-->
</form>

Each element in your form MUST have a name attribute if you want it to be submitted correctly.

Should you want jQuery to submit a form via ajax, you can use the beauty serialize

 $('[name=shapes]').serialize();

This will convert the form values to a query string for posting. See http://api.jquery.com/serialize/ for details on this function.


The best way to assign each option a dollar value is by using the value key of the option tag. It would go something like this:

#html    
<select> <!-- I'm assuming you meant a select-tag here not a style-tag -->
    <option value="5"> Red Box </option>
    <option value="8"> Green Box </option>
    <option value="1"> Blue Box </option>
</select>
<select>
    <option value="6"> Red Circle</option>
    <option value="3"> Green Circle</option>
    <option value="1"> Blue Circle</option>
</select>

Your jQuery code can look like:

var total = $('select:first').attr('value') + $('select:last').attr('value');


To get the total:

<script>
  $(document).ready(function(){
    alert( $('select:first').val() + $('select:last').val() );
  });
</script>

Hope this helps. Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜