CodeIgniter Forums

Full Version: Retrieve value of hidden form field with jQuery
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]clancey[/eluser]
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:

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

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

But, it does not seem work for me.

El Forum

[eluser]danmontgomery[/eluser]
Should be:

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

But other than that it's correct.

El Forum

[eluser]clancey[/eluser]
Thanks. I have got it working now. I have no idea what I did wrong.

El Forum

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

El Forum

[eluser]clancey[/eluser]
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.

El Forum

[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.

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

[jquery]
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';
[/jquery]

(Code is untested)