Rahul Chawla Rahul Chawla - 5 months ago 10
HTML Question

Adding argument to form action using input type hidden

How to add arguments in a form action using input type="hidden".
My HTML snippet...

<form id="form1">
<input type="text" name="txt"/>
<input type="hidden" name="usID" value=123/>
<input type="hidden" name="usname" value="name1"/>
<input type="submit" onclick="add()" value="ADD"/>
</form>


My JavaScript snippet...

function add()
{
document.getElementsByName('usID').value=789;
document.getElementsByName('usname').value="name2";

document.getElementById('form1').action = "/page";
document.getElementById('form1').submit();
}


After entering "text" in the textbox and pressing ADD, the link looks like this...
http://localhost:3000/page?txt=text&usID=123&usname=name1

Why hasn't the usID and usname changed to 789 and "name2" respectively?
Any other alternative if not this?

Answer

getElementsByName is going to return a collection of html elements (NodeList), not a single html element. meaning the return value doesnt have a value attribute that will change the input. you need to either give them an id and find them with getElementById and then change the value, or grab the first element of your collection

document.getElementsByName('usname')[0].value="name2";

or (preferred way)

<input type="hidden" name="usname" value="name1" id="usname"/>

function add(){
  document.getElementById('usname').value="name2";
  ...
}

though i have to ask, is there a reason you're changing the hidden field element like this?

Comments