Value change on drop down or check box

I searched the whole Internet, but could not find any buy now form close to this.

The values are changing on a drop-down selection and checkbox selection.

Is this achieved through AJAX(something that I do not know at the moment today)/ javascript or this can be achieved purely through HTML/CSS?

The above seems to be inspired by Amazon buy now form style.

Certainly there will be javascript involved. Ajax, possibly, depends if all the data is already loaded in a script on the page, or if it needs to query the server to get more data.
Will move to js forum.

2 Likes

7 posts were split to a new topic: What are these image types?

I believe the type of image / font / whatever is tangential to your question.

I think that AJAX is not involved with what is displayed on the form.

I usually do fairly well with animations, but I’ve looked at the screen capture and still can’t see what exactly is changing based on something else being changed. As best as I can tell, various option combinations require specific plans. And various plans do not include certain options. (I would go with a table where the differences could be seen at a glance) Anyway, this could be done with JavaScript, though getting the logic right might be tricky

In extreme alpha pseudocode it could be something like

// event handlers for both plans and options 
// plan logic 
function somefunction(plan) {
displayed_price = plan.id; 
}
// option logic 
function otherfunction(option_array) {
  if ( option['1'] === 'checked' ) 
    && ( option['2'] === 'checked' ) 
    && ( option['3'] === 'checked' ) { 
      selected_plan = 1; 
      displayed_price = 1;
  } 
// else ifs 
}
2 Likes

Javascripts functions seems identical to PHP functions.

They do have many similarities. But they are not entirely the same by any means. Having an understanding of syntax, data types, control logic structure etc. in one will help a lot with understanding the other. But there is more to each than those similarities alone that could and have taken books to cover.

1 Like

Any advice for a beginner like me where to start learning Java scripting?[quote=“Mittineague, post:10, topic:283724”]
// event handlers for both plans and options
// plan logic
function somefunction(plan) {
displayed_price = plan.id;
}
// option logic
function otherfunction(option_array) {
if ( option[‘1’] === ‘checked’ )
&& ( option[‘2’] === ‘checked’ )
&& ( option[‘3’] === ‘checked’ ) {
selected_plan = 1;
displayed_price = 1;
}
// else ifs
}
[/quote]

In our example, we have 3 License type, and then we have 3 add-on services(0 or all can be selected).

So if we use some mathematics(permutation and combination).

then3 Licenses can give 3 possibilities, and with every possibility, there can be 0, 1, 2, or all 3 add-on services selected.

so,

3 X (3C0 + 3C1 + 3C2 + 3C3) =
3 X (1 +3 + 3 + 1) =
3 X (8) =
24
If conditions needs to be created; I guess there should be some smart method to achive this.

After studying the animated image, it’s only the dropdown box that changes the price.
I’ve added a total area at the bottom though, which makes things trickier.

First we start with the form, which is a dropdown list and some checkboxes

<form id="order">
  <p>Item Price USD</p>
  <p class="price">$59</p>
  <select name="licenseType">
    <option value="single">Single-Domain License</option>
    <option value="5-domain">5 Domain License</option>
    <option value="developer">Developer License</option>
  </select>
  <hr>
  <h2>Recommended Add-On's</h2>
  <p>
    <input type="checkbox" name="installTheme"> Install Your WordPress Theme <span class="price">$49</span></p>
  <p>
    <input type="checkbox" name="amazingLooks"> Make My Wordpress Site Look Amazing <span class="price">$149</span></p>
  <p>
    <input type="checkbox" name="backupSite"> Backup Your Wordpress WebSite <span class="price">$99</span></p>
  <p>Total = <span class="total">$59</span></p>
</form>

For the scripting, we keep it well behaved by putting it in an IIFE (immediately invoked function expression), and to sue strict mode, which helps to prevent common issues from occurring.

(function iife() {
    "use strict";
    // rest of code here
}());

We need to get several pieces of information from the form, so these functions help us to do that:

    function getPriceEl(form) {
        return form.querySelector(".price");
    }
    function getCheckboxes(form) {
        return form.querySelectorAll("input[type='checkbox']");
    }
    function getCheckboxPrice(checkbox) {
        return checkbox.parentNode.querySelector(".price").innerHTML;
    }
    function getTotalEl(form) {
        return form.querySelector(".total");
    }

Updating the price is a simple matter of using the index of the selected option, to pick a value from an array of prices.

    function updatePrice(select, prices) {
        var price = getPriceEl(select.form);
        price.innerHTML = "$" + prices[select.selectedIndex];
    }

We trigger that price update whenever the dropdown list is changed.

    function updatePriceHandler(evt) {
        var select = evt.target;
        var form = select.form;
        updatePrice(select, prices);
        updateTotal(form);
    }

    var prices = [59, 236, 1475];
    var form = document.querySelector("#order");
    var select = form.elements.licenseType;
    select.addEventListener("change", updatePriceHandler);

The prices we can get in any way such as by using an Ajax request, but I’ve just use an array for them here.

    var prices = [59, 236, 1475];

When sending the form, it’s vitally important that you do not send price information through to the server because we can not trust the client. Instead, send the form information through (the select and the checkboxes), and have the server calculate everything for itself as well.

Updating the total is made easier with the help of some helper functions:

    function isChecked(checkbox) {
        return checkbox.checked;
    }
    function priceToValue(price) {
        return Number(price.split("$")[1]);
    }
    function sum(val1, val2) {
        return val1 + val2;
    }

We can now use those helper functions to make updating the total really easy.
The checkbox totals are the most difficult, but by filtering for only the checked checkboxes, we can reduce things down to a total from them:

    function checkboxTotals(checkboxes) {
        return Array.from(checkboxes)
            .filter(isChecked)
            .map(getCheckboxPrice)
            .map(priceToValue)
            .reduce(sum, 0);
    }

And we can then incorporate that in the total for the whole form:

    function updateTotal(form) {
        var total = getTotalEl(form);
        var dropdownPrice = priceToValue(getPriceEl(form).innerHTML);
        var checkboxTotal = checkboxTotals(getCheckboxes(form));
        var totalPrice = dropdownPrice + checkboxTotal;
        total.innerHTML = "$" + totalPrice;
    }

Which gets called from the updatePriceHandler() function that you saw above, and from a separate click handler on each checkbox:

    function updateTotalHandler(evt) {
        var form = evt.target.form;
        updateTotal(form);
    }
    // ...
    var checkboxes = getCheckboxes(form);
    
    checkboxes.forEach(function addCheckboxHandler(checkbox) {
        checkbox.addEventListener("click", updateTotalHandler);
    });

All together, the code looks like this:

(function iife() {
    "use strict";

    function getPriceEl(form) {
        return form.querySelector(".price");
    }
    function getCheckboxes(form) {
        return form.querySelectorAll("input[type='checkbox']");
    }
    function getCheckboxPrice(checkbox) {
        return checkbox.parentNode.querySelector(".price").innerHTML;
    }
    function getTotalEl(form) {
        return form.querySelector(".total");
    }
    function updatePrice(select, prices) {
        var price = getPriceEl(select.form);
        price.innerHTML = "$" + prices[select.selectedIndex];
    }
    function isChecked(checkbox) {
        return checkbox.checked;
    }
    function priceToValue(price) {
        return Number(price.split("$")[1]);
    }
    function sum(val1, val2) {
        return val1 + val2;
    }
    function checkboxTotals(checkboxes) {
        return Array.from(checkboxes)
            .filter(isChecked)
            .map(getCheckboxPrice)
            .map(priceToValue)
            .reduce(sum, 0);
    }
    function updateTotal(form) {
        var total = getTotalEl(form);
        var dropdownPrice = priceToValue(getPriceEl(form).innerHTML);
        var checkboxTotal = checkboxTotals(getCheckboxes(form));
        var totalPrice = dropdownPrice + checkboxTotal;
        total.innerHTML = "$" + totalPrice;
    }
    function updatePriceHandler(evt) {
        var select = evt.target;
        var form = select.form;
        updatePrice(select, prices);
        updateTotal(form);
    }
    function updateTotalHandler(evt) {
        var form = evt.target.form;
        updateTotal(form);
    }

    var prices = [59, 236, 1475];
    var form = document.querySelector("#order");
    var select = form.elements.licenseType;
    var checkboxes = getCheckboxes(form);
    select.addEventListener("change", updatePriceHandler);
    checkboxes.forEach(function addCheckboxHandler(checkbox) {
        checkbox.addEventListener("click", updateTotalHandler);
    });
}());

And a working example (without the CSS to make it look pretty) is found at https://jsfiddle.net/nyyL3tw4/2/

5 Likes

Taking things further, I’ve applied my meager CSS skills and without going for pixel-perfection, have come up with a rather similar design while sicking with em’s and relative sizes such as larger and x-small.

The updated code with the appropriate CSS is found at https://jsfiddle.net/nyyL3tw4/4/

3 Likes

Thanks in the meanwhile I was trying to build the form here.

I used this CSS for the select →

display: inline-block;
	width: 300px;
	cursor: pointer;
	padding: 10px 15px;
	outline: 0;
	border: 0;
	border-radius: 0;
	background: #FFFFFF;
	color: #000000;
	appearance: none;
	-webkit-appearance: none;
	-moz-appearance: none;

Post this CSS the drop-down arrow has disappeared from the select. what CSS removed that?

Right-click on the dropdown box and select “Inspect element”. You should be able to investigate the css styles that are applied to that element.

1 Like

In the meanwhile I was doing this, and realized that →

-webkit-appearance: none; 

was conflicting.

1 Like

I changed few classes in my custom.js based my HTML

But my form here doesn’t seem to take the custom.js in effect.

I have also included the custom.js → Looks like I am missing something.

the live URL is this one.

The browser console tells you that the problem is with addEventListener

1 Like

the console is showing error at this line:

select.addEventListener("change", updatePriceHandler);`

the function is this →

function updatePriceHandler(evt) {
    var select = evt.target;
    var form = select.form;
    updatePrice(select, prices);
    updateTotal(form);
  }

what do you think where is the problem?

The cause of the problem is that the select variable is undefined. Investigation as to why that select variable is undefined will lead you to the cause of the problem.

1 Like

Fixed!

var select = form.elements.licensetype;

needed to be changed to

var select = form.elements.license_type;

because of this in my HTML:

<select class="license_type" name="license_type" id="">

My top one $amount is updating, but the bottom one is not updating.

What does the browser console have to say about this particular issue?

1 Like

This one →

That’s right, so why would it have a problem with add ?

1 Like