Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the value of a input hidden field through JavaScript?

I am trying to call the resetyear function and it's getting called also, but the flow stops at alert("over"). It doesn't transfer its control to resetmaster.

    String flag = "";     flag = (String) session.getAttribute("flag");     System.out.println("flag = " + flag);     if (flag == null) {         flag = "";     }     if (flag.equals("yes")) { %>    <script>        alert(1);   // resetyear();     dontreset();     //document.getElementById("checkyear").value = "1";     //alert(document.getElementById("checkyear").value);      </script> <%} else if(flag.equals("no"))     {%> <script>     alert(2);     //document.getElementById("checkyear").value = "2";     //alert(document.getElementById("checkyear").value);     resetyear(); </script> <%}else{}%>   function resetyear(){  if(confirm("DO YOU WANT TO RESET THE YEAR?")) {     alert("hello");     //document.forms['indexform'].action = "resetmaster";     //alert(document.forms['indexform'].action);     //document.forms['indexform'].submit();       alert("over");     form.action = "resetmaster";     form.submit();     alert(1); } 
like image 733
Divyang Avatar asked Oct 07 '13 19:10

Divyang


People also ask

What attribute should be used for a hidden value?

Definition and Usage The hidden attribute is a boolean attribute. When present, it specifies that an element is not yet, or is no longer, relevant.

How get Boolean from hidden field in jQuery?

How do you toggle a hidden field's true/false value using jquery? $('#myDiv'). on('click'), (function() { var hiddenField = $('#myHiddenField'), val = hiddenField. val(); hiddenField.

How can store hidden field value in jQuery?

In jQuery to set a hidden field value, we use . val() method. The jQuery . val() method is used to get or set the values of form elements such as input, select, textarea.


2 Answers

For me it works:

document.getElementById("checkyear").value = "1"; alert(document.getElementById("checkyear").value); 

http://jsfiddle.net/zKNqg/

Maybe your JS is not executed and you need to add a function() {} around it all.

like image 143
almo Avatar answered Sep 24 '22 12:09

almo


You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value=""> to the beginning.

like image 32
Matt H Avatar answered Sep 22 '22 12:09

Matt H