Tuesday, February 14, 2012

Change value JS, PHP getting old value


I've a silly problem.



Depending on a the visibility of a div I want to set a hidden value




if($('#crewMember').is(':visible')) {
$('#visibility').attr('value', 'hidden')
} else {
$('#visibility').attr('value', 'visible')
}



This works. I've checked it via FireBug and I can see that the HTML has changed.



But when I try to get this value after form submission I get the original value, not the changed value.




echo $_POST['visibility']
//returns default value, not the adjusted valueHow come?



How come?



EDIT SOme example code




<html>
<script type="text/javascript">
$(document).ready(function() {

$('#div').click(function() {
$('#visibility').val('hidden');
$('#value').html('hidden value: ' + $('#visibility').val());
});

$('#value').html('hidden value: ' + $('#visibility').val());
});

<body>
<form method="post">
<div id="div">
click this area to change value
</div>

<div id="value"> <!-- This div will show the actual value of the hidden field -->
</div>
<input type="hidden" id="visibility" name="visibility" value="initial value" />
<input type="submit" name="button" value="button" />
</form>
</body>
</html>



When I submit this form the $_POST['visibility'] always contains the string 'initial value'. Even when I changed the value with JS to 'hidden';

2 comments:

  1. As ManseUK said, Change $("").attr('value',...) to $("").val(...) (see the jQuery documentation for .val)

    But to answer the question as to why, you need to understand how DOM objects work in JavaScript. For every element (div, p, a, img, form, input, whatever...) every single element is an object in the DOM.

    Here's the important part: the element has a value, but also each attribute has a value. In jQuery, when you use .attr('value',...), what you are really doing is creating an attribute with the name of 'value'. But this does NOT change the element value, which stays the same.

    In firebug, it will read the JavaScript attributes and layer it on top of the element, which explains why it showed up that way in firebug. However, when it comes time to submit the data to the server, the browser will NOT submit the attribute values - only the element's value (which has not changed). But using .val() will change the element value, which is what will be submitted to the server.

    Perhaps this will make more sense in raw JavaScript, instead of jQuery:

    the equivalent of .attr() is: element.setAttribute("value","...");

    the equivalent of .val() is: element.value = "...";

    Do you see the difference? In .attr() you never changed the value, only the attribute.

    ReplyDelete
  2. Try using val() instead (im assuming your visibility element is an input element):

    if($('#crewMember').is(':visible')) {
    $('#visibility').val('hidden');
    } else {
    $('#visibility').val('visible');
    }

    ReplyDelete