tags:

views:

33

answers:

3

I have this link that creates a few div's in which a form is loaded via load(). This form is in a separate php file. Now i want to use the ID value of my link to set the value of an input field, but how?

I know i need live() for that, but the setting of the value should be automatically, and not after an event.

It's a situation like below

main.php


[..]
<a href="form.php" rel="box" id="inputvalue">

form.php


<form>
[..]
<input type="text" id="el">

I now want to set 'inputValue' (when form.php is loaded) as the new value of $("#el"), but how?

My javascript file is in main.php and the way i load form.php is like this


$("a").click(function(){
 if(this.rel == "box"){
  [..]
  $("#container").load("form.php");

When the form is displayed i want to change the value of the input

A: 

Provide a callback function to load which will execute once load is done:

$("a").click(function(){
 if(this.rel == "box"){
  var clicked = this;
  $("#container").load("form.php", function() {
     $("#el").val( $(clicked).attr("id") );
  });
Mikael Svenson
If i use this method i will get <em>container</em> in the input value, because $(this) refers to that container, right?
Maurice
@Maurice: Edited my code. Obvious mistake by me.
Mikael Svenson
A: 

You can use the liveQuery plugin, available here: http://brandonaaron.net/code/livequery/docs. It's a bit like live(), but instead of binding an event, it executes code for each matched element.

SimpleCoder
Will read it, but want to try fixing it myself without plugins, want to learn :)
Maurice
@Maurice: I agree
SimpleCoder
+2  A: 

Provide a callback function which does exactly that. You can pass that as 2nd argument of load().

var linkId = this.id;
$("#container").load("form.php", function() {
    $(this).find('#el').val(linkId);
});

Note that it's a bad idea to have multiple elements with the same id in the document. Your code is namely suggesting that there are multiple links like that.

BalusC
That's it! Thanks! Oh, and i won't have double ID's, no worries :)
Maurice
You're welcome. Don't forget to mark the answer accepted (and do the same for the most helpful answers on your [previous questions](http://stackoverflow.com/users/450454/maurice) whenever applicable). See also http://stackoverflow.com.faq.
BalusC
Oh, sure! Thanks for the tip! Didn't know that!
Maurice