开发者

Jquery - Finding Alt Text for Current Image

Using Jquery UI to make a form where when you drag an image to an input, the alt text is parsed as the value of the input.

I have this working fine for 1 image but, I want to make it so it pulls for the current image ( so that I dont have to specify the ID's of all of the images ). See the script below:

<script>    
    $(function() {
    var teamname = $(".helmet").attr("alt");

        $( "#draggable" ).draggable();
        $( "#draggable2" ).draggable();
        $( "#droppable" ).droppable({
            drop: function( event, ui ) {
                $( this )
                    .find( "input" )
                        .val("" + teamname + "");
                }
        });
        $( "#droppable" ).droppable({
            out: function( event, ui ) {
                $( this )
                    .find( "input" )
                        .val( " " );
                }
        });
    });
    </script>

And here is the HTML

<div id="draggable" class="ui-widget-content">
    <img src="team1.jpg" alt="Team Name 1" class="helmet">
</div>

<div id="draggable2" class="ui-widget-content">
    <img src="team2.jpg" alt="Team N开发者_开发技巧ame 2" class="helmet">
</div>

<div id="droppable" class="ui-widget-header">
    <input type="text" name="team" />
</div>

Right now, whether I drag the first or second image, its only grabbing the alt text of the first image. Any help would be greatly appreciated.


Change this function, oh and you can add the out function in with it:

$( "#droppable" ).droppable({
    drop: function( event, ui ) {
        $( this )
            .find( "input" )
                .val("" + ui.helper.find('img').attr('alt') + "");
    },
    out: function( event, ui ) {
        $( this )
            .find( "input" )
                .val( " " );
    }
});

defining teamname outside of the droppable function sets it's definition to the first .helmet it finds.


Since you have multiple draggable elements then things are easier when using a class instead of an id.

<div class="ui-widget-content draggable">
    <img src="team1.jpg" alt="Team Name 1" class="helmet">
</div>

<div class="ui-widget-content draggable">
    <img src="team2.jpg" alt="Team Name 2" class="helmet">
</div>

<div id="droppable" class="ui-widget-header">
    <input id="team-name" type="text" name="team" />
</div>

<script type="text/javascript">
$(function() {

    $.each($( ".draggable" ), function() { $(this).draggable(); });

    $( "#droppable" ).droppable({

        drop: function( event, ui ) {
            $("#team-name").val($("img", ui.draggable).attr('alt'));
        },

        out: function( event, ui ) {
            $("#team-name").val("");
        }
    });
});
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜