borie88 borie88 - 2 months ago 5x
HTML Question

Jquery one button updates multiple input fields on form

I am trying to update two input fields in a form when clicking one button. I actually had all the code right when using document.getElementById, but the form that I'm using strips the ID's I set away, so I can't use getbyid. If I know the form field name, how could I change my function to do the same thing? Please note that my form has more than two fields, including a submit button, so I don't want to update those.

This is what I used before (with the ID selector)

<input type="text" name="field-1" id="info1">
<input type="text" name="field" id="info2">
<a href="#" onclick="addTxt(['value1','value2'],'info','2')">Populate</a>


function addTxt(val, id,no)
var id = id;
for(var i=1;i<=no;i++){
document.getElementById(id+i).value = val[i-1];




Edited with a much simpler and readable approach

function addVal(obj) {
  event.preventDefault(); // Prevent page scrolltop on anchor click
  $.each(obj, function(k, v) {
    $("input[name='"+ k +"']").val( v );
<script src=""></script>

<input type="text" name="foo">
<input type="text" name="bar">   

<a  href="#" onclick='addVal({foo:"Hello", bar:"World"})'>Populate</a>

Or with native JS:

function addVal(obj) {
  Object.keys(obj).forEach(function(name) {
    document.querySelector('input[name="' + name + '"]').value = obj[name];    
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="name-with-dashes">   

<a  href="#" onclick='addVal({foo:"Hello", bar:"World", "name-with-dashes": "Works !"})'>Populate</a>