0

I'm trying to use jquery to set some default text in a form input. The text will be dynamic and so I can't just set this in the html. I want the jquery to wait for the form to load.

The delay function sets the text, but doesn't delay at all. It's instant.

Nothing in the load function seems to execute.

HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Testinput</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="testinput.js"></script>
</head>

<body>
<form>
  <input size="20" name="thing" />
  <input type="image" src="" name="submit" value="go" />
</form>

</body>
</html>

JQuery code:

$(document).ready(function(){

var $input = $('input[name="thing"]');
$input.val("");

var query = "orange";

//$input.delay(10000).val(query); // No delay!

$input.load(function(){ 
// Nothing happens!!
alert("form loaded");
$input.val(query);
});

});

Tried both jquery-1.6.4.min.js and jquery-1.4.min.js to no avail.


Edit: I can't respond to replies, javascript on stack overflow doesn't seem to be working correctly for me. I get "Stack Overflow requires external JavaScript from another domain, which is blocked or failed to load".

I've gotten the delay function working using Clive's answer, but is there a way to make jquery wait for a form to have loaded first before running code?

1
  • @shafty: Regarding your edit: You're already doing it...$(document).ready will only be run when the DOM is ready, at which point the form will be fully loaded and available in the DOM tree. Commented Oct 13, 2011 at 14:44

1 Answer 1

3

delay() relates to queues, not arbitrary functions so you need to use setTimeout() instead:

window.setTimeout(function () {
  var $input = $('input[name="thing"]');
  var query = 'orange';
  $input.val(query);
}, 10000);

Also load() is a function to:

Load data from the server and place the returned HTML into the matched element.

It won't work for what you're trying to do

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to make jquery wait for a form to have loaded first before running code? The delay function works, but isn't always a practical solution.

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.