user1618573
user1618573

Reputation: 11

Catch a change event on a field with no ID with jQuery

I struggle with with jQuery but need to figure this out to finish some code I'm working on.

I control the img tag but not the input (meaning I cannot give it an ID like I would like).

I need to set the img's SRC to the value of the input's value (whenever the user changes it).

Here is the HTML:

<div class="my_meta_control metabox">
    <img id="IconImage" src="">
    <p>
        <input type="text" class="mediafield-nn" name="_custom_meta[imgurl]" value=""/>
        <a href="media-upload.php?post_id=2&tab=type&TB_iframe=1" class="mediabutton-nn thickbox button {label:'Insert'}">Add Media</a>
    </p>
</div>

This is what I have been trying, with no luck. Any help would be greatly appreciated. :)

$('#IconImage').next().children(":first").change(function() {
    var icon = $(this).val();
    $('#IconImage').attr('src', $(icon));
}

Upvotes: 0

Views: 79

Answers (2)

Cat
Cat

Reputation: 67522

Your selector is fine (though I think there are better alternatives, like $('#IconImage').next().find("input[type='text']")), but there are a few problems:

  1. You may not be executing this code in ready(). I would suggest doing that.
  2. You are referencing $(icon) instead of just icon. It is not a DOM selector, just text.
  3. You didn't close the ( of .change(.

Here is a working JSFiddle with the above changes applied.

The code:

$(document).ready(function() {
    $('#IconImage').next().children(":first").change(function() {
        var icon = $(this).val();
        $('#IconImage').attr('src', icon);
    });
});​

Upvotes: 1

Phil.Wheeler
Phil.Wheeler

Reputation: 16858

How about this:

var container = $('.my_meta_control metabox');

$('input:first', container).change(function(){
  $('img:first', container).attr('src', $(this).val());
});

Upvotes: 0

Related Questions