スクリプト (Smarty) によってドロップダウンを動的に生成しています。
ドロップダウンにオプション値が 1 つしかない場合、それをラベルとして表示することはできますか?
これにより、3 つの値を含むドロップダウンが表示されます。
<select>
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
</select>
値が 1 つだけ表示される場合は、それをラベルとして表示します。純粋な HTML や Jquery、または両方の組み合わせで可能ですか? smarty を使用して値をチェックし、さまざまな html をスローすることもできますが、多くのドロップダウンがあるため、コードが長くなります。
<select>
<option> 1 </option>
</select>
私が見逃しているかもしれない簡単なロジックはありますか?
更新 (解決済み)
助けてくれたすべての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());
});
}
});