-1

I am working with jsp. I want to set a value from JavaScript to HTML hidden type input in order to pass the value to another page.

This is my HTML code:

<form id="reg" method="post" action="/questionnaire.jsp">
    <input type="hidden" name="userId" value="123"> 
    <button id="submit" name="sr-buttobmitun">Submit</button>
</form> 

JavaScript is like:

<script>
    var userId = "123";
</script>
masud_moni
  • 969
  • 14
  • 29
Ilham
  • 33
  • 1
  • 5

1 Answers1

0

If you give the hidden input an id, you can then query the DOM for that element and set the value, like so:

document.getElementById('userid').value = '123';

AHB
  • 548
  • 2
  • 6
  • `userid` will be `userId`. isn't it? – Ataur Rahman Munna Jun 11 '17 at 09:10
  • That would depend on what id is given to the input field. It is best practice to keep the ids/classnames of elements lowercase, which is why I just put userid. – AHB Jun 11 '17 at 09:13
  • do i need to keep the default value as empty in html input type? – Ilham Jun 11 '17 at 09:14
  • But the original OP asked for `` not for `userid`. – Ataur Rahman Munna Jun 11 '17 at 09:14
  • You don't need to, you can have provide a default value if you wish, but it will be overridden when this piece of javascript executes. – AHB Jun 11 '17 at 09:15
  • Yes the user gave a field with a name of userId, but the DOM retrieval for name returns a NodeList, which seemed overly complicated for this example. The difficulties of using the name to query the element is that then you need to iterate through the NodeList to ensure that you are going to mutate the correct value. By having the OP add an `id` attribute to the element, you can query for just that element because ids are unique. Yes the OP can put the id as 'userId' if they wish, but as I said that isn't the preferred way of naming ids. – AHB Jun 11 '17 at 09:16
  • How ever it is not work for me while I print the hidden value in the page questionnaire.jsp what could be the problem? – Ilham Jun 11 '17 at 09:24
  • `` have you changed your input field to this? – AHB Jun 11 '17 at 09:25
  • yes. it is not working even after this change – Ilham Jun 11 '17 at 09:31
  • sorry. i have tried with 'userid' not with 'userId' so had not worked. now ok. thank you so much. – Ilham Jun 11 '17 at 09:35