2014-01-17 89 views
0

可以使用選項內的按鈕或鏈接創建選擇輸入?我想用它來列出一些值,並在選項中使用一個按鈕來創建「創建值」。我不知道這是否可能。我用href嘗試過,但將其視爲文本。使用選項中的按鈕創建選擇輸入

這將是理想的方案:

<select name="things"> 
    <option value="1">Thing One</option> 
    <option value="2">Thing Two</option> 
    <option value="3">Thing Three</option> 
    <option value=""><button>New Thing</button></option> 
</select> 

我有搜索,但沒有運氣。有人知道一個jQuery插件或類似的工作?

+0

不,你不能把任何HTML放在'option'元素中,*只是* text。你需要使用一個list元素來模擬'select',*或*在'select'元素上使用一個變化處理器。 –

回答

5

這裏有一個簡單的實現:

$('select[name=things]').change(function() { 
    if ($(this).val() == '') 
    { 
     var newThing = prompt('Enter a name for the new thing:'); 
     var newValue = $('option', this).length; 
     $('<option>') 
      .text(newThing) 
      .attr('value', newValue) 
      .insertBefore($('option[value=]', this)); 
     $(this).val(newValue); 
    } 
}); 

當然,這可以做的更好,更乾淨,但它的一個開始。

Demonstration


閱讀您的意見後,似乎你只是想將用戶重定向到另一種形式,當他們選擇一個給定的選項。在這種情況下,你可以簡單地這樣做:

$('select[name=things]').change(function() { 
    if ($(this).val() == '') 
    { 
     window.location.href = 'CreateThingForm'; // Replace with the actual URL 
    } 
}); 
1

你不應該這樣做,不要把按鈕放在選項內。

另外,您可以:

<select name="things" onchange="checkAndAddOption(this)"> 

<select name="things" onclick="checkAndAddOption(this)"> 
. 
. 
. 
</select> 
<script> 
function checkAndAddOption(selectElement) { 
    if (selectElement.value === "") { 
     var opt = document.createElement('option'); 
     opt.value = 'newVal'; 
     opt.innerHTML = 'textToDisplay'; 
     selectElement.appendChild(opt); 
    } 
} 
</script> 
+0

我不想這樣做,我需要的是將用戶重定向到「Create Thing Form」,當他們點擊選擇內的鏈接或按鈕時。 – arielcr

+1

然後,只需將代碼更改爲location.href ='url-of-form' – Shehabix

相關問題