tags:

views:

30

answers:

2

Let's say I have an image and a textfield. Whenever I type a specific word into the textfield... I want the image to dynamically and ajax-acally change (without reloading the web page) to the image I set it at...

How is this done? Maybe using PHP/jQuery?

A: 

Here is a partial solution to start you off:

// bind to the keyup event of a text input
$("#textinput").keyup(function() {

    // when the event is triggered, send the captured text to the server
    // as the 'whichImage' param
    $.getJSON('image.php', { whichImage: $(this).val()}, function(json) {

        if(!json.error) {
            // modify the src (and whatever other attributes) to
            // whatever the response contains
            // another approach would be to send back an entire image tag and insert it
            // somewhere in the document
            $("#theImage").attr('src', json.src);
            $("#theImage").attr('width', json.width);
        } else {
            alert(json.error);
        } 
    });
});

PHP:

<?php
if(isset($_GET['whichImage']) && !empty($_GET['whichImage'])) {

    // supposing that function returns array('src' => 'foo.jpg', 'width' => '250px') etc..
    $imgArray = getMatchingImage($_GET['whichImage']);
    if(!empty($imgArray)) {
        echo json_encode($imgArray);
    } else {
        echo json_encode(array('error' => 'no match!'));
    }
    exit;
} 
?>

It would be a good idea to add a delay to sending captured text to the server, so requests are not constantly firing while the user is typing. Hope this was useful!

karim79
This looks promosing. But the image will NOT change in width so I can remove that. But how would I complete the PHP code because I think if I add the array inside the !empty check that it would not be right.
Dan
+1  A: 

This has nothing to do with a server-side language like PHP.

Using jQuery:

$(function() {
   $('#textfield').change(function () {
     switch($(this).val()) {
       case 'some text':
         $('#image').attr('src', 'some image source');
         break;
       case 'some other text':
         $('#image').attr('src', 'some other source');
         break;
     }
   });
});

Alternatively, you could maintain a hash of text => image-src pairs. Instead of a switch statement, you could simply see if the text the user has entered exists has a matching image src within the hash.

meagar
Works like a charm! http://www.dasdas.pastebin.com/tgicjmSK
Dan
Only one thing... can I make it so it "fades" to anotehr image and instead of pressing enter It can be on Key press? :D
Dan
OK I solved the keyUp problem... thanks to this: http://api.jquery.com/keyup/
Dan