2012-08-23 177 views
1

我創建了這個在的jsfiddle http://jsfiddle.net/MZtML/只允許一個有一定的價值選擇選項來選擇

我有圖像的行一個選擇框,以確定它是什麼類型的圖像。這些選項:

<select name="image-type"> 
    <option value="none">Select Image Type</option> 
    <option value="small-thumbnail">Small Thumbnail (70x50)</option> 
    <option value="thumbnail" selected="selected">Thumbnail (140x100)</option> 
    <option value="feature">Feature</option> 
    <option value="gallery">Gallery</option> 
</select> 

現在,當有圖像的幾行,我只想用一個行被指定爲特徵。如果另一行當前設置爲「功能」,則應重置爲「選擇圖像類型」。與小縮略圖和縮略圖相同。

可以將多個圖像設置爲選擇圖像類型和圖庫。

我一直在使用jQuery的遵循嘗試:

$('#image_container').on('change', '[name="image-type"]', function() { 
    $this = $(this); 

    $('[name="image-type"]').not($this).each(function() { 
     if ($(this).val() === 'feature') { 
      $(this).val('none'); 
     } 
    }); 
}); 

我試過的這幾個變化,我已經得到接近,但沒有我嘗試似乎準確地做到這一點。有人可以幫我嗎?

回答

3

updated jsFiddle DEMO

幾件事情:

你有容器區域錯的小提琴,你需要:#image_library。此外,如果您想要選擇的選項的值,您需要:$(this).find('option:selected').val()

$('#image_library').on('change', '[name="image-type"]', function() { 
    var $this = $(this), 
     _current = $(this).find('option:selected').val(); // save current val 

    // we're only allowing 'gallery' to have multiple 

    if (_current !== 'gallery') { 

     // loop through all selects to remove any matching values 
     $('[name="image-type"]').not($this).each(function() { 

      if ($(this).find('option:selected').val() === _current) { 
       $(this).val(''); 
      } 
     }); 
    } 
}); 

+0

其實我試過這樣的事情之前和在此的jsfiddle得到了同樣的問題。將其中一個選項設置爲功能,然後選擇另一個作爲小縮略圖。它將重置功能一以選擇圖像類型。我無法弄清楚爲什麼這樣做。 – Motive

+0

剛更新了!完全忘記確保當前的一個是「精選」,然後再循環並刪除其他任何擁有它的人。固定:) –

+0

這一個應該被標記爲答案,因爲它符合所有的要求,而我錯過了畫廊需求。 –

2

jsFiddle

大廈關閉@mcpDESIGNS做工精細,我刪除了硬編碼"feature"值,而是得到了當前所選選項的值。然後您可以遍歷其他下拉菜單並相應地進行比較。

請注意,如果沒有var關鍵字,則您的$this變量的作用域爲全局。

$('#image_library').on('change', '[name="image-type"]', function() { 
    // without the var, you're creating a global variable $this... 
    var $this = $(this), 
     thisValue = $this.find('option:selected').val(); 

    // using find() with an id context is faster 
    $('#image_library').find('[name="image-type"]').not($this).each(function() { 
     //console.log($(this).find('option:selected').val()); 
     if ($(this).find('option:selected').val() === thisValue) { 
      $(this).val(''); 
     } 
    }); 
}); 

+0

+1非常真實!沒有注意到他想讓他們中的任何一個匹配。我也更新了這個...除了Gallery外,沒有任何東西可以超過1 –