[英]Get Javascript value from Dynamically adding/removing input fields in JQuery
我在這里關注此鏈接
如何將所有文本框中的值放入JavaScript表單的數組中? 我試圖將其嵌套為一種形式。 但是,我無法獲取HTML ID,因為當我添加/刪除jQuery文本框字段時,它會不斷變化
HTML
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Java腳本
$(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());
});
您可以使用選擇器".input_fields_wrap input[name='mytext[]']"
來獲取將name
屬性設置為"mytext[]"
所有動態<input>
元素傳遞給document.querySelectorAll()
和Array.from()
或或者jQuery()
和$.map()
創建具有相同值的數組
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>
let values = $.map($(".input_fields_wrap input[name='mytext[]']") , ({value}) => value); console.log(values);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.