Jump to content

On click, populate field with parent value


Guest

Recommended Posts

I'm at a loss. How would one do this with jQuery?

 

On the page, there are several divs. Each div has several spans and, well, I'll just show you:

 

<p class="box">
<span class="id">Id 1</span>
<span class="title">Title 1</span>
<span class="admin"><a class="edit">Edit</a></span>
<span class="content">Content 1</span>
</p>
<p class="box">
<span class="id">Id 2</span>
<span class="title">Title 2</span>
<span class="admin"><a class="edit">Edit</a></span>
<span class="content">Content 2</span>
</p>

 

And so on. Further down the page, there is a form:

 

<form id="editForm">
<input type="text" id="id" /><br />
<input type="text" id="title" /><br />
</form>

 

I'd like to be able to click the "Edit" link and have it populate the form with the (parent?) id and title.

 

<script type="text/JavaScript">
$(document).ready(function() {
	$("a.edit").live('click', function() {
		$("#editForm #id").val("Something goes here");
		$("#editForm #title").val("Something else goes here");
	});
});
</script>

 

Does that even make sense? Can I somehow select the value of the parent of the link that I'm clicking on??

Maybe if I post a simpler example, I'll be closer to achieving exactly what I want. Let's say I have these divs on my page:

 

<div id="div1">
<a class="red">Red</a>
</div>
<div id="div2">
<a class="red">Red</a>
</div>

 

Clicking on red should turn the div it's nested in to turn red. How do I do this without writing a separate jQuery function for each red link?

 

Bonus points if you can figure out how this would help me solve my original problem :P

Here's one way you can do it (the original problem, btw):

 

$('p.box a.edit').click(function() {
var p = $(this).parents('p.box');
$('form#editForm input#id').val(p.find('> .id').html());
$('form#editForm input#title').val(p.find('> .title').html());
});

 

edited twice for nicer solutions.. Can't think tonight.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.