0

I have a page that is generated dynamically via the URL (GET Method). This dynamic page generates among a lot of other stuff the following line of HTML:

<input type='hidden' name='device' id='device' value='abcd' />

I am also loading several javascript functions, and I want one them to be able to read the initial value of 'device', however, it doesn't seem to be able to read the initial value on the intial page load. It will read it if the javascript function is fired again after the page load.

I am using the following code in my .js file

jQuery(document).ready(function(){
    var device = jQuery('#device').val();
});

When debugging, on the intial page load device is simply set to 'undefined' Anyone have any ideas? Thanks.

Brian

2
  • How are you debugging it? After setting it in that code example, where are you trying to read it? Commented Nov 6, 2011 at 17:56
  • You mean there's an $.ajax() or $.get() call occurring that's loading content, right? So it's loading asynchronously, and $.ready() is firing before the async: true loaded content loads. Have you tried setting async: false on the content loading? Commented Nov 6, 2011 at 18:05

2 Answers 2

1

This means the element isn't available by the time you are looking for its value, you can either use onload event or put your script before </body> tag.

This should work:

$(window).load(function(){
  var device = jQuery('#device').val();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't it already supposed to be "onloaded" bu using $(document).ready?
@ZenMaster: As per OP, it is dynamically generated because of which one can't say for sure.
1

If you load those JavaScript functions together with the HTML that you receive as a response to an AJAX request - it is possible that by the moment your JS executes this code:

jQuery(document).ready(function(){
    var device = jQuery('#device').val();
});

it refers to the existing DOM? If you don't reload your body - I don't see this event firing when you insert the received HTML into your existing DOM.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.