簡體   English   中英

有什么方法可以將單選按鈕列表動態更改為選擇下拉列表?

[英]Any way to change a list of radio buttons to a select drop down dynamically?

我正在嘗試尋找一種動態創建的表單,無論出於何種原因,該表單都不提供選擇列表的選擇,而僅提供單選和檢查輸入。 我沒有辦法修改代碼,所以我很好奇是否可以使用jquery將單選按鈕列表轉換為選擇下拉列表嗎?

例如,如果我有以下代碼:

<form>
   <div class="col-lg-5">     
      <p class="bullet"><b><font class="required" size="3" color="FF0000">*     </font></b></p>
      <p class="inputLabel">First Name:</p>
      <input type="text" size="25" name="Text1" value="">
   </div>
   <div class="col-lg-5">
      <input type="radio" name="gender" value="male">Male<br>
      <input type="radio" name="gender" value="female">Female
   </div>
   <div class="col-lg-10"><p>Current Employer / Facility:</p>
      <input type="text" size="25" name="Text9" value="">
   </div>
</form>

無論如何,將其更改為:

<form>
    <div class="col-lg-5">     
      <p class="bullet"><b><font class="required" size="3" color="FF0000">*     </font></b></p>
      <p class="inputLabel">First Name:</p>
      <input type="text" size="25" name="Text1" value="">
   </div>
    <select name="gender">
       <option value ="male">Male</option>
       <option value ="female">Female</option>
    </select>
   <div class="col-lg-10"><p>Current Employer / Facility:</p>
      <input type="text" size="25" name="Text9" value="">
   </div>
</form>

這是一種方法:

var sel = $('<select name="gender">').append(function () {
    var opts='';
    $('input[name="gender"]').each(function () {
        opts += '<option value ="' + this.value + '">' + this.value.charAt(0).toUpperCase() + this.value.slice(1) + '</option>';
    })
    return opts;
});
$('form div.col-lg-5:eq(1)').empty().append(sel);

jsFiddle示例

var select = $("<select></select>").attr("name", "gender");
$('form input[name="gender"]').each(function(index, item) {
    $('<option/>', {
         'value': this.value,
         'text': this.value
    }).appendTo(select);
});

這個JSFiddle與我能夠得到的差不多

HTML:

<form>
   <input type="radio" name="gender" value="male">Male<br>
   <input type="radio" name="gender" value="female">Female
</form>

使用Javascript:

var select = $('form').append($('<select>', {
    name: 'gender',
    id: 'genderSelect'
}));

$("form > input[type='radio']").each(function() {
    $('#genderSelect').append($('<option>', {
        value: $(this).val(),
        text: $(this).val()
    }));
    $(this).remove();
});

您需要對單選按鈕的標簽做一些事情,以獲取值或更輕松地擺脫它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM