tags:

views:

91

answers:

3

I'm using Facebox (http://defunkt.github.com/facebox/) on one of my websites. Also i'm using jQuery extensively on the site.

My problem is that the .val() function doesn't seem to work inside facebox. Now, this is the DIV that shows up as facebox :

<div id="edit-tags" style="display: none;">
  <script type="text/javascript">   
   $('.add-tag-form').submit(function(){
    alert($('input.tags-input').val());
    return false;
   });
  </script>

  <form class="add-tag-form">
   <input type="text" name="tags-input" class="tags-input" />
   <input type="submit" class="small-button" value="Add Tag" />
  <form>
</div>

Now, the problem is that the value of input.tags-input doesn't show up on the alert box. It shows up empty.

To make the problem worse, the jQuery selection actually works. That is, $('input.tags-input').hide() works perfectly fine.

To make the problem even worse, the .val() works with the initial value. That is, if i use this :

<input type="text" name="tags-input" class="tags-input" value="Some value" />

Then, the alert box shows "Some Value" irrespective of whether i change the value or not.

I'm totally stuck here. The .val() at the same position in the code works fine with the text boxes outside the facebox.

+2  A: 

you need to wrap your code in an anonymous function, like

$(function() { ... });
       or
$(document).ready(function() { ... });

may be this help's

$(function() {
   $('.add-tag-form').submit(function(){
      alert($('input.tags-input').val());
      return false;
   });
});

please let me know if the problem still exists

Ninja Dude
+1  A: 

The problem is that by the time your javascript code runs, the document hasn't been loaded yet. By the time you run $('.add-tag-form'), jquery looks and does not find any element that matches the query, and so nothing happens.

To fix this, do as Avinash says, and tell jQuery to run your code when the document is ready. I usually do this with:

$(document).ready(function(){
    ...
});

Another thing, to be safe I also like to wrap my functions and call them with jquery, like so:

(function ($){
   $(document).ready(function() {
       ...
   });
})(jQuery);

This way if someone overrides the $ name, the script still works and I can still use the $ shortcut.

Mike Axiak
Actually the selectors work fine.. $('.add-tag-form').submit(function(){ alert("hello world"); return false; }); $('.add-tag-form').submit(function(){ $("input.tags-input").hide(); return false; });These work fine.. It is the .val() that doesn't work.
Shrihari
A: 
Ngo Minh Nam