开发者

jQuery dialog scripts for input val

I have a bit of a problem with a jQuery dialog and the way scripts are handled.

In the dialog html, I have

<input id="test"> 

If I do

<script type="text/javascript>
   $('#test').va开发者_JS百科l("haha")
</script>

after the input, it shows up. If I put it before, it doesn't work. Now the problem is I'm trying to change the value of $('#test') using a click trigger, and I can't!

   $('.testbutton').click(function() { 
          alert();      
          $('#test').val("haha");
    });

The alert works, and the initial val replacement works, which means there aren't any duplicate or missing input areas.

The total script as it is now, not working:

<input type="button" class="testbutton" />
<input type="text" size="10" id="test" name="test" value="">

 $('#test').val("currentvalue"); // This works
       $('.testbutton').click(function() { 
              alert();      
              $('#test').val("haha");
        });

Update The dialog shows the correct value in #test once the dialog is closed and then reopened. Could this be something I'm missing?


Put your jQuery code into $(document).ready(function () {...your code...}). This will make it executed after browser creates DOM tree for your page. Otherwise javascript is not able to search/manipulate DOM elements correctly. It will look as following:

$(document).ready(function () {
    $('.testbutton').click(function() { 
          $('#test').val("haha");
    });
});

Update:

If your HTML code is loaded dynamically, then use live to bind event handler:

$(document).ready(function () {
    $('.testbutton').live("click", function() { 
          $('#test').val("haha");
    });
});


I guess you should wrap your code inside of a $(function() { //code here }); to make sure your code is run only when your DOM is ready.


The problem ended up being the # in test. For some reason the replacement works with a class identifier instead of a id identifier. I suppose it's because the # will replace only one instance, and for some reason that I have yet to discover, there is more than one instance of the dialog (or a hidden one).

Thanks for all your suggestions!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜