I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.
The country is changing along side the shipping. I could alert my shipping but will refuse to display in my div. What could be wrong? All calculations working well and displays well except for the #usashipping please help. My country changes and give the correct value for the calculation. The shipping fee just will not display.
<!-- language: lang-js -->
<script type="application/javascript">
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
$('.add').click(function() {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput= currentValue + 1;
$('#gems').val(newinput);
(newinput);
if(newinput==1)
{
var np1=(19.99*2.0);
flpay= np1.toFixed(2);
$('#flpay').html(flpay);
var tot= (fees + shipping + flpay);
var total= tot.toFixed(2);
$('#total').html(total);
var newp=19.99;
var price= newp.toFixed(2);
$('#price').html(price);
useprice= 19.99;
}
else if(newinput>1)
{
//useprice=useprice;
var newprice= 19.99 + (9.99*(newinput-1));
var np1 =(2*newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot =( fees + shipping + (2*newprice) );
var total= tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp= newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
First & Last Months Payment = $<span data-first-last-month-fees="" id="flpay"></span>
</div>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
<div>
Total due today : $<span data-total-due="" id="total"></span>
</div>
Your code should work perfectly, but there are few things that you could improve in your code:
Instead of declaring shipping variable 3 times in each condition, you need to declare it only once, then update it in each condition, and make sure it's stored as a string so it can be displayed correctly in your HTML.
Instead of updating the HTML content of your span in every condition, just update it with the shipping amount in the end.
This is how should be your code:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
Demo:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="country">
<option value="40">40</option>
<option value="236">236</option>
<option value="100">100</option>
</select>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
I can see error showing in your code. I found "$('.add').click" inside "$('#country').change". Also "$('#country').change" function you declared local variable "var shipping;" that's why no change on global "shipping;" value but you using it inside "$('#country').change" function. I modified little bit now try with following code and comment reply if not work for you:
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
})
$('.add').click(function () {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput = currentValue + 1;
$('#gems').val(newinput);
(newinput);
if (newinput == 1) {
var np1 = (19.99 * 2.0);
flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + flpay);
var total = tot.toFixed(2);
$('#total').html(total);
var newp = 19.99;
var price = newp.toFixed(2);
$('#price').html(price);
useprice = 19.99;
}
else if (newinput > 1) {
//useprice=useprice;
var newprice = 19.99 + (9.99 * (newinput - 1));
var np1 = (2 * newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + (2 * newprice));
var total = tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp = newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
})
I only changed the div id from #usashipping to something else and it works just fine. Maybe #usashippingis now a constant in jquery library.
just need some help with this code. I want a response picked by random in the array, but whenever I inspect the code in browser I have to refresh the page to get a random response. Also I need some tips on how how I can block out the Question section if the user hasn't input a name. Much thanks :)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<p>SoothSayer<br></p>
<form>
Name: <input id="Name" name="textfield" type="text"><br>
Question: <input id="Question" name="textfield" type="text"><br>
Birthday: <select id="month">
<option value=0>  --Month--</option>
<option value=1>January</option>
<option value=2>February</option>
<option value=3>March</option>
<option value=4>April</option>
<option value=5>May</option>
<option value=6>June</option>
<option value=7>July</option>
<option value=8>August</option>
<option value=9>September</option>
<option value=10>October</option>
<option value=11>November</option>
<option value=12>December</option>
</select>
<select id="date">
<option value=0>  --Date--</option>
</select>
</form>
<br>
<span id="sign"></span>
<span id="Random"></span>
<script type="text/javascript">
var dsel = document.getElementById("date");
var msel = document.getElementById("month");
var mong = document.getElementById("Name");
//var schlong = document.getElementById("Question");
var x = ["I see great calamity up ahead, you should definitley hold off on that", "I see great fortune up ahead, you should definitley do that!", "Your way ahead is cloudy, I suggest you dont do that", "Your way ahead is clear and fortunate, I suggest you attemp that!"];
var rand = x[Math.floor(Math.random() * x.length)];
dsel.options.length = 32;
for ( var d = 1; d <= 31; ++d ) {
dsel.options[d] = new Option(d,d);
}
msel.onchange = clearbox;
function clearbox() {
document.getElementById("sign").innerHTML = " ";
document.getElementById("date").selectedIndex = 0;
}
dsel.onchange = getSign;
function getSign( ) {
var m = Number(msel.value);
var d = Number(dsel.value);
var s = "";
var a = mong.value
if ((d == 0) || (m == 0)) {
document.getElementById("sign").innerHTML = " ";
return;
}
var md = m * 100 + d;
if ( m == 1 && d > 0 && d <= 19 ) md = 1299;
if ( md >= 1222 ) { s = "Capricorn"; }
else if ( md >= 1122 ) { s = "Sagittarius"; }
else if ( md >= 1023 ) { s = "Scorpio"; }
else if ( md >= 923 ) { s = "Libra"; }
else if ( md >= 823 ) { s = "Virgo"; }
else if ( md >= 723 ) { s = "Leo"; }
else if ( md >= 622 ) { s = "Cancer"; }
else if ( md >= 521 ) { s = "Gemini"; }
else if ( md >= 420 ) { s = "Taurus"; }
else if ( md >= 321 ) { s = "Aries"; }
else if ( md >= 219 ) { s = "Pisces"; }
else if ( md > 100 ) { s = "Aquarius"; }
document.getElementById("sign").innerHTML = "Your Zodiac sign is " + s +", "+ a + " "+ rand;
}
</script>
</body>
</html>
U can do it by AJAX to retrieve data without refresh the pages
Use time interval, in javascript to run the AJAX function
I'm having trouble filtering resulting div's with jQuery via two different inputs. Users can decide to filter by office, specialty or both office and specialty. The filtering is set from data attributes on the div that correspond to the select inputs values.
<div>
<label for="officeSearch">Search by office:</label>
<select name="Office Search" id="officeSearch">
<option value="all"></option>
<option value="communication">Communication</option>
<option value="internal medicine">Internal Medicine</option>
</select>
</div>
<div>
<label for="specialtySearch">Search by specialty:</label>
<select name="Specialty Search" id="specialtySearch">
<option value="all"></option>
<option value="Bone Cancer">Bone Cancer</option>
<option value="Breast Cancer">Breast Cancer</option>
<option value="Oral Cancer">Oral Cancer</option>
</select>
</div>
<div class="module-sm profile" data-office="communication" data-specialty="Oral Cancer">
<p>Person A</p>
</div>
<div class="module-sm profile" data-office="communication" data-specialty="Breast Cancer">
<p>Person B</p>
</div>
<div class="module-sm profile" data-office="internal medicine" data-specialty="Bone Cancer">
<p>Person C</p>
</div>
Here's the jQuery I'm using that fires on change of the selects:
$(document).ready(function() {
$("#officeSearch").on('change', function(){
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var person = $('#filterList .profile').not('.out');
var allPersons = $('#filterList .profile');
var allPersonsOffice = $('#filterList .profile').data('office');
var allPersonsOut = $('#filterList .profile.out');
var office = $('.profile[data-office="' + selectedOffice +'"]');
alert(''+ selectedOffice + ' ' + selectedSpecialty +'');
if (selectedOffice == 'all' && selectedSpecialty == 'all'){
$(allPersons).removeClass('out').fadeIn(500);
}
else {
$(person).not(office).addClass('out').fadeOut(500);
office.removeClass('out').fadeIn(500);
}
});
$("#specialtySearch").on('change', function(){
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var person = $('#filterList .profile').not('.out');
var allPersons = $('#filterList .profile');
var allPersonsOffice = $('#filterList .profile').data('office');
var allPersonsOut = $('#filterList .profile.out');
var specialty = $('.profile[data-specialty="' + selectedSpecialty +'"]');
alert(''+ selectedOffice + ' ' + selectedSpecialty +'');
if (selectedOffice == 'all' && selectedSpecialty == 'all'){
$(allPersons).removeClass('out').fadeIn(500);
}
else {
$(person).not(specialty).addClass('out').fadeOut(500);
specialty.removeClass('out').fadeIn(500);
}
});
});
If it helps, I've made a codepen to demonstrate what I'm trying to do and where I'm at so far.
I've done some searching and have been scratching my head on how to get this working for weeks. Any help making this code more concise or examples to how others have solved this problem are greatly appreciated!
Call a single update from either selection changing.
Create a filter based on the selections (appended).
Hide the ones not in the matches
show the matches.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/2u7NY/
$(document).ready(function () {
var onChange = function () {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var filter = "#filterList .profile";
var allPersons = $(filter);
if (selectedOffice != "all")
{
filter += '[data-office="' + selectedOffice + '"]'
}
if (selectedSpecialty != "all")
{
filter += '[data-specialty="' + selectedSpecialty + '"]'
}
var $matching = allPersons.filter(filter);
$(allPersons).not($matching).removeClass('out').fadeOut(500);
$matching.removeClass('out').fadeIn(500);
}
$("#officeSearch, #specialtySearch").on('change', onChange );
});
Update: http://jsfiddle.net/TrueBlueAussie/2u7NY/2/
The filter can be made slightly more efficient as "#filterList .profile" is not needed to filter allPersons based on attributes.
I also removed the function variable and placed the function inline on the change event.
$(document).ready(function () {
$("#officeSearch, #specialtySearch").on('change',
function () {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var allPersons = $("#filterList .profile");
var filter = "";
if (selectedOffice != "all") {
filter = '[data-office="' + selectedOffice + '"]'
}
if (selectedSpecialty != "all") {
filter += '[data-specialty="' + selectedSpecialty + '"]'
}
var $matching = allPersons.filter(filter);
$(allPersons).not($matching).removeClass('out').fadeOut(500);
$matching.removeClass('out').fadeIn(500);
});
});
OK. Try something like this....
var match = function(office, specialty, profile) {
var show = ((office == 'all' || office == $(profile).data('office')) &&
(specialty == 'all' || specialty == $(profile).data('specialty')));
if (show && !$(profile).is(':visible')) {
$(profile).fadeIn();
}
if (!show && $(profile).is(':visible')) {
$(profile).fadeOut();
}
}
var filter = function() {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
$.each($('#filterList .profile'), function(i, profile) {
match(selectedOffice, selectedSpecialty, profile);
});
};
$("#officeSearch").on('change', function(){
filter();
});
$("#specialtySearch").on('change', function(){
filter();
});
working fiddle here.... http://jsfiddle.net/6Q8FF/
Hi I am trying to load the information from my dropdown from the default value in hikashop_product_characteristic_1. Based off of what the default value is in this first dropdown i want to hide all other options under the hikashop_product_option_1 dropdown
<select id="hikashop_product_characteristic_1" name="hikashop_product_characteristic[1]" class="inputbox" size="1" onchange="return hikashopUpdateVariant(this);">
<option value="2" selected="selected">Twin</option>
<option value="6">Full</option>
<option value="7">Queen</option>
<option value="8">King</option>
<option value="9">Cal King</option>
</select>
<select id="hikashop_product_option_1" name="hikashop_product_option[1]" class="inputbox" size="1" onchange="hikashopChangeOption();">
<option value="0" selected="selected">No</option>
<option value="775"> Twin ( +
$39.99
)</option>
<option value="774"> Twin Heavy Duty ( +
$49.99
)</option>
<option value="769"> Twin Heavy Duty Glideamatic ( +
$59.99
)</option>
<option value="772"> Twin XL ( +
$39.99
)</option>
<option value="771"> Twin XL Heavy Duty ( +
$49.99
)</option>
<option value="770"> Twin XL Heavy Duty Glideamatic ( +
$59.99
)</option>
<option value="776"> Full ( +
$39.99
)</option>
<option value="777"> Full Heavy Duty ( +
$49.99
)</option>
<option value="778"> Full Heavy Duty Glideamatic ( +
$59.99
)</option>
<option value="773"> Queen ( +
$49.99
)</option>
<option value="779"> Queen Heavy Duty ( +
$59.99
)</option>
<option value="780"> Queen Heavy Duty Glideamatic ( +
$99.99
)</option>
<option value="781"> King ( +
$59.99
)</option>
<option value="782"> King Heavy Duty ( +
$69.99
)</option>
<option value="783"> King Heavy Duty Glideamatic ( +
$99.99
)</option>
<option value="784"> Cal King ( +
$59.99
)</option>
<option value="785"> Cal King Heavy Duty ( +
$69.99
)</option>
<option value="786"> Cal King Heavy Duty Glideamatic ( +
$99.99
)</option>
</select>
I have put the information below. The problem I am having is on inital page load: it is loading all the values under hikashop_product_option_1 and I only want it to show the value based off what the intial value is in hikashop_product_characteristic_1
Here is the code I have below: I have tried all day with no success I cannot get this to work.
http://jsfiddle.net/HYQpj/4/
var subselectContains = {
"Twin": [0,775,774,769], //Twin
"Twin XL": [0,772,771,770], //Twin XL
"Full": [0,776,777,778], //Full
"Queen": [0,773,779,780], //Queen
"King": [0,781,782,783], //King
"Cal King": [0,784,785,786] //Cal King
};
var productcharacteristics = $("#hikashop_product_characteristic_1");
var solutionOptions = $("#hikashop_product_option_1 option");
productcharacteristics.change(function () {
var visibleOptions = subselectContains[this.options[this.selectedIndex].textContent];
if (visibleOptions.length != 0) {
solutionOptions.hide();
solutionOptions.each(function () {
for (var i = 0; i <= visibleOptions.length; i++) {
if (this.value == visibleOptions[i]) {
$(this).show();
}
}
});
} else {
solutionOptions.show();
}
});
Here is the complete code for the hikashopChangeOption you requested
<?php
/**
* #package HikaShop for Joomla!
* #version 2.3.0
* #author hikashop.com
* #copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved.
* #license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><table class="hikashop_product_options_table">
<?php
$this->setLayout('listing_price');
$old_show_discount = $this->params->get('show_discount');
$old_per_unit = $this->params->get('per_unit',1);
$this->params->set('show_discount',0);
$this->params->set('per_unit',0);
$this->params->set('from_module','1');
$i=0;
$js="var hikashop_options=Array();";
foreach($this->element->options as $optionElement){
?>
<tr>
<?php $this->values = array();
$value = 0;
$currency = hikashop_get('class.currency');
$map = 'hikashop_product_option['.$i.']';
$id = 'hikashop_product_option_'.$i;
if(empty($optionElement->variants)){
if(!$optionElement->product_published || (!$this->config->get('show_out_of_stock',1) && $optionElement->product_quantity==0)) continue;
$this->values[] = JHTML::_('select.option', 0,JText::_('HIKASHOP_NO'));
$text = JText::_('HIKASHOP_YES');
$this->row =& $optionElement;
if(!empty($optionElement->prices) && $this->params->get('show_price')){
$ok = null;
$positive=1;
foreach($optionElement->prices as $k => $price){
if(empty($price->price_min_quantity)){
$ok = $price;
if($price->price_value<0) $positive=false;
break;
}
}
$this->row->prices = array($ok);
$text.=' ( '.($positive?'+ ':'').strip_tags($this->loadTemplate()).' )';
if($this->params->get('price_with_tax')){
$price = $ok->price_value_with_tax;
}else{
$price = $ok->price_value;
}
$js.="
hikashop_options[".(int)$optionElement->product_id."]=".(float)$price.";";
}
$this->values[] = JHTML::_('select.option', $optionElement->product_id,$text);
}else{
$defaultValue=array();
if(isset($optionElement->characteristics) && is_array($optionElement->characteristics) && count($optionElement->characteristics)){
foreach($optionElement->characteristics as $char){
$defaultValue[]=$char->characteristic_id;
}
}
foreach($optionElement->variants as $variant){
if(!$variant->product_published || (!$this->config->get('show_out_of_stock',1) && empty($variant->product_quantity))) continue;
if($variant->product_sale_start>time()) continue;
if($variant->product_sale_end!='' && $variant->product_sale_end!='0' && $variant->product_sale_end<time()) continue;
if(empty($variant->variant_name)){
if(empty($variant->characteristics_text)){
$text = $variant->product_name;
}else{
$text = $variant->characteristics_text;
}
}else{
$text = $variant->variant_name;
}
$this->row =& $variant;
if(!empty($variant->prices) && $this->params->get('show_price')){
$ok = null;
$positive=1;
foreach($variant->prices as $k => $price){
if(empty($price->price_min_quantity)){
$ok = $price;
if($price->price_value<0) $positive=false;
break;
}
}
$this->row->prices = array($ok);
$text.=' ( '.($positive?'+ ':'').strip_tags($this->loadTemplate()).' )';
if($this->params->get('price_with_tax')){
$price = $ok->price_value_with_tax;
}else{
$price = $ok->price_value;
}
$js.="
hikashop_options[".(int)$variant->product_id."]=".(float)$price.";";
}
if($defaultValue && isset($variant->characteristics) && is_array($variant->characteristics) && count($variant->characteristics)){
$default = true;
foreach($variant->characteristics as $char){
if(!in_array($char->characteristic_id,$defaultValue)){
$default = false;
}
}
if($default){
$value = $variant->product_id;
}
}
$this->values[] = JHTML::_('select.option', $variant->product_id,$text);
}
}
if(!count($this->values)) continue;
$html = JHTML::_('select.genericlist', $this->values, $map, 'class="inputbox" size="1" onchange="hikashopChangeOption();"', 'value', 'text', (int)$value,$id );
if(!empty($optionElement->variants)){
$optionInfo =& $optionElement->main;
}else{
$optionInfo =& $optionElement;
}
$options='';
if(!empty($optionInfo->product_description) || !empty($optionInfo->product_url)){
$options='<img src="'.HIKASHOP_IMAGES.'info.png" alt="Information"/>';
$description = '';
if(!empty($optionInfo->product_description)){
$description = $this->escape(strip_tags(JHTML::_('content.prepare',$optionInfo->product_description)));
$options='<span class="hikashop_option_info" title="'.$description.'">'.$options.'</span>';
}
if(!empty($optionInfo->product_url)){
JHTML::_('behavior.modal');
if(empty($description)){
$description = $optionInfo->product_name;
}
$options='<a class="hikashop_option_info_link modal" rel="{handler: \'iframe\', size: {x: 450, y: 480}}" title="'.$description.'" href="'.$optionInfo->product_url.'">'.$options.'</a>';
}
}
$html='<span class="hikashop_option_name" >'.$optionInfo->product_name.$options.'</span></td><td>'.$html;
?>
<td>
<?php echo $html; ?>
</td>
</tr>
<?php $i++;
}
global $Itemid;
$url_itemid='';
if(!empty($Itemid)){
$url_itemid='&Itemid='.$Itemid;
}
$baseUrl = hikashop_completeLink('product&task=price',true,true);
if(strpos($baseUrl,'?')!==false){
$baseUrl.='&';
}else{
$baseUrl.='?';
}
$js = $js. "
function hikashopChangeOption(){
var j = 0;
total_option_price = 0;
while(true){
var option = document.getElementById('hikashop_product_option_'+j);
if(!option){
break;
}
j++;
var option_price = hikashop_options[option.value];
if(option_price){
total_option_price+=option_price;
}
}
var arr = new Array();
arr = document.getElementsByName('hikashop_price_product');
for(var i = 0; i < arr.length; i++){
var obj = document.getElementsByName('hikashop_price_product').item(i);
var id_price = 'hikashop_price_product_' + obj.value;
var id_price_with_options = 'hikashop_price_product_with_options_' + obj.value;
var price = document.getElementById(id_price);
var price_with_options = document.getElementById(id_price_with_options);
if(price && price_with_options){
price_with_options.value = parseFloat(price.value) + total_option_price;
}
}
hikashopRefreshOptionPrice();
}
function hikashopRefreshOptionPrice(){
var price_div = document.getElementById('hikashop_product_id_main');
var inputs = price_div.getElementsByTagName('input');
if(inputs[0]){
var id_price_with_options = 'hikashop_price_product_with_options_' + inputs[0].value;
var price_with_options = document.getElementById(id_price_with_options);
if(price_with_options){
try{
new Ajax('".$baseUrl."price='+price_with_options.value+'".$url_itemid."', { method: 'get', onComplete: function(result) { var totalPrice = window.document.getElementById('hikashop_product_price_with_options_main'); if(totalPrice) totalPrice.innerHTML = result;}}).request();
}catch(err){
new Request({url:'".$baseUrl."price='+price_with_options.value+'".$url_itemid."', method: 'get', onComplete: function(result) { var totalPrice = window.document.getElementById('hikashop_product_price_with_options_main'); if(totalPrice) totalPrice.innerHTML = result;}}).send();
}
}
}
}
window.addEvent('domready', function() { hikashopChangeOption(); });
";
if (!HIKASHOP_PHP5) {
$doc =& JFactory::getDocument();
}else{
$doc = JFactory::getDocument();
}
$doc->addScriptDeclaration("\n<!--\n".$js."\n//-->\n");
$this->params->set('show_discount',$old_show_discount);
$this->params->set('per_unit',$old_per_unit);
$this->params->set('from_module','');
?>
</table>
Here is the code for the product variant you requested in the html:
function hikashopUpdateVariant(obj){
var options = ['1'];
var len = options.length;
var selection = '';
var found=false;
try { obj.blur(); } catch(e){}
if(obj.type=='radio'){
var form = document['hikashop_product_form'];
if(form){
for (var i = 0; i < len; i++){
var checkFields = form.elements['hikashop_product_characteristic['+options[i]+']'];
if(checkFields){
if(!checkFields.length && checkFields.value){
selection = selection + '_' + checkFields.value;
continue;
}
var len2 = checkFields.length;
for (var j = 0; j < len2; j++){
if(checkFields[j].checked){
selection = selection + '_' + checkFields[j].value;
found=true;
}
}
}
if(!found){
return true;
}
}
}
}else{
for (var i = 0; i < len; i++){
selection = selection + '_' + document.getElementById('hikashop_product_characteristic_'+options[i]).value;
}
}
hikashopUpdateVariantData(selection);
return true;
}
function hikashopUpdateVariantData(selection){
if(selection){
var names = ['id','name','code','image','price','quantity','description','weight','url','width','length','height','contact','custom_info','files'];
var len = names.length;
for (var i = 0; i < len; i++){
var el = document.getElementById('hikashop_product_'+names[i]+'_main');
var el2 = document.getElementById('hikashop_product_'+names[i]+selection);
if(el && el2) el.innerHTML = el2.innerHTML.replace(/_VARIANT_NAME/g, selection);
}
if(typeof this.window['hikashopRefreshOptionPrice'] == 'function') hikashopRefreshOptionPrice();
if(window.Oby && window.Oby.fireAjax) window.Oby.fireAjax("hkContentChanged");
}
return true;
}
//-->
Here is the product code for the product options in the html
function hikashopChangeOption(){
var j = 0;
total_option_price = 0;
while(true){
var option = document.getElementById('hikashop_product_option_'+j);
if(!option){
break;
}
j++;
var option_price = hikashop_options[option.value];
if(option_price){
total_option_price+=option_price;
}
}
var arr = new Array();
arr = document.getElementsByName('hikashop_price_product');
for(var i = 0; i < arr.length; i++){
var obj = document.getElementsByName('hikashop_price_product').item(i);
var id_price = 'hikashop_price_product_' + obj.value;
var id_price_with_options = 'hikashop_price_product_with_options_' + obj.value;
var price = document.getElementById(id_price);
var price_with_options = document.getElementById(id_price_with_options);
if(price && price_with_options){
price_with_options.value = parseFloat(price.value) + total_option_price;
}
}
hikashopRefreshOptionPrice();
}
function hikashopRefreshOptionPrice(){
var price_div = document.getElementById('hikashop_product_id_main');
var inputs = price_div.getElementsByTagName('input');
if(inputs[0]){
var id_price_with_options = 'hikashop_price_product_with_options_' + inputs[0].value;
var price_with_options = document.getElementById(id_price_with_options);
if(price_with_options){
try{
new Ajax('/mattresses/product/price/tmpl-component.html?price='+price_with_options.value+'&Itemid=231', { method: 'get', onComplete: function(result) { var totalPrice = window.document.getElementById('hikashop_product_price_with_options_main'); if(totalPrice) totalPrice.innerHTML = result;}}).request();
}catch(err){
new Request({url:'/mattresses/product/price/tmpl-component.html?price='+price_with_options.value+'&Itemid=231', method: 'get', onComplete: function(result) { var totalPrice = window.document.getElementById('hikashop_product_price_with_options_main'); if(totalPrice) totalPrice.innerHTML = result;}}).send();
}
}
}
}
window.addEvent('domready', function() { hikashopChangeOption(); });
//-->
You can put needed values to a comma-separated string as a values of the options of the first select:
<select id="hikashop_product_characteristic_1" name="hikashop_product_characteristic[1]" class="inputbox" size="1">
<option value="0,775,774,769" selected="selected">Twin</option>
<option value="0,772,771,770">Twin XL</option>
<option value="0,776,777,778">Full</option>
<option value="0,773,779,780">Queen</option>
<option value="0,781,782,783">King</option>
<option value="0,784,785,786">Cal King</option>
</select>
(note, that i removed onchange listener).
Then you can add following function to show only needed options of the products selectbased on selection of the characteristics select:
function refreshProducts() {
//get the selected value and parse it to array
var parsedValues = $("#hikashop_product_characteristic_1").val().split(",");
//find products select
var selectProduct = $("#hikashop_product_option_1");
//reset selection
selectProduct.val(0);
//hide all it's options
selectProduct.find("option").css({
display: 'none'
});
//go over each parsed value
$.each(parsedValues, function (index, value) {
//find and show an option which has it's value equals to needed value
selectProduct.find("option[value='" + parseFloat(value) + "']").css({
display: 'block'
});
});
}
Finally, you should call this function in $(document).ready() and on each change of characteristics select:
$(document).ready(function(){
refreshProducts();
//handle selection of characteristic
$(document).on("change", "#hikashop_product_characteristic_1", function(evt){
refreshProducts();
});
});
Here is the Demo
(note that i removed inline onchange listener from characteristics select, you can attach one if you need)