Duncan Palmer
Duncan Palmer

Reputation: 2913

Updating image source with jQuery

So I'm trying to automatically update an image source using javascript but for some reason it won't work. The image is being retrieved from my php text generator (generates an image with text on it) the text is grabbed from a input box. I want it to automatically grab the text inside the inputbox then change the src of image to gen.php?text=Input_box_text_goes_here

here is my code:

<html>
    <head>
        <title>text generator</title>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <script language=javascript type='text/javascript'> 
            setInterval(function () {
                var str= document.form.letters.value;
                $('#logo').src("gen.php?text="+str);
            }, 10);
        </script>
        <img id="logo" name="logo" src="gen.php?text=default" />
        <form name="form" action="">
            Text: <input type="text" name="letters"/>
        </form>
    </body>
</html>

any help will be appreciated.

Upvotes: 0

Views: 124

Answers (2)

Joseph
Joseph

Reputation: 119837

try:

<script>
    $(function(){

        //reference the image
        var img = $('#logo');

        //use onkeyup instead of polling
        $('input[name="letters"]').on('keyUp',function(){

            //get the value every keystroke
            var inputValue = $(this).val();

            //apply the values to the image source
            img.each(function(){
               this.src = "gen.php?text="+inputValue;
            });
        });
    });
</script>

Upvotes: 1

John W
John W

Reputation: 1512

Change $('#logo').src("gen.php?text="+str); to $('#logo').attr("src", "gen.php?text="+str);.

Upvotes: 2

Related Questions