我只使用JavaScript和HTML構建表單(業務需求 - 無服務器訪問)。我有一個我需要的值的文本框列表。用戶具有填寫1個文本框,或儘可能多的選擇,因爲他們需要高達35.我可以爲每個單獨的盒子如何捕獲每個文本框的值(僅限JavaScript)並顯示它們?
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
if (a != '' && b != '' && c != '') {
var abc = "this is a: " + a + "this is b: " + b + "and this is c:" + c;
}
創建一個功能,我可以做一個函數爲每個值的每個場景:
if(a != '' && b != '' && c == '') {
var ab = "this is a: " + a + " and b: " + b + "but not c";
}
if(a != '' && b == '' && c != '') {
var ac = "this is a: " + a + " and c: " + c + "but not b";
}
if(a != '' && b == '' && c == '') {
var a-only = "this is a: " + a + " but not b or c";
}
if(a == '' && b != '' && c != '') {
var bc = "this is b: " + b + " and c: " + c + " but not a";
}
這甚至不是僅僅3個變量的所有情況,但我可能有我需要爲每個場景的函數,而時間和空間大塊多達35個不同的變量,我想其中大約10人之後,如果我需要更多的話,它會變得太亂並且很難維護。
我覺得必須有一種更有效的方法來捕獲這些值,並且如果它們不是空的而不是通過每種可能的方案。
我的文本框動態點擊 「添加更多」 按鈕
的JavaScript創建:
var max_fields = 35;
var x = 0;
$('#add').click(function(e) {
e.preventDefault();
if(x < max_fields){
x++;
var inps = $('#wrapper >div:last').data('count')+1 || 1;
$('#wrapper').append('<div class="date-time-list" data-count="'+inps+'"><input type="text" name="date_count' + inps + '" id="date_count'+inps+'" class="inp"/><input type="text" name="time_count' + inps + '" id="time_count'+inps+'" class="inp"/><a class=remove>Remove</a><br><br></div>');
}
});
$('#wrapper').on('click' , 'a.remove' ,function(){
var inps = $('#wrapper > div:last').data('count')-1 || 1;
x--;
$(this).closest('div').remove();
});
HTML:
<tr class="list" style="line-height:1em;">
<td>
Please fill in the dates and times
</td>
<td>
<strong>Dates</strong> <strong>Times</strong>
</td>
</tr>
<tr class="list" style="line-height:1em;">
<td>
</td>
<td>
<span id="wrapper">
</span>
</td>
</tr>
<tr class="list">
<td>
</td>
<td>
<button id="add">Add More</button>
</td>
</tr>
您可以發佈您的textboxs的例子嗎?文本框是靜態的還是動態創建的? – Cory
它們是動態創建的。評論中沒有足夠的空間,所以我將其添加到原始問題 – Matt
我改編了我的答案,完全符合您的使用案例。應該立即開箱即用。 –