Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    New Coder
    Join Date
    Jul 2005
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question jQuery, calculations, onchange?

    Alright, I'm not even sure how to begin programming this with jQuery. I'm building a form. Early in the form the user is asked to select a course from a <select> box. The <select> box is populated from a database using PHP. Included in the drop down menu is the name of the course, the instructor, some other information, and the price of the course. Right now the user can add as many courses as they want (or remove courses they selected). That all works great.

    I have several price-related <input type="text"> boxes at the bottom of the form. I would like for these to be automatically updated (and unchangeable by the user, if possible) whenever the user adds/selects a new course.

    My initial thought is to create a javascript function that runs every time one of the <select> boxes changes (ie. a different course is selected)...

    I would look up how to do this but I'm not even sure where to begin looking.

  • #2
    Senior Coder Spudhead's Avatar
    Join Date
    Jun 2002
    Location
    London, UK
    Posts
    1,856
    Thanks
    8
    Thanked 110 Times in 109 Posts
    We really need to see some code to be able to help with this. None of it sounds impossible, but we need to know the format of the info in the select boxes in order to pull the price out, and I'm unclear on the price text boxes - why are there several, shouldn't there just be one, for the total? And while we're at it, why is it a text box at all? If you're not allowing input, and simply wish to display a cost to the user, it can be any element that you update. It doesn't have to be a form field.

  • #3
    Senior Coder
    Join Date
    Jan 2005
    Location
    Memphis, TN
    Posts
    1,788
    Thanks
    8
    Thanked 131 Times in 129 Posts
    Like spudhead said,

    Some example code of what you are already doing would be better. I also agree that if you don't want the user to be able to change the total then don't show it in an input.

    maybe this will be a good start though:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    
    
    <script type="text/javascript">
    $(document).ready(function() {
    // begin
    	$("select.course").change(function () {
    		var total = 0;
    		$("select.course option:selected").each(function() {
    			total += parseFloat($(this).val()) || 0;
    		});
    		$(".courseTotal span").text("$"+total.toFixed(2));
    	});
    // end
    });
    </script>
    
    </head>
    <body>
    <form action="blank.php" method="post">
    	<select class="course" name="course1">
        	<option value="0.00"></option>
    		<option value="212.99">Reading - $212.99</option>
    		<option value="198.25">Writing - $198.25</option>
    		<option value="143.44">Arithmatic - $143.44</option>
    	</select>
    	<select class="course" name="course2">
        	<option value="0.00"></option>
    		<option value="212.99">Reading - $212.99</option>
    		<option value="198.25">Writing - $198.25</option>
    		<option value="143.44">Arithmatic - $143.44</option>
    	</select>
    	<select class="course" name="course3">
        	<option value="0.00"></option>
    		<option value="212.99">Reading - $212.99</option>
    		<option value="198.25">Writing - $198.25</option>
    		<option value="143.44">Arithmatic - $143.44</option>
    	</select>
    </form>
    <div class="courseTotal">Your total cost: <span></span></div>
    </body>
    </html>
    Stop making things so hard on yourself.
    i is tugbucket :: help raise tugburg :: Whitehaven Kiwanis

  • #4
    New Coder
    Join Date
    Jul 2005
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you harbingerOTV that is useful although I don't think it quite meets my needs. And yes, you are both correct there is no reason to make the price fields input boxes when they can just be dynamic text. I need to show and change all the various price fields so the user can see how the total costs breaks down.

    Right now this is the code I'm using. I'll show two parts. The first is the PHP that populates the <option> elements in the <select> box and the second is the jQuery:

    PHP Code:
    $course_block .= "<option value=\"$subject-$coursenum-$section-$crn-$title-$instructor-$credits-$price\">$subject $coursenum- $title- Instructor: $instructor- Section: $section- Credits: $credits- Price: \$$price</option>"
    // you see that price is at the end, hyphenated.

    Next is the jQuery that calls the php and populates the <select> boxes (dynamically added by the user):

    Code:
    .append(
    			$('<select>')
    				.attr('id', 'course' + count)
    				.attr('name', 'courses[]')
    				.append('<?php echo javascript_escape($course_block); ?>')
    		)
    // this all works fine so far. The user adds a select box using the code above (and some other code in the jquery function) by clicking on a link. They can add as many courses as they want.

    So I want to be able to pull the value of price after the last hyphen in every instance of a select box with a similar name I suppose and put it into a dynamic text field. Does that help at all?

  • #5
    Senior Coder
    Join Date
    Jan 2005
    Location
    Memphis, TN
    Posts
    1,788
    Thanks
    8
    Thanked 131 Times in 129 Posts
    So you just need to grab the price, sure, change the script to look like:

    Code:
    	$("select.course").change(function () {
    		var total = 0;
    		$("select.course option:selected").each(function() {
    			total += parseFloat($(this).attr('rel')) || 0;
    		});
    		$(".courseTotal span").text("$"+total.toFixed(2));
    	});
    instead of getting and adding the "val" we'll just grab the "rel" and the options would lok like:
    Code:
    <option value="212.99" rel="212.99">Reading - $212.99</option>
    so your code could look like:

    Code:
    $course_block .= "<option value=\"$subject-$coursenum-$section-$crn-$title-$instructor-$credits-$price\" rel=\"$price\">$subject $coursenum- $title- Instructor: $instructor- Section: $section- Credits: $credits- Price: \$$price</option>";
    Stop making things so hard on yourself.
    i is tugbucket :: help raise tugburg :: Whitehaven Kiwanis

  • #6
    New Coder
    Join Date
    Jul 2005
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question

    Alright, thanks. I think I see what you're saying...but it's not doing anything when I change the select box. Here's what I did:

    jQuery code:
    Code:
    	$("select.course1").change(function () {
    		var total = 0;
    		$("select.course1 option:selected").each(function() {
    			total += parseFloat($(this).attr('rel')) || 0;
    		});
    		$(".courseTotal span").text("$"+total.toFixed(2));
    	});
    That's your code. Then below I put a <span> element with the following:
    Code:
      <p>
      <label for="total">Total: </label><span class="courseTotal" id="courseTotal">0.00</span>
      </p>
    I also made sure to add the "rel" attribute to my php $course_block. So why is the <span> text not changing?

  • #7
    Senior Coder
    Join Date
    Jan 2005
    Location
    Memphis, TN
    Posts
    1,788
    Thanks
    8
    Thanked 131 Times in 129 Posts
    Code:
    $(".courseTotal span").text("$"+total.toFixed(2));
    is looking for a span inside something with the class "courseTotal". The code you posted has the span having that class.

    also i just noticed that in your append part you are appending the selects without a class. The script is looking for the change of selects with the class of "course"

    Code:
    	$("select.course").change(function () {
    		var total = 0;
    		$("select.course1 option:selected").each(function() {
    			total += parseFloat($(this).attr('rel')) || 0;
    		});
    		$("span.courseTotal").text("$"+total.toFixed(2));
    	});
    So you need to change your append to something like:

    Code:
    .append(
    			$('<select>')
    				.attr('id', 'course' + count)
    				.attr('name', 'courses[]')
    				.append('<?php echo javascript_escape($course_block); ?>')
                                    .addClass("course")
    		)
    Dont change the script for evryone as it will just itterate through all matched selects when any of them change.
    Last edited by harbingerOTV; 12-03-2009 at 09:33 PM.
    Stop making things so hard on yourself.
    i is tugbucket :: help raise tugburg :: Whitehaven Kiwanis

  • #8
    New Coder
    Join Date
    Jul 2005
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Alright, you the man. Got that to work. But then it gets more complicated...

    First a problem with the current code:

    There is an initial <select> box that when changed automatically updates the total field. Good! However, when I click on 'add another course' link (giving me yet another <select> box) and then change that value, it doesn't update the field unless I change the first <select> box again (even though it does add the second <select> boxes $price to the total)

    Here's a link to the code in actionscroll down about half way to see the course select box - the total field is just a bit below it, near the top, under 'calculation of fees')

    http://distance.uaf.edu/projects/jquery/regtest.php

    Also, I allow the user to remove courses they have added with a 'remove' link that shows up next to the <select> box they added. Obviously I want the course total to change to reflect the new total once a course has been removed. How would I add that? Here's all the jQuery code I'm using so far (including the remove code):

    Code:
    <script type="text/javascript">
    var count = 1;
    $(document).ready(function(){
    
    	$("select.course").change(function () {
    		var total = 0;
    		$("select.course option:selected").each(function() {
    			total += parseFloat($(this).attr('rel')) || 0;
    		});
    		$("span.courseTotal").text("$"+total.toFixed(2));
    	});
    
    	$('span#add_field').click(function(){
    	
    		count++;
    		
    		$('#container')
    
    		.append(
    			$('<label>')
    				.attr('for', 'course' + count)
    				.append('Select Course: ')
    		)
    		.append(
    			$('<select>')
    				.attr('id', 'course' + count)
    				.attr('name', 'courses[]')
    				.append('<?php echo javascript_escape($course_block); ?>')
    				.addClass("course")
    		)
    		
    		.append(
    			$('<a>').addClass('select_remove').attr('href','#').text("Remove")
    		)
    		
    		$('a.select_remove').unbind('click').click(function(){
    			$(this).prev('select').remove();
    			$(this).prev('label').remove();
    			$(this).remove();
    			return false;
    		});
    	});
    });
    </script>

  • #9
    Senior Coder
    Join Date
    Jan 2005
    Location
    Memphis, TN
    Posts
    1,788
    Thanks
    8
    Thanked 131 Times in 129 Posts
    okay, download this plugin: http://docs.jquery.com/Plugins/livequery

    then change your script to look like:

    Code:
    	$("select.course").livequery('change', function(event) { 
    		var total = 0;
    		$("select.course option:selected").each(function() {
    			total += parseFloat($(this).attr('rel')) || 0;
    		});
    		$("span.courseTotal").text("$"+total.toFixed(2));
    	});
    see if that doesn't fix it up.
    Stop making things so hard on yourself.
    i is tugbucket :: help raise tugburg :: Whitehaven Kiwanis

  • #10
    New Coder
    Join Date
    Jul 2005
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts
    That worked perfectly, thank you.

  • #11
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    Quote Originally Posted by harbingerOTV View Post
    okay, download this plugin: http://docs.jquery.com/Plugins/livequery

    then change your script to look like:

    Code:
    	$("select.course").livequery('change', function(event) { 
    		var total = 0;
    		$("select.course option:selected").each(function() {
    			total += parseFloat($(this).attr('rel')) || 0;
    		});
    		$("span.courseTotal").text("$"+total.toFixed(2));
    	});
    see if that doesn't fix it up.
    With jQuery 3.2.1 we have the .live() function; would that not do the same thing as this plugin? Just curious.

  • #12
    Senior Coder Spudhead's Avatar
    Join Date
    Jun 2002
    Location
    London, UK
    Posts
    1,856
    Thanks
    8
    Thanked 110 Times in 109 Posts
    Quote Originally Posted by Fumigator View Post
    With jQuery 3.2.1 we have the .live() function; would that not do the same thing as this plugin? Just curious.
    The docs say that change isn't yet supported by live(). Dunno if that's still the case, the whole live() thing was new to me

  • #13
    Senior Coder
    Join Date
    Jan 2005
    Location
    Memphis, TN
    Posts
    1,788
    Thanks
    8
    Thanked 131 Times in 129 Posts
    Quote Originally Posted by Fumigator View Post
    With jQuery 3.2.1 we have the .live() function; would that not do the same thing as this plugin? Just curious.
    Like spud said, it looks like they haven't fully assimilated the livequery script into the core yet. I'm glad they are working on it. I kind of forget jQuery needing this to readdress the DOM. Making it into the core, like they did with the dimensions plugin, will be nice.
    Stop making things so hard on yourself.
    i is tugbucket :: help raise tugburg :: Whitehaven Kiwanis


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •