Hola
Hola

Reputation: 83

PHP + jQuery: grabbing data from a PHP form with jQuery

I've done a lot of searching about this and I've tried pretty much everything that has been suggested to no effect.

I have 2 series of radio buttons (only publishing one series):

    <div class='place PP'>
              <input type='radio' name='hotel' class='hotel' value='Natura Cabana Boutique Hotel' required>
              Natura Cabana Boutique Hotel (24.300 DKK)
              <input type='hidden' name='hotelPrice' class='Natura Cabana Boutique Hotel' value='24.300'>
            </div>
    <div class='place PP'>
              <input type='radio' name='hotel' class='hotel' value='Casa Maravilla' required>
              Casa Maravilla (42.500 DKK)
              <input type='hidden' name='hotelPrice' class='Casa Maravilla' value='42.500'>
            </div>
    <div class='place PP'>
              <input type='radio' name='hotel' class='hotel' value='Casa Veintiuno' required>
              Casa Veintiuno (31.500 DKK)
              <input type='hidden' name='hotelPrice' class='Casa Veintiuno' value='31.500'>
            </div>

The value and the price are retrieved from a database.

My jQuery code to show the price looks like this:

$(".hotel").change(function() {
    var hotel = $(this).val();

    switch (hotel) {
        case "Natura Cabana Boutique Hotel":
            var x = new Number(24.300);
            $("#price").val(x.toFixed(3) + " DKK");
            break;
        case "Casa Maravilla":
            var x = new Number(42.500);
            $("#price").val(x.toFixed(3) + " DKK");
            break;
        case "Casa Veintiuno":
            var x = new Number(31.500);
            $("#price").val(x.toFixed(3) + " DKK");
            break;
        // more jQuery code
        } });

How can I pass 2 values and replace the fixed numbers I used with the value of $hotelPrice?

Thanks a lot.

Upvotes: 0

Views: 65

Answers (1)

Marc B
Marc B

Reputation: 360662

Given you've got the price embedded 3 ways (plaintext, hidden form field, JS switch statement), it's rather duplicative. You could ditch everything except the hidden form field, for instance:

<input type='radio' name='hotel' class='hotel' value='Casa Maravilla' required>
Casa Maravilla (<span class="displayPrice">42.500</span> DKK)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^---note new span
<input type='hidden' name='hotelPrice' class='Casa Maravilla' value='42.500'>

Then:

$(".hotel").change(function() {
    price = $(this).siblings('.hotelPrice');
    $(this).parent().children('.displayPrice').val(price);
});

Since every DOM node "knows" where it is in the tree, you can use .siblings() to retrieve the hotel's price from the hidden form field, then .parent().children('...') to find the new span and insert the retrieved price.

Upvotes: 1

Related Questions