• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Retrieve value of hidden form field with jQuery

I am incorporating jQuery into my Codeigniter app. I am working on an ajax style login/logout area on the page.

I have been pout a hidden field into the login/logout form. I want to include the value of the field in my ajax request. However, I cannot figure out how to pull out the value using jQuery.

A simple example field is:

<input type="hidden" id="data" value="something">

I have tried this [removed]
var data = $('#data').val();

But, it does not seem work for me.

Should be:

<input type="hidden" id="data" value="something"/>

But other than that it's correct.

Thanks. I have got it working now. I have no idea what I did wrong.

[eluser]Nick Husher[/eluser]
Do you have another element with the id of "data"?

Yes, it looks like it was a problem with multiple forms on the working page.

Once again ... after I post a question .. I stumble on the solution ... and it is always ... embarrasingly dumb.

[eluser]Nick Husher[/eluser]
Suggestion: create code conventions for deriving CSS paths for elements you need to access. The easiest way to do this is to give every form a descriptive and unique ID attribute and then "filter" by that in your jQuery selectors. You can have multiple forms on the same page with the same field name attributes, but you can only (well... should only; having more than one is considered an undefined use case) have one instance of an ID per page.

<form id="log-in-form">
  <input type="hidden" name="hidden-field" value="hidden-login-value" />
<form id="register-form">
  <input type="hidden" name="hidden-field" value="hidden-register-value" />

var getHiddenValue = function(form) {
   return $('#' + form + '-form input[name="hidden-field"]').eq(0).val();

var foo = getHiddenValue('register'); // = 'hidden-register-value';
var bar = getHiddenValue('log-in'); // = 'hidden-login-value';

(Code is untested)

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.