Reputation: 391
Hi I have the following code (I've removed some of the bloat, but everything needed is here.
<div class="item">
<div class="img_url"><input type="text" value="/siteimg/Designs/special-request.jpg" id="DT_Image_1" name="DT_Image_1" /></div>
<div id="copy_to_all_1"><a href="#">Copy to all</a></div>
</div>
<div class="item">
<div class="img_url"><input type="text" value="" id="DT_Image_2" name="DT_Image_2" /></div>
<div id="copy_to_all_2"><a href="#">Copy to all</a></div>
</div>
<div class="item">
<div class="img_url"><input type="text" value="" id="DT_Image_3" name="DT_Image_3" /></div>
<div id="copy_to_all_3"><a href="#">Copy to all</a></div>
</div>
These div's are loaded dynamically, so there could be a lot more in there. I need a way of finding the current ID and then copying it into all of the other input ID's listed.
So in this case if I clicked the link "Copy to all" on the first item, the other input fields would be populated with "/siteimg/Designs/special-request.jpg"
I need abit of jQuery magic to get this ready to go.
Upvotes: 2
Views: 192
Reputation: 7302
Try This:
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('a').live('click', function() {
parentDivTagId = $(this).closest("div").attr("id");
index = parentDivTagId.substring(12, (parentDivTagId.length));
copyString = $('#DT_Image_' + index).val();
$('input:text').val(copyString);
});
});
</script>
</head>
<body>
<div class="item">
<div class="img_url">
<input type="text" value="/siteimg/Designs/special-request.jpg"
id="DT_Image_1" name="DT_Image_1" />
</div>
<div id="copy_to_all_1">
<a href="#">Copy to all</a>
</div>
</div>
<div class="item">
<div class="img_url">
<input type="text" value="" id="DT_Image_2" name="DT_Image_2" />
</div>
<div id="copy_to_all_2">
<a href="#">Copy to all</a>
</div>
</div>
<div class="item">
<div class="img_url">
<input type="text" value="" id="DT_Image_3" name="DT_Image_3" />
</div>
<div id="copy_to_all_3">
<a href="#">Copy to all</a>
</div>
</div>
</body>
</html>
Upvotes: 1
Reputation: 11044
$(document).ready(function(){
$('div[id^="copy_to_all"] a').live('click', function(){
$('.img_url input').val($(this).closest('div.item').find('.img_url input').val())
});
});
P.S.: Your markup sucks. Should be this:
<div class="item">
<input class="img_url" type="text" value="/siteimg/Designs/special-request.jpg" id="DT_Image_1" name="DT_Image_1" />
<a class="copy_to_all" href="#">Copy to all</a>
</div>
And the corresponding function from above:
$(document).ready(function(){
$('a.copy_to_all').live('click', function(){
$('.img_url').val($(this).prev('.img_url').val())
});
});
Edit: Saw the
the divs are loaded dynamically
part of the question, changed click()
to live()
just to be safe.
Edit 2: Bonus working fiddles with original and with decent markup.
Upvotes: 4