PHP / AJAX / jQuery选择框

时间:2014-05-30 19:42:49

标签: php jquery ajax

在我的运输部分,我有一个国家/州选项。每当用户更改国家/地区(选择)时,我都会使用ajax检查是否有该国家/地区的状态列表。如果有,则会显示下拉状态的下拉列表。如果没有,将显示一个输入框,以便他们可以手动输入其状态。我还有一个"已保存的地址"如果他们有一个保存的地址,将使用ajax自动填充表单的一侧。我遇到国家/州值的问题 - 状态正在国家/地区值之前设置,因此当设置国家/地区值时,它会触发状态刷新,删除值。这是我的代码(我忘记了PHP ajax请求,因为它们正在运行 - 它们只是从数据库中获取数据并返回一个JSON数组):

注意:可以随时访问此页面。如果用户访问此页面,填写并稍后再次访问,则应使用数据库中的相应信息填充表单(即:应显示正确的国家/地区)。

HTML(隐藏输入并最初选择):

<label>State/Province</label>

<input  type="text" id="shipping_state_input" name="data[Order][shipping_state_input]" style="display: none;" <?php if(isset($this->request->data['Order']['shipping_state'])) { echo "value='" . $this->request->data['Order']['shipping_state'] . "'"; } ?>>
<select id="order_shipping_state" name="data[Order][shipping_state]" class="required span6" style="width: 180px; display: none;">

JS:

// Update the country
$('#order_shipping_country').change(function() {
    var country = $(this).val();

    // Get a list of states for that country
    $.getJSON("/states/ajax_getStatesByCountry/"+country, function(data) {
        // If a list is returned, populate the select box
        if(data) {
            $('#shipping_state_select').empty().show().addClass('state_active');
            $('#shipping_state_input').val('').hide().removeClass('state_active');

            $.each(data, function(key, val){
                $('<option/>').attr('value', key).html(val).appendTo('#shipping_state_select');
            });
        } else {
            // Otherwise, show the select box
            $('#shipping_state_select').empty().hide().removeClass('state_active');;
            $('#shipping_state_input').show().addClass('state_active');;
        }
    });
});

// If they click on a previous address
$('.previous_address').change(function() {
    var addr_id = $(this).val();

    if(addr_id != '') {
        // Get the address
        $.getJSON("/UserAddresses/ajax_get_address/" + addr_id,{ajax: 'true'}, function(j) {

            $.each(j, function(key, value){
                // Update state & country with the appropriate values
                // I've harded the array to return 'country' first...

                // .state_active is either attached to the select box or input box
                // the code below is hard coded for the US (I know the US is a select box)

                if(key == 'state') {
                    if($('#order_' + c + '_country').val() == 'US') {   
                        $('.state_active').find('option[value="UT"]').attr('selected', true);
                    } else {
                        $('.state_active').val(value);
                    }
                }

                if(key == 'country') {
                    $('#order_' + c + '_country').val(value).trigger('change'); 
                }
            })
        });

    }
});

0 个答案:

没有答案