0

スクリプト (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());
        });
    }
});
4

2 に答える 2

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

ドロップダウンを生成したら、このスニペットを実行して各select要素を確認できます。

デモ: http://jsfiddle.net/kqunE/

于 2013-03-21T10:27:32.267 に答える
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()

于 2013-03-21T10:29:08.993 に答える