通过在JQuery中dynamic添加/删除input字段来获取Javascript值
我在这里链接这里
我怎样才能从所有的文本框中的值到我的javascript窗体中的数组? 我试图把它embedded到一个表格中; 然而,我不能得到的HTML标识,因为它不断变化,当我添加/删除jQuery文本框字段
HTML
<div class="input_fields_wrap"> <button class="add_field_button">Add More Fields</button> <div><input type="text" name="mytext[]"></div> </div>
使用Javascript
$(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = 1; //initlal text box count $(add_button).click(function(e){ //on add input button click e.preventDefault(); if(x < max_fields){ //max input box allowed x++; //text box increment $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box } }); $(wrapper).on("click",".remove_field", function(e){ //user click on remove text e.preventDefault(); $(this).parent('div').remove(); x--; }) });
根据名称获取您的价值。
例如:
$('input[name^="mytext"]').each(function() { alert($(this).val()); });
您可以使用select器".input_fields_wrap input[name='mytext[]']"
来获取传递给document.querySelectorAll()
和Array.from()
name
属性设置为"mytext[]"
所有dynamic<input>
或者jQuery()
和$.map()
来创build具有相同值的数组
let values = Array.from( document .querySelectorAll(".input_fields_wrap input[name='mytext[]']") , ({value}) => value); console.log(values);
<div class="input_fields_wrap"> <button class="add_field_button">Add More Fields</button> <div><input type="text" name="mytext[]" value="0"></div> </div> <div class="input_fields_wrap"> <button class="add_field_button">Add More Fields</button> <div><input type="text" name="mytext[]" value="1"></div> </div> <div class="input_fields_wrap"> <button class="add_field_button">Add More Fields</button> <div><input type="text" name="mytext[]" value="2"></div> </div>