2012-02-28 150 views
4

在你-1之前,這是一個如此簡單的問題,因爲我花了一段時間搜索並找不到它。我有什麼是5個選擇框。每個結果取決於之前選擇的內容。沒有提交按鈕。我只需要根據在上一個框中選擇的內容進行更改,到目前爲止我已經擁有了該功能。哦,結果正在從數據庫中提取。問題在於,當您在選項1中選擇一個選項時,會出現框2選項,但當您再次選擇框1中的選項時,它們的選項將疊加在其他選項上。當它再次改變時,我需要他們清除。我會張貼我擁有的js,如果你還需要其他的東西,就問問。使用javascript更改選擇選項

p.s.即時通訊使用php-mysql的選項。 ps.s.s這個網站必須在明天完成,所以即使有點急。請不要浪費時間告訴我這是一個愚蠢的問題,或者不是。

在此先感謝您的幫助。

$(function() { //When the page is finished loading run this code 
    $('#country').change(function() { 
     $.ajax({ 
      url: "<!--Base url taken out-->/discovery/aLoad", 
      success: function (data) { 
       eval(data); 
      }, 
      error: function() { 
       alert('failed'); 
      }, 
      data: { 
       country: getSelectValues('#country') 
      }, 
      type: 'POST' 
     }); 
    }); 
}); 

    function changeSearchBar (newBar) { 
    //remove the crap 
    function ClearOptions(country) 
    { 
    document.getElementById('country').options.length = 0; 
    } 

    for (var i = 0; i <= newBar.length; i++) { 
     newBar[i].id = newBar[i][0]; 
     newBar[i].name = newBar[i][1]; 
     $('#group').append(
      $('<option></option>').attr('value', newBar[i].id).text(newBar[i].name) 
     ); 
    } 
    } 

    function getSelectValues (sId) { 
    var str = ""; 

    $(sId +" option:selected").each(function() { 
     str += $(this).val() + ","; 
    }); 

    return str.replace(/.$/g, ''); 
} 
+0

您的ClearOptions功能看起來很不錯,但我沒有看到它在哪裏調用它。它被定義爲changeSearchBar,但從未被調用。我想如果你在for循環之前調用它,你應該沒問題。 – Zoidberg 2012-02-28 02:49:11

回答

1

從我從你長的帖子理解你只需要開始追加從AJAX請求新的選項之前刪除所有select孩子的。

嘗試這樣的事情你for循環之前:

$('#group').html('');​ 

演示:http://jsfiddle.net/57TYu/2/

+0

這就像你的天才或什麼! :D是的,我知道這是一個很長的帖子。不知道如何澄清它。但是,這是有效的。非常感謝你。 – 2012-02-28 02:53:27

+0

等待,對不起,這擺脫了選擇多個選項 – 2012-02-28 02:54:16

+0

我需要能夠選擇多個並具有與這兩個返回相關聯的所有第二個選項框選項。有任何想法嗎? – 2012-02-28 02:54:55

0

在這裏,你走了,我覺得這基本上就是你正在嘗試做的:

How do you remove all the options of a select box and then add one option and select it with jQuery?

基本上,找到'選項'標籤內t他選擇並移除它們。

$('select').find('option').remove() 

將清除所有的選擇框。

這將追加數據,這是假設在自己的位置的選項:

$('select').find('option').remove().end().append(data); 

我認爲這是你在找什麼。