Javascript – how to pass a value to a hidden field using jquery

javascriptjqueryjquery-selectors

<input type="hidden" id="name" name="hidden-new-field"/>
<form>
<input type="text" id="name-emails" />
<input id="send-btn" type="submit" class="button" value="SEND NOW" />
</form>

On button click I want to give the value of input type text to the value of hidden type

Best Answer

There are few mistakes in your form

  • there is no name attribute on input type text
  • id of Hidden element should not be name (leading confusion)
  • Hidden field should be inside form tag

i would prefer like this

PHP

<form>
<input type="text" id="email"  name="email"/>
<input type="hidden" id="hidden_email" name="hidden_email"/>
<input type="submit" id="send_btn"  class="button" value="SEND NOW" />
</form>

jQuery

$("form").bind('submit',function(e){
  e.preventDefault();
  var formEmail=$("input[name=email]").val();
  $("input[type=hidden][name=hidden_email]").val(formEmail);     
});

DEMO