CodeIgniter Forums
Retrieve value of hidden form field with jQuery - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Retrieve value of hidden form field with jQuery (/showthread.php?tid=28453)



Retrieve value of hidden form field with jQuery - El Forum - 03-11-2010

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


Retrieve value of hidden form field with jQuery - El Forum - 03-11-2010

[eluser]danmontgomery[/eluser]
Should be:

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

But other than that it's correct.


Retrieve value of hidden form field with jQuery - El Forum - 03-11-2010

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


Retrieve value of hidden form field with jQuery - El Forum - 03-11-2010

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


Retrieve value of hidden form field with jQuery - El Forum - 03-11-2010

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


Retrieve value of hidden form field with jQuery - El Forum - 03-11-2010

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