我只使用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
我改编了我的答案,完全符合您的使用案例。应该立即开箱即用。 –