What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-downs, and then see the total sum calculated from the selected values.

Here's the code I have so far, but it's definitely not correct:

<form>
echo "<select name=Postage>
  <option value='14'>1st Class</option>
  <option value='8'>2nd Class</option>
  <option value='22'>Next Day Delivery</option>
  <option value='0'>Click And Collect</option>
</select>
<br>
<select name=Type>";

$type = "SELECT * FROM $category order by id";
$item = mysql_query($type);
while ($typeitem = mysql_fetch_assoc($item)) {

echo "<option value=$typeitem[price]>$typeitem[type]</option>";

}

$totalspend = Type.value + Postage.value;

echo "
Total £$totalspend
</select>
</form>";

I know many will suggest doing this with JavaScript, but honestly, I don't know how to implement that in my code. Can anyone please offer some help or guidance?

Answer №1

I'm not sure if you want to add the selection to the database based on your question... This would require a different code, but here's how you can achieve what you're asking for.

You don't need a form, just the selection boxes. Notice that each piece of HTML is enclosed in an echo tag, which writes a condensed code to the browser.

Make sure to assign an id to each selection box:

HTML

echo '<select id="this_postage" name="Postage">';
        echo '<option value="14">1st Class</option>';
        echo '<option value="8">2nd Class</option>';
        echo '<option value="22">Next Day Delivery</option>';
        echo '<option value="0">Click And Collect</option>';
    echo '</select>';   

    echo '<select id="this_type" name="Type">';
        $type = "SELECT * FROM $category order by id";
        $item = mysql_query($type);
        while ($typeitem = mysql_fetch_assoc($item)) {  
            echo '<option value='.$typeitem[price].'>'.$typeitem[type].'</option>'; 
        }
    echo '</select>';

    echo '<div id="total_spend"></div>';

Note the div with id="total_spend".

JQUERY

$(function() {  
    $( "#this_type" ).change(function(){
        var total_spend = parseInt($('#this_postage').val()) + parseInt($('#this_type').val());
        $('#total_spend').html('Total: £'+total_spend);
}); 

When the user selects the Type, jQuery will detect the change, retrieve the values of both the postage and type, add them together, and display the total in

<div id="total_spend">Total: £TOTAL HERE</div>

THIS CODE WILL SEND TO DB:

Again, no form tag is required:

HTML:

An additional hidden input is added to store the processing URL

echo '<input type="hidden" id="updateURL" value="PATH-TO-PHP-PROCESSING-FILE.PHP">';
    echo '<select id="this_postage" name="Postage">';
        echo '<option value="14">1st Class</option>';
        echo '<option value="8">2nd Class</option>';
        echo '<option value="22">Next Day Delivery</option>';
        echo '<option value="0">Click And Collect</option>';
    echo '</select>';   

    echo '<select id="this_type" name="Type">';
        $type = "SELECT * FROM $category order by id";
        $item = mysql_query($type);
        while ($typeitem = mysql_fetch_assoc($item)) {  
            echo '<option value='.$typeitem[price].'>'.$typeitem[type].'</option>'; 
        }
    echo '</select>';

    echo '<div id="total_spend"></div>';

JQUERY:

$(function() {
$( "#this_type" ).change(function(){
        var url = $('#updateURL').val();        
        var postage = parseInt($('#this_postage').val());   
        var type = parseInt($('#this_type').val());
        var total_spend = (postage + type);
        var postit = $.post( url, {
        custom_block_name:custom_block_name,
        postage:postage,
        type:type
        });     
        postit.done(function( data ) {
        alert(data);
        $('#total_spend').html('Total: £'+total_spend);
        });     
    });});

Treat the processing PHP code as you would with the post method. After the MySQL update code at the bottom, you can add a message in the alert box using

echo 'Whatever Message you want to display in the alert here.';

If you don't want an alert, simply remove it from the jQuery code.

To call jQuery:

...?>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
 $(function() { 
        $( "#this_type" ).change(function(){
            var total_spend = parseInt($('#this_postage').val()) + parseInt($('#this_type').val());
            $('#total_spend').html('Total: £'+total_spend);
    }); 
</script>

Answer №2

To display the total, you can make use of a few lines of JavaScript code. Check out this live example: http://jsfiddle.net/v67hcta9/

<select class="postage choice" name='Postage'>
    <option value='0'>Please choose postage...</option>
    <option value='14'>Standard Delivery</option>
    <option value='8'>Express Delivery</option>
    <option value='22'>Next Day Delivery</option>
    <option value='0'>In-Store Pickup</option>
</select>

<!-- PHP-generated output example -->
<select class="type choice" name='Type'>
    <option value='0'>Please choose type...</option>
    <option value='12'>Box</option>
    <option value='5'>Envelope</option>
    <option value='3'>Card</option>
</select>

<label>Total:</label>
<input name='total' id='total' disabled='true' value=''>

JavaScript:

$(document).ready(function(){
    $('.choice').change(function(){
        var postage = parseInt($('.postage').val());
        var type = parseInt($('.type').val());
        var total = postage + type;
        $('#total').val('$' + total.toFixed(2));
    }); 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Ajax form's malfunction is attributed to JSON, as it throws a parser error indicating a SyntaxError. Specifically, the JSON.parse function encounters an unexpected end of data at line 1, column 1

I understand that this is a commonly asked question, but I have tried all the solutions provided and none of them have worked for me. My specific issue is that I am unable to load a JSON response from the server using AJAX. Here's the setup: my "scrip ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...

Troubleshooting MVC3 @Ajax.ActionLink: Unexpected Page Display Instead of Target UpdateId Replacement

My current project is built with VS2010/.net4/MVC3 (MVC4 encounters the same issue) I am attempting to invoke an AJAX function in my project @Ajax.ActionLink("Display ALL Cbms results", "All" , "Cbms", new AjaxOptions() { HttpMethod = "GET", Upda ...

jQuery import children into output

When inserting a div every nth-child and later calling the children of the parent, the jQuery inserted elements do not appear in this new list. How can I retrieve the inserted elements as well? Apologies if this is confusing. If it's easier to under ...

What is the best way to update a CSS class in React JS?

Suppose I have a CSS class called 'track-your-order' in my stylesheet. Whenever a specific event occurs, I need to modify the properties of this class and apply the updated values to the same div without toggling it. The goal is to replace the ex ...

What is the best way to refresh an Angular model containing nested data?

This week, I started working on a proof of concept with Angular Material where I have a table displaying nested data: <table> <thead> <tr> <th colspan="2">Employee Name</th> <th>Ovr&l ...

An issue arises when attempting to execute npm with React JS

I encountered an error after following the setup steps for a react configuration. Can anyone provide assistance? This is the content of the webpack.config.js file: var config = { entry: './main.js', output: { path:'/', ...

Tips for declaring the OpenLayers map object globally

I have successfully created a map with ol 6 and added an OSM layer. Now I am trying to incorporate a vector layer that is coded in another JavaScript file, using the same 'map' object. Despite my efforts to declare it globally, it doesn't se ...

JavaScript: Retrieving the names of children within a <div> element

Within my structure setup, there is a tower div with inner elements like this: <div class="tower"> <div class="E0">abc</div> <div class="GU">123</di </div> The challenge I am facing is that I need to access the in ...

What is the best approach to merging multiple arrays to create a new array in CodeIgniter?

Here are two arrays provided below, where I want to combine the first key of the first array with the second key of the second array to create a new array. [animals1] => Array ( [0] => Horse [1] => Dog1 ...

What is the best way to adjust the size of a button using CSS within a ReactJS

I am facing an issue where I need to create a button with a specific width, but the template I'm using already has predefined styles for buttons. When I try to customize the button's style, nothing seems to change. Below is the code snippet: Her ...

What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

Seamlessly replacing an image in PixiJS without any sudden movement

I'm currently developing a HTML5 JavaScript game with a heavily textured background. My goal is to incorporate a 3D background element that can be swapped out dynamically. For example, the initial scene may show a room with a closed door, but once a J ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

AngularJS - Smoothly navigate to the top of the page by swiping left or right

I'm currently working on a project in angularJS and ionic that involves a slidebox with three slides, each containing different content. My goal is to scroll back to the top every time I switch between slides. Initially, I thought using on-swipe-left ...

Tips for streamlining the use of hidden and visible div elements with concise code

I have been attempting to use the same code for multiple modules on this page, but none of the methods I've tried seem to be effective. I want to avoid endlessly duplicating existing code. document.addEventListener('DOMContentLoaded', fun ...

Using AJAX to filter array values in Rails 3 views

In my project with Rails 3.1 and Ruby 1.92, I am working on enabling users to filter a list of products based on the product type attribute and update the list asynchronously using AJAX after their selection. My strategy involves creating instance variabl ...

Tips for effectively retrieving data from the server in Node.js

When attempting to retrieve data using /data with server-side fetch, I encountered the following errors: response.getCategory is not a function (()=>{ const url = "/data"; fetch(url) .then(response => { console ...

Creating a Seamless Bond Between JavaScript and HTML

I've been struggling to find a helpful and straightforward solution to a simple problem. On my web page, I have five image placeholders that should be filled with one of nine random pictures. To achieve this, I wrote a JavaScript code that generates r ...