javascript - 根据第一个下拉列表的选择将初始值加载到第二个下拉列表中

标签 javascript jquery html joomla joomla-extensions

您好,我正在尝试从 hikashop_product_characteristic_1 中的默认值加载下拉列表中的信息。根据第一个下拉列表中的默认值,我想隐藏 hikashop_product_option_1 下拉列表

下的所有其他选项
<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>

我已将信息放在下面。我遇到的问题是初始页面加载:它正在加载 hikashop_product_option_1 下的所有值,我只希望它根据 hikashop_product_characteristic_1 中的初始值显示该值>

这是我的代码:我已经尝试了一整天但没有成功,我无法让它工作。

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();
    }
});

这是您请求的 hikashopChangeOption 的完整代码

<?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>

以下是您在 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;
    }

//-->

这是 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(); });

//-->

最佳答案

您可以将所需的值放入逗号分隔的字符串中,作为第一个 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>

(注意,我删除了 onchange 监听器)。

然后您可以添加以下功能来仅显示产品所需的选项 select基于特征的选择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'
        });
    });
}

最后,你应该在$(document).ready()中调用这个函数。以及特征的每次变化select :

$(document).ready(function(){
    refreshProducts();

    //handle selection of characteristic
    $(document).on("change", "#hikashop_product_characteristic_1", function(evt){
        refreshProducts();
    });
});

这是Demo

(请注意,我从 characteristics onchange 中删除了内联 select 监听器,如果需要,您可以附加一个)

关于javascript - 根据第一个下拉列表的选择将初始值加载到第二个下拉列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21840832/

相关文章:

html - 右浮动和左浮动元素在语义 ui 中超出容器

javascript - 从 4 级 json 对象数组返回特定​​ json 项

javascript - 模态框打开有奇怪的效果

php - 使用自动完成从 mysql 表返回用户 ID

javascript - 为什么这段代码中需要 setTimeout

特定网页上的 CSS 问题

html - 如何将页脚保持在页面底部并以 html 和 css 居中?

javascript - 未知 vendor | Angular Bootstrap 颜色选择器

javascript - 使用 JSDoc 记录工厂

javascript - 如何使用 jQuery 无限循环播放音频文件