Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery val() inside display: none

Tags:

<a href="#addFriend" rel="facebox" title="[+] add <?php echo $showU["full_name"]; ?> as friend">     <div class="addFriend"></div></A>  <div id="addFriend" style="display:none; margin: auto;">     <form action="javascript:DoFriendRequest()" method="post">         <input name="commentFriend" type="text" id="commentFriend" value="" size="22">          <input name="submit" type="submit" id="submit" value="Send">     </form> </div> 

My form when it's inside this element which is a jquery lightbox, the field #commentFriend get empty value in DoFriendRequest

function DoFriendRequest() {     var wrapperId = '#insert_svar';     $.ajax({          type: "POST",         url: "misc/AddFriendRequest.php",         data: {             mode: 'ajax',             comment : $('#commentFriend').val()          },         success: function(msg) {             $(wrapperId).prepend(msg);             $('#commentFriend').val("");         }     }); } 

Updated answer

But when I remove the display:none, it works. How can I solve this?

like image 566
Karem Avatar asked Aug 21 '10 10:08

Karem


2 Answers

For fields with display:none, it seems that val() does not work.

I bypass this behavior with attr():

$('input').attr('value',myNewValue); 
like image 147
Yako Avatar answered Nov 10 '22 01:11

Yako


There are three ways you can go about this;

  1. Make the element visible, update it, then hide it again.

  2. detach() the element from the DOM, make it visible, update it, hide it, and then re-insert into the DOM.

  3. clone() the element, make it visible, update it, hide it, insert it into the DOM and remove the original element.

Approach #2 and #3 are probably your best options, since these won't trigger a re-draw. All operations are done to the elements "outside" of the DOM (in memory, if you will). This way your UI wont jump/skitter/shift.


Approach #3:

$(function () {     var e = $("...");     var c = e.clone();      c.show();     c.html("...");     c.hide();      e.after(c);     e.remove();         }); 

A shoter version (not tested):

var e = $("...");  e.append(e.clone().show().html("...").hide()).remove(); 



Approach #2:

Note: you will need a container which you can re-insert the detached element into

$(function () {     var e = $("...");     var c = $("container");      e.detach();     e.show();     e.html("...");     e.hide();     c.add(e);     }); 

And just for good measure - not tested - the shorter version:

$("container").add($("...").detach().show().html("...").hide()); 
like image 21
cllpse Avatar answered Nov 10 '22 01:11

cllpse