开发者

Problem with retrieving dynamic value set to an input element in jquery

I have set the value of a hidden input element dynamically on clicking a link.

<input id="flag" type="text" class="hidden"  /> 

$("#changed_link").click(function(){
            $('#flag').val(1);
});

This link opens a lightbox window. In the lightbox, one of my div, that #section1 is hidden开发者_如何学Go. Initially, when I open the lightbox,(by clicking another link), this div is hidden. The second time, when I clicked the second link, i.e, changed_link, I want this #section1 to be shown.

so I tried to set a flag value , while clicking the link, and pass it to the corresponding js file. But when I try to retrieve the value of that hidden input flag, it is undefined in the js file.

var flag=$('#flag').val();
alert(flag); //undefined

But if the flag value is set initially,

 <input id="flag" type="text" class="hidden" value='1' /> 

then I get that value in the js file. but then the div section1 is always shown.

How can I get the dynamically set value in my js file??


@Jade: Try --

var flag = $('#flag', top.document).val();
alert(flag);

Update

The above assumes you're checking the value of the hidden input from your lightBox. If however you're checking in the parent window, then initialise your hidden input with 0:

<input type="hidden" id="flag" value="0" />

<a href="#" id="changed_link1">Link 1</a> | 
<a href="#" id="changed_link2">Link 2</a> 

and set/check the value of the hidden input accordingly:

$("#changed_link1").click(function(e) {
    e.preventDefault();
    $('#flag').val(1);
});

$("#changed_link2").click(function(e) {
    e.preventDefault(); 
    var flag = $('#flag').val(); 
    alert(flag); // 0 if first link wasn't used, 1 if it was
});


Have you tried:

$(function(){
    var flag = $('#flag').val();
    alert(flag);
});


Sometimes I have the same problem and I change my code for : $('#flag').attr('value');

Otherwise, if your goal is to alternatively show/hidden a dom node, you can use : $(...).toggle()

Hope this help.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜