views:

131

answers:

3

A simplified version of problem I am experiencing:

Here is my HTML form:

<form enctype="multipart/form-data" method="post" action="/controller/action">
<input type="text" name="title" id="title" value="" class="input-text" />
<input type="hidden" name="hidden_field" value="" id="hidden_field" />
<input type="submit" name="submit_form" id="submit_form" value="Save" class="input-submit" />
</form>

Here is the JavaScript:

$(document).ready(function() {    
    $('#submit_form').hover(function() {
        $('#hidden_field').attr('value') = 'abcd';
    });
});

And here is a really short version of the PHP backend:

if (isset($_POST)) {
    var_dump($_POST);
}

What I do is I hover the #submit_form button for a few seconds just to make sure that the jQuery code got executed, then I submit the form and:

  • the $_POST['hidden_field'] is empty!

Why is that? It should contain 'abcd' as I insert it into the hidden field with jQuery on the hover event.

+3  A: 

Correct way to set the value:

 $('#hidden_field').val('abcd');

Reference: http://docs.jquery.com/Attributes/val

meder
it's still empty even when I use $('#hidden_field').val('abcd'); :(
Richard Knop
@Knop, Are you sure your hover handler is being called?
strager
Sorry that was just my typo it works :)
Richard Knop
+3  A: 

The statement

$('#hidden_field').attr('value') = 'abcd';

is incorrect. You should get an error there as you're assigning an rvalue (the jQuery object) to another rvalue (a string). (The assignment operator needs an lvalue (e.g. a variable) on the left.)

You probably want:

$('#hidden_field').val('abcd');

or:

$('#hidden_field').attr('value', 'abcd');

(The former is more jQuery-ish, but for this case both are equivilent.)

strager
+1  A: 

it is:

$('#hidden_field').attr('value','abcd');
TheVillageIdiot