2013-03-21 29 views
0

我正在通過腳本(Smarty)動態生成下拉列表。HTML,顯示標籤如果下拉只有一個值

如果下拉菜單中只有一個選項值,是否可以將其顯示爲標籤。

這將顯示一個包含3個值的下拉菜單。

<select> 
    <option> 1 </option> 
    <option> 2 </option> 
    <option> 3 </option> 
</select> 

如果它顯示然後只是一個值顯示爲標籤,是能夠以兩者的純HTML或Jquery的或組合?我可以使用smarty來檢查值並拋出不同的html,但這會讓我的代碼長久,因爲我有很多下拉菜單。

<select> 
    <option> 1 </option> 
</select> 

任何簡單的邏輯,我可能會失蹤?

UPDATE(解決)

感謝所有誰幫助stackoverflow'ers。 我使用@ahren給出的代碼,根據需要工作。

您已經生成您的下拉菜單後,但是我已經擴大代碼一個標籤的屬性複製到另一個,萬一要是有人找

// To replace a <select>, with <label> tag if it has just one value 
$('select').each(function(){ 
    if($(this).find('option').length === 1){ 

     // Copy all attributes from a given tag and save it in a variable. 
     var attributes_from = $(this).prop("attributes"); 
     var attributes_to = ''; 
     $.each(attributes_from, function() { 
      attributes_to += ' '+this.name+'="'+this.value+'"'; 
     }); 

     // If select then copy its value from option. 
     attributes_to += ' value="'+$(this).find('option').attr('value')+'"'; 

     // Replace the <tag> 
     $(this).replaceWith(function(){ 
      return $('<label '+attributes_to+' />').html($(this).text()); 
     }); 
    } 
}); 

回答

3
$('select').each(function(){ 
    if($(this).find('option').length === 1){ 
    $(this).replaceWith(function(){ 
     return $('<label />').html($(this).text()); 
    }); 
    } 
}); 

,你可以運行這個snippet檢查每個select元素。

DEMO:http://jsfiddle.net/kqunE/

+0

非常感謝這麼一個小巧而智能的功能,在這7行代碼中一直在摸索着我的頭腦。 – 2013-03-21 14:31:32

1

我會遍歷每個<select>元素,檢查他們有期權數量,並進行必要的DOM相應改變:

$('select').each(function(index, select) { 
    var numOptions = $('option', this).length; 
    if(numOptions === 1) { 
     // replace the select element here - something like the below 
     var label = $('<label>').html(this.value); 
     $(this).after(label).hide(); 
    } 
}); 

我選擇了隱瞞,而不是替換<select>元素,這樣您仍然可以將值作爲表單的一部分發回。如果不需要,那麼您可以使用.remove()代替.hide()完全刪除元素。

+0

嗨,@Anthony感謝您的幫助,並沒有測試過您的代碼,但它似乎遵循與(at)ahren代碼相同的邏輯步驟,它應該可以工作。 – 2013-03-21 14:53:48