简体   繁体   English

从输入的html表单到javascript对象收集所有值

[英]Collect all value from input html form to object of javascript

Normally if I add a new input tag I also have to add in Javascript. 通常,如果添加新的输入标签,则还必须添加Javascript。

I try to collect all value from input tag, So how to pass value into an object by loop use tag input name to be object key name also. 我尝试从输入标签中收集所有值,因此如何通过循环将值传递到对象中也使用标签输入名作为对象键名。

Try to use for count 尝试计数

document.getElementById("form1").elements.length

seem it collected the button tag also, how to void it 似乎它也收集了按钮标签,如何使其无效

<form name="form1">
 <input type="text" name="value1">
 <input type="text" name="value2">
 <input type="text" name="value3">
 <input type="text" name="value4">

 <input type="button" id="save" onClick="fc1()" value="Save">
</form>


for(i=0;......)
{
    obj.value+'i' =  document.forms["form1"]["value"+ (i+1)].value;
}

Same result as this.


function fc1(){

   this.value1 = document.forms["form1"]["value1"].value;
   this.value2 = document.forms["form1"]["value2"].value;
   this.value3 = document.forms["form1"]["value3"].value;
   this.value4 = document.forms["form1"]["value4"].value;


   const obj = {
      "value1": this.value1,
      "value2": this.value2,
      "value3": this.value3,
      "value4": this.value4
   };

} 

I usually grab inputs by their ID or class: 我通常按​​他们的ID或班级获取输入:

<input type="text" id="value1">

then grab the value: 然后获取值:

const value1 = document.getElementById('value1').value

to cut down on code, maybe throw it in an array: 减少代码,也许将其放入数组中:

const valueArray = [value1, value2, value3]

then you can do something like this: 那么您可以执行以下操作:

const allValues = {}

valueArray.forEach((value, index) => {
  allValues[`value${index + 1}`] = value
})

now when you log allValues you should have what you want. 现在,当您记录allValues您应该拥有所需的内容。 Note, I am using some es6. 注意,我正在使用一些es6。

What about this ? 那这个呢 ?

var obj = {};
 var form = document.getElementById("form1");
    form.children.forEach(function(elm){
    if(elm.type === 'text'){
        obj[elm.name] = elm.value;
      }
  });
  console.log(obj);

try giving same 'class' or 'name' attribute to the text fields. 尝试为文本字段赋予相同的“类”或“名称”属性。 try var x = document.getElementsByClassName("example"); 试试var x = document.getElementsByClassName("example");

which gives you the list of all elements with the class name as "example'. Then you can loop around based on the length of x. 这会为您提供所有类别名称为“ example”的元素的列表,然后您可以根据x的长度进行循环。

References: 参考文献:

https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

document.querySelectorAll is made for this. 为此创建了document.querySelectorAll

document.querySelectorAll("form[name='form1'] input[type='text']")

will return all input fields of type text in form1 as HTML nodes. 将返回form1 text类型的所有输入字段作为HTML节点。

let elements = document.querySelectorAll("form[name='form1'] input[type='text']");

elements.forEach(e => console.log(e.value));

...logs the values of the input fields. ...记录输入字段的值。 Don't make things harder on yourself by hard coding classes or ID's, and this will allow you to target the input elements you need without additional checks or without fetching every input on the page. 不必通过对类或ID进行硬编码来使事情变得更艰难,这将使您能够定位所需的输入元素,而无需进行额外的检查或获取页面上的每个输入。

Example: 例:

 const values = {}; document.querySelectorAll("form[name='form1'] input[type='text']").forEach(element => values[element.name] = element.value); console.log(values); 
 <form name="form1"> <input type="text" name="value1" value=1> <input type="text" name="value2" value=2> <input type="text" name="value3" value=3> <input type="text" name="value4" value=4> <input type="button" id="save" onclick="fc1()" value="Save"> </form> 

This is an alternative solution done with jQuery. 这是使用jQuery完成的替代解决方案。

Hope this is what you were looking for. 希望这就是您想要的。 Happy to explain or help in a better solution if needed. 如果需要,很高兴为您解释或提供更好的解决方案。

 //jQuery solution const obj = {} $('#save').click(function(e){ var form = $(this).parent(); var inputs = form.children().not(':input[type=button]'); $.each( inputs, function(){ obj[$(this).attr('name')] = $(this).val(); }); console.log(obj); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2>jQuery solution</h2> <form name="form1"> <input type="text" name="value1"> <input type="text" name="value2"> <input type="text" name="value3"> <input type="text" name="value4"> <input type="button" id="save" value="Save"> </form> 

JS Solution JS解决方案

 //JS Solution const objs = {} var button = document.getElementById('savejs'); var form = document.getElementById('formjs'); var element = {}; button.addEventListener('click', function(){ inputs = form.children; for(i=0; i < inputs.length; i++){ if(inputs[i].name != ""){ objs[inputs[i].name] = inputs[i].value; } } console.log(objs); }) 
 <h2>JS solution</h2> <form name="form1" id='formjs'> <input type="text" name="value1"> <input type="text" name="value2"> <input type="text" name="value3"> <input type="text" name="value4"> <input type="button" id="savejs" value="Save"> </form> 

try this: 尝试这个:

 var input = document.forms[0].querySelectorAll('input[type=text]'); var result = Array.from(input).reduce((r, ele) => { r[ele.name] = ele.value; return r; }, {}); console.log(result); 
 <form name="form1"> <input type="text" name="value1" value=1> <input type="text" name="value2" value=2> <input type="text" name="value3" value=3> <input type="text" name="value4" value=4> <input type="button" id="save" onclick="fc1()" value="Save"> </form> 

If you used something like .. I think it will work. 如果您使用类似..的方法,我认为它会起作用。 :) :)

var myObj = {};
var elems = document.getElementsByTagName('input'), i;
for (i in elems) {
    myObj[value + i] = myObj[i].value;
}

return from getElementsByTagName is an array of all matching tags. 从getElementsByTagName返回的是所有匹配标签的数组。 there are some wizard answers in here ha. 在这里有一些向导的答案。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM