views:

40

answers:

4

given series of DIVs w/unique ID as in:

<div id="2988">
    <div class="site">YaHoot.com</div>
    <div class="logo">/images/yahootLogo.jpg</div>
//[and so on]
    <input type="button" value="YaHoot" onclick="javascript:processMe('2988');" />
</div>

//[followed by bunches more divs repeating that structure]

I'm trying to code a click handler that can map a form's hidden fields with the contents of each of the child DIVs.

In other words, the form has a hidden field:

<input type="hidden" name="logo"> 

that should be valued with /images/yahootLogo.jpg when the given button is clicked.

thx

+1  A: 

You should be able to accomplish this by adding a click event to the buttons that follow the pattern. In the example below I just used the :button selector, but you would probably want to modify this to your needs, maybe you can piggy back on the processMe() function that it is already calling .

Also you may need to use siblings() or prevAll() instead of prev() depending on the exact layout.

$(document).ready(function(){
    $(":button").click(function(){
        $("input[name='logo']").val($(this).prev(".logo").text());
    });
});

Example with prevAll()

$(document).ready(function(){
    $(":button").click(function(){
        $("input[name='logo']").val($(this).prevAll(".logo").text());
    });
});
Quintin Robinson
+1  A: 

I like to use jQuery's context feature for this, like:

function processMe(id){
  var logo = $(".logo", "#"+id).text();

  $("input[name='logo']").val(logo);
}
Andy Groff
A: 

Try this -

<div id="2988">
    <div class="site">YaHoot.com</div>
    <div class="logo">/images/yahootLogo.jpg</div>
//[and so on]
    <input type="button" value="YaHoot" onclick="javascript:processMe(this);" />
</div>


<script type="text/javascript">

function processMe(id){
$(id).siblings().each(function(){
var class = $(this).attr('class');
$('input[name='+class+']').val($(this).val());
});
}
</script>

The above code will replace the values of all the div's with same parent in to the 
hidden fields with class name equal to the individual div's class name.
Alpesh
A: 

My solution:

$(function() {
    $("#2988 div").each(function() {
        $(this).parent().append('<input type="hidden" name="'+$(this).attr("class")+'" value="'+$(this).text()+'" />');
    });   
});

Oh... as a sidenote, element IDs beginning with digits are technically invalid :)

chigley