Jade
Jade

Reputation: 13

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. 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??

Upvotes: 1

Views: 1163

Answers (3)

stealthyninja
stealthyninja

Reputation: 10371

@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
});

Upvotes: 1

Riba
Riba

Reputation: 1118

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.

Upvotes: 0

mattsven
mattsven

Reputation: 23303

Have you tried:

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

Upvotes: 0

Related Questions