Setting form values in jQuery

16 Apr

UPDATE: most people are coming to this post to find out how to set form values in jQuery, so here is the quick version.

Basically you need to use the .val() function to set form values for input elements in jQuery.

     // Get value from a HTML element's attribute
     var idval = $(this).attr("id");
     // Set the value of a form input element

For my assignment in “Visual Databases”, one of my projects involved having a hidden form value set using Javascript. The value would be set to the id of the div when the mouse moved over one of the div elements.

Since I was using jQuery, I looked around for some code that would enable me to do this using jQuery, and this was the result:

Javascript (in <head>):

   // other functions
   $("").mouseover(function() {
     var idval = $(this).attr("id");

What the above code does is : for a mouseover on a, it sets the background color, and then gets the “id” attribute of that div – and sets the form value (input#pcompid) to that value.

HTML in body:

<form action="">
<input type="hidden" id="pcompid" name="pcompid" value="">
<input type="submit" value="Compare">

<div class='photo' id='2419405422'>
<a href="morephotos.php?photoid=2419405422">
<img border='0'>

2 Responses to “Setting form values in jQuery”

  1. pfwd June 30, 2009 at 12:49 pm #

    Thanks. Just what I needed

  2. gogrumogru February 12, 2010 at 4:07 pm #

    good code!

Leave a Reply to pfwd Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: