简体   繁体   English

JQuery Change下拉列表项

[英]JQuery Change Drop Down List Items

So I have a fairly complicated piece of code that a previous programmer wrote for me; 所以我有一个相当复杂的代码,以前的程序员为我写的; however, it is now showing an error in the console and blocking other jquery scripts from running on the page. 但是,它现在在控制台中显示错误,并阻止其他jquery脚本在页面上运行。 I wouldn't really care about the console error, but it is blocking a modal box from popping up for users to login along with blocking fancybox lightbox. 我不太在意控制台错误,但是它阻止弹出一个模式框,以阻止用户登录以及阻止fancybox灯箱。

To see a live version of the problem you could go to: http://www.cabcot.com/listings/united-states/colorado/alamosa/ . 要查看问题的实时版本,您可以访问: http//www.cabcot.com/listings/united-states/colorado/alamosa/

The goal of the code is to have a drop down list automatically get filled based upon a previously selected drop down list. 该代码的目标是根据先前选择的下拉列表自动填充下拉列表。 For example, using the previously mentioned url in the top left "Search Listings" if someone selects "United States" it would then have a list of states in that country. 例如,如果有人选择“美国”,则使用左上角“搜索列表”中的前面提到的URL,然后它将具有该国家/地区的州列表。 Then if the user selects a state in would display a list of cities in that state in the select box below. 然后,如果用户选择状态,则会在下面的选择框中显示该状态的城市列表。 That part works well, except for it continually throws the console code "Uncaught ReferenceError: request is not defined" and is blocking other jquery modal boxes and lightboxes. 该部分工作良好,除了不断抛出控制台代码“ Uncaught ReferenceError:未定义请求”,并阻止其他jquery模式框和灯箱。 I believe I have narrowed down the problem to an on-page javascript that automatically fills in the dropdown selects if that person is on a specific page. 我相信我已经将问题缩小到页面上的javascript,如果该人在特定页面上,则会自动填写下拉选项。 For example if the user is on the page for Colorado, then the select box for Country would be United States, for State would be Colorado. 例如,如果用户在科罗拉多州的页面上,那么国家的选择框将是美国,因为州将是科罗拉多州。 All of it does what it is supposed to do, but it blocks other jquery scripts from running. 所有这些都做它应该做的事情,但它阻止其他jquery脚本运行。 Here is the code: 这是代码:

Javascript Ajax Javascript Ajax

 <?php
  header('Content-Type: text/javascript; charset=UTF-8');
  // ...
?>


function sack(file) {
this.xmlhttp = null;
this.resetData = function () {
    this.method = "POST";
    this.queryStringSeparator = "?";
    this.argumentSeparator = "&";
    this.URLString = "";
    this.encodeURIString = true;
    this.execute = false;
    this.element = null;
    this.elementObj = null;
    this.requestFile = file;
    this.vars = new Object();
    this.responseStatus = new Array(2);
};
this.resetFunctions = function () {
    this.onLoading = function () {};
    this.onLoaded = function () {};
    this.onInteractive = function () {};
    this.onCompletion = function () {};
    this.onError = function () {};
    this.onFail = function () {};
};
this.reset = function () {
    this.resetFunctions();
    this.resetData();
};
this.createAJAX = function () {
    try {
        this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {
        try {
            this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            this.xmlhttp = null;
        }
    }
    if (!this.xmlhttp) {
        if (typeof XMLHttpRequest != "undefined") {
            this.xmlhttp = new XMLHttpRequest();
        } else {
            this.failed = true;
        }
    }
};
this.setVar = function (name, value) {
    this.vars[name] = Array(value, false);
};
this.encVar = function (name, value, returnvars) {
    if (true == returnvars) {
        return Array(encodeURIComponent(name), encodeURIComponent(value));
    } else {
        this.vars[encodeURIComponent(name)] =     Array(encodeURIComponent(value), true);
    }
}
this.processURLString = function (string, encode) {
    encoded = encodeURIComponent(this.argumentSeparator);
    regexp = new RegExp(this.argumentSeparator + "|" + encoded);
    varArray = string.split(regexp);
    for (i = 0; i < varArray.length; i++) {
        urlVars = varArray[i].split("=");
        if (true == encode) {
            this.encVar(urlVars[0], urlVars[1]);
        } else {
            this.setVar(urlVars[0], urlVars[1]);
        }
    }
}
this.createURLString = function (urlstring) {
    if (this.encodeURIString && this.URLString.length) {
        this.processURLString(this.URLString, true);
    }
    if (urlstring) {
        if (this.URLString.length) {
            this.URLString += this.argumentSeparator + urlstring;
        } else {
            this.URLString = urlstring;
        }
    }
    this.setVar("rndval", new Date().getTime());
    urlstringtemp = new Array();
    for (key in this.vars) {
        if (false == this.vars[key][1] && true == this.encodeURIString) {
            encoded = this.encVar(key, this.vars[key][0], true);
            delete this.vars[key];
            this.vars[encoded[0]] = Array(encoded[1], true);
            key = encoded[0];
        }
        urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
    }
    if (urlstring) {
        this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
    } else {
        this.URLString += urlstringtemp.join(this.argumentSeparator);
    }
}
this.runResponse = function () {
    eval(this.response);
}
this.runAJAX = function (urlstring) {
    if (this.failed) {
        this.onFail();
    } else {
        this.createURLString(urlstring);
        if (this.element) {
            this.elementObj = document.getElementById(this.element);
        }
        if (this.xmlhttp) {
            var self = this;
            if (this.method == "GET") {
                totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
                this.xmlhttp.open(this.method, totalurlstring, true);
            } else {
                this.xmlhttp.open(this.method, this.requestFile, true);
                try {
                    this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
                } catch (e) {}
            }
            this.xmlhttp.onreadystatechange = function () {
                switch (self.xmlhttp.readyState) {
                    case 1:
                        self.onLoading();
                        break;
                    case 2:
                        self.onLoaded();
                        break;
                    case 3:
                        self.onInteractive();
                        break;
                    case 4:
                        self.response = self.xmlhttp.responseText;
                        self.responseXML = self.xmlhttp.responseXML;
                        self.responseStatus[0] = self.xmlhttp.status;
                        self.responseStatus[1] = self.xmlhttp.statusText;
                        if (self.execute) {
                            self.runResponse();
                        }
                        if (self.elementObj) {
                            elemNodeName = self.elementObj.nodeName;
                            elemNodeName.toLowerCase();
                            if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
                                self.elementObj.value = self.response;
                            } else {
                                self.elementObj.innerHTML = self.response;
                            }
                        }
                        if (self.responseStatus[0] == "200") {
                            self.onCompletion();
                        } else {
                            self.onError();
                        }
                        self.URLString = "";
                        break;
                }
            };
            this.xmlhttp.send(this.URLString);
        }
    }
};
this.reset();
this.createAJAX();
}
var ajax = new Array();

function getFSREPlist(sel, elementidupdate, fsrepvariable, currentvalue) {
if (sel == '[object]' || sel == '[object HTMLSelectElement]') {
    var FSREPID = sel.options[sel.selectedIndex].value;
} else {
    var FSREPID = sel;
}
document.getElementById(elementidupdate).options.length = 0;
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'http://www.cabcot.com/wp-content/plugins/firestorm-real-estate-plugin/search.php?' + fsrepvariable + '=' + FSREPID + '&cvalue=' + currentvalue;
ajax[index].onCompletion = function () {
    ElementUpdate(index, elementidupdate)
};
ajax[index].runAJAX();
}

function ElementUpdate(index, elementidupdate) {
    var obj = document.getElementById(elementidupdate);
    eval(ajax[index].response);
}

Here is the search.php 这是search.php

<?php
require("../../../wp-config.php"); 

if(isset($_GET['ProvinceID'])){
    $FSREPCities = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."fsrep_cities WHERE province_id = ".$_GET['ProvinceID']." ORDER BY city_name");
    $FSREPProvince = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."fsrep_provinces WHERE province_id = ".$_GET['ProvinceID']);
    $HTTPREFERER = explode('?', $_SERVER['HTTP_REFERER']);
    if (substr($HTTPREFERER[0], -13) == '/add-listing/') {
        echo "obj.options[obj.options.length] = new Option('Select a City','');\n";
    } else {
        echo "obj.options[obj.options.length] = new Option('Search All of ".$FSREPProvince->province_name."','');\n";
    }
    $count = 1;
    foreach ($FSREPCities as $FSREPCities) {
        echo "obj.options[obj.options.length] = new Option('".$FSREPCities->city_name."','".$FSREPCities->city_id."');\n";
        if ($FSREPCities->city_id == $_GET['cvalue']) {
            echo "obj.options[$count].selected = true;";
        }
        $count++;
    }
}
if(isset($_GET['CountryID'])){
    $FSREPProvinces = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."fsrep_provinces WHERE country_id = ".$_GET['CountryID']." ORDER BY province_name");
    $FSREPCountry = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."fsrep_countries WHERE country_id = ".$_GET['CountryID']);
    $count = 1;
    echo "obj.options[obj.options.length] = new Option('Select a State/Province','');\n";
    foreach ($FSREPProvinces as $FSREPProvinces) {
        echo "obj.options[obj.options.length] = new Option('".$FSREPProvinces->province_name."','".$FSREPProvinces->province_id."');\n";
        if ($FSREPProvinces->province_id == $_GET['cvalue']) {
            echo "obj.options[$count].selected = true;";
        }
        $count++;
    }
}


?>

Here is the on-page javascript which is where the console says the error is coming from: 这是页面上的javascript,控制台说错误的来源是:

<script type="text/javascript">
    <?php
            if (isset($_POST['fsrep-search-country']) && isset($_POST['fsrep-search-province'])) {
                echo 'jQuery(document).ready(function ($){getFSREPlist(\''.$_POST['fsrep-search-country'].'\', \'fsrep-search-province\', \'CountryID\', \''.$_POST['fsrep-search-province'].'\'); getFSREPlist(\''.$_POST['fsrep-search-province'].'\', \'fsrep-search-city\', \'ProvinceID\', \''.$_POST['fsrep-search-city'].'\'); request.send(null); });';
            }else {
                if ($CountryID != 0) {
                    $GetCountry = $CountryID;
                    if ($ProvinceID != 0) {
                        $GetProvince = $ProvinceID;
                    }
                    if ($CityID != 0) {
                        $GetCity = $CityID;
                    }

                    echo 'jQuery(document).ready(function ($){getFSREPlist(\''.$GetCountry.'\', \'fsrep-search-province\', \'CountryID\', \''.$GetProvince.'\'); getFSREPlist(\''.$GetProvince.'\', \'fsrep-search-city\', \'ProvinceID\', \''.$GetCity.'\'); request.send(null); });';
                }
            }   
            ?>
    </script> 

And finally the search widget: 最后是搜索小部件:

<?php  
function fsrep_search_widget_init() {
    if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') ) {
        return;
    }
    function fsrep_search_widget($args) {
        global $wpdb,$FSREPconfig,$CityID,$ProvinceID,$CountryID;
        extract($args);
        $options = get_option('fsrep_search_widget');
        $fsrep_title = empty($options['title']) ? 'Search Listings' : $options['title'];
        echo $before_widget;
        echo $before_title;
        echo $fsrep_title;
        echo $after_title;
        echo '<form id="fsrep_search_widget_form" name="fsrep_search_widget_form" action="'.get_option('home').'/listings/search/" method="post">';
        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">Country:</div>';
        echo '<select id="fsrep-search-country" name="fsrep-search-country"  onchange="getFSREPlist(this, \'fsrep-search-province\', \'CountryID\', \'\')">';
        echo '<option value="">Select Country</option>';
        $FSREPCountries = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."fsrep_countries ORDER BY country_name");
        foreach ($FSREPCountries as $FSREPCountries) {
            if ($wpdb->get_var("SELECT listing_address_country FROM ".$wpdb->prefix."fsrep_listings WHERE listing_address_country = ".$FSREPCountries->country_id) > 0) {
                $selected = '';
                if (isset($_POST['fsrep-search-country']) || $CountryID != 0) { 
                    if ($_POST['fsrep-search-country'] == $FSREPCountries->country_id) { 
                        $selected = ' selected'; 
                    }elseif ($CountryID == $FSREPCountries->country_id) { 
                        $selected = ' selected'; 
                    }
                }
                echo '<option value="'.$FSREPCountries->country_id.'"'.$selected.'>'.$FSREPCountries->country_name.'</option>';
            }
        }
        echo '</select></div>';
        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">State/Prov.:</div>';
        echo '<select id="fsrep-search-province" name="fsrep-search-province"  onchange="getFSREPlist(this, \'fsrep-search-city\', \'ProvinceID\', \'\')">';
        echo '<option value="">- - - - - -</option>';
        echo '</select></div>';
        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">City:</div>';
        echo '<select id="fsrep-search-city" name="fsrep-search-city">';
        echo '<option value="">- - - - - -</option>';
        echo '</select></div>';
        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">Price:</div>';
        echo '<select name="fsrep-search-price-range">';
        echo fsrep_price_range_print('options',$_POST['fsrep-search-price-range']);
        echo '</select></div>';
        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">to</div>';
        echo '<select name="fsrep-search-price-range2">';
        echo fsrep_price_range_print('options',$_POST['fsrep-search-price-range2']);
        echo '</select></div>';
        $SFields = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."fsrep_fields WHERE field_search = 1 ORDER BY field_order");
        foreach($SFields as $SFields) {
            $SFieldsValue = '';
            echo '<div class="fsrepws-input"><div class="fsrepws-input-title fsrepwst-'.$SFields->field_id.'">'.$SFields->field_name.'</div>';
            if ($SFields->field_type == 'selectbox') {
                echo '<select name="field-'.$SFields->field_id.'">';
                echo '<option value="">All</option>';
                $Array = explode(',',$SFields->field_value);
                for($i=0;$i<count($Array);$i++) {
                    $selected = '';
                    if (isset($_POST['field-'.$SFields->field_id])) { if ($_POST['field-'.$SFields->field_id] == $Array[$i]) { $selected = ' selected'; } }
                    echo '<option value="'.$Array[$i].'"'.$selected.'>'.$Array[$i].'</option>';
                }
                echo '</select></div>';
            } elseif ($SFields->field_type == 'radio') {
                $selected = ''; if (!isset($_POST['field-'.$SFields->field_id])) { $selected = ' checked'; }
                echo '<br /><label for="wsall"><input type="radio" style="width: 10px;" name="field-'.$SFields->field_id.'" value="" id="wsall"'.$selected.'> All</label>';
                $Array = explode(',',$SFields->field_value);
                for($i=0;$i<count($Array);$i++) {
                    $selected = '';
                    if (isset($_POST['field-'.$SFields->field_id])) { if ($_POST['field-'.$SFields->field_id] == $Array[$i]) { $selected = ' checked'; } }
                    echo '<label for="'.$Array[$i].'"><input type="radio" style="width: 10px;" name="field-'.$SFields->field_id.'" value="'.$Array[$i].'" id="'.$Array[$i].'" '.$selected.'> '.$Array[$i].'</label>';
                }
                echo '</select></div>';
            } elseif ($SFields->field_type == 'checkbox') {
                $selected = ''; if (!isset($_POST['field-'.$SFields->field_id])) { $selected = ' checked'; }
                echo '<br /><input type="checkbox" style="width: 25px;" name="field-'.$SFields->field_id.'" value="" '.$selected.' /> All &nbsp; &nbsp;<br />';
                $Array = explode(',',$SFields->field_value);
                for($i=0;$i<count($Array);$i++) {
                    $selected = '';
                    if (isset($_POST['field-'.$SFields->field_id])) { if ($_POST['field-'.$SFields->field_id] == $Array[$i]) { $selected = ' checked'; } }
                    echo '<input type="checkbox" style="width: 25px;" name="field-'.$SFields->field_id.'-'.$i.'" value="'.$Array[$i].'" '.$selected.' /> '.$Array[$i].' &nbsp; &nbsp;<br />';
                }
                echo '</select></div>';
            } else {
                if (isset($_POST['field-'.$SFields->field_id])) { $SFieldsValue = $_POST['field-'.$SFields->field_id]; }
                echo '<input type="text" name="field-'.$SFields->field_id.'" id="field-'.$SFields->field_id.'" value="'.$SFieldsValue.'" />';
            }
        }


        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">Bedrooms:</div>';
        echo '<select name="fsrep-search-bedrooms">';
        echo '<option value="">All</option>';
                $Array = explode(',',$SFields->field_value);
                for($i=0;$i<10;$i++) {
                    $selectedbed = '';
                    if (isset($_POST['fsrep-search-bedrooms'])) { if ($_POST['fsrep-search-bedrooms'] == $i && $_POST['fsrep-search-bedrooms'] != '') { $selectedbed = ' selected'; } }
                    echo '<option value="'.$i.'"'.$selectedbed.'>'.$i.'+</option>';
                }
                echo '</select></div>';

        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">Bathrooms:</div>';
        echo '<select name="fsrep-search-bathrooms">';
        echo '<option value="">All</option>';
                $Array = explode(',',$SFields->field_value);
                for($i=0;$i<7.5;$i += 0.5) {
                    $selectedbath = '';
                    if (isset($_POST['fsrep-search-bathrooms'])) { if ($_POST['fsrep-search-bathrooms'] == $i && $_POST['fsrep-search-bathrooms'] != '') { $selectedbath = ' selected'; } }
                    echo '<option value="'.$i.'"'.$selectedbath.'>'.$i.'+</option>';
                }
                echo '</select></div>';

        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">Sqft:</div>';
        echo '<select name="fsrep-search-sqft">';
        echo '<option value="">All</option>';
                $Array = explode(',',$SFields->field_value);
                for($i=250;$i<5000;$i += 250) {
                    $selectedsqft = '';
                    if (isset($_POST['fsrep-search-sqft'])) { if ($_POST['fsrep-search-sqft'] == $i && $_POST['fsrep-search-sqft'] != '') { $selectedsqft = ' selected'; } }
                    echo '<option value="'.$i.'"'.$selectedsqft.'>'.$i.'+</option>';
                }
                echo '</select></div>';

        if (isset($_POST['fsrep-search-id'])) { $SFieldsValue = $_POST['fsrep-search-id']; }
        echo '<div class="fsrepws-input"><div class="fsrepws-input-title">Listing#</div><input type="text" name="fsrep-search-id" id="fsrep-search-id" value="'.$SFieldsValue.'" /></div>';


        //echo '<div class="fsrepws-input"><div class="fsrepws-input-title">Listing#</div><input type="text" name="fsrep-search-id" id="fsrep-search-id" value=""></div>';
        echo '<div id="fsrepws-submit"><input type="submit" name="fsrep-search-submit" id="fsrepw-widget-search-submit" value="Search" style="width:127px;font-size:14px" /></div>';




        echo '</form>';
        if ($FSREPconfig['EnableAdvancedSearch'] == 'Yes') {
            echo '<div align="center"><a href="'.get_option('home').'/listings/search/">Advanced Search</a></div>';
        }

        echo $after_widget;
    }
    function fsrep_search_widget_control() {
        $options = get_option('fsrep_search_widget');
        $fsrep_title = htmlspecialchars($options['title'], ENT_QUOTES);
        echo '<div>There are no options for this widget.</div>';
    }
    register_sidebar_widget('FSREP Search Widget', 'fsrep_search_widget');
    register_widget_control('FSREP Search Widget', 'fsrep_search_widget_control');
}
add_action('plugins_loaded', 'fsrep_search_widget_init');
?>

I have been racking my brain on this for over two days trying to figure out what the heck is wrong and I am really hoping it is something easy. 我已经花了超过两天的时间试图弄清楚到底是什么错了,我真的希望这很容易。 You guys would be a life saver if you can help me figure this out. 如果您能帮助我解决这个问题,你们将是一个救命的人。

Thanks, Chris 谢谢,克里斯

Your issue seems to be that request is not defined in the scope. 您的问题似乎是该request未在范围内定义。 Simply changing it over to a connection that is in scope should fix your issue. 只需将其更改为范围内的连接即可解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM