2013-03-21 58 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