tags:

views:

3951

answers:

3

I have a form with a select field and a div i wish to update with a value depending on what the user selects.

Example:

<select name="mysel" id="msel">
    <option value="test1">Test1</option>
    <option value="test2">Test2</option>
    <option value="test3">Test3</option>
</select>

<div id="myresult"></div>

I would like the div to update with "This is test 2 and other info" if the user selects test2 and so on.

Any help on this would be greatly appreciated.

+2  A: 

The general idea:

$(function() {
   $("#msel").change(function(){
      $("#myresult").html("This is " + $("#msel").val() + " and other info");
   });
});

With more specifics I can do better. ;-)

Joel Potter
+2  A: 

Try something like that:

<select id="choose">
    <option value="test1">Test1</option>
    <option value="test2">Test2</option>
    <option value="test3">Test3</option>
</select>
<div id="update"></div>

<script type="text/javascript>
<!--
    $('#choose').change(function(event) {
        $('#update').html('This is ' + $('#choose').val() + ' and other info');
    }); 
//-->
</script>


If you want to make it with AJAX, change the javascript function to something like that:

<script type="text/javascript>
<!--
    $('#choose').change(function(event) {
        $.post('info.php', { selected: $('#choose').val() },
            function(data) {
                $('#update').html(data);
            }
        );            
    }); 
//-->
</script>

And in your info.php, you'll have something like:

<?php

    $selected = isset($_POST['selected']) ? $_POST['selected'] : 'nothing';
    echo("This is $selected and other info");
lpfavreau
Thank you both for the great replies, i would would like for it to send the value of the select to a php file via ajax, in that way i can use a switch to send back data to the div. The php part i can do but executing the ajax call is where I am lost. Thanks again for the help.
Here you go, but please update (by adding at the bottom) the original question so people looking for a similar answer can benefit from it.
lpfavreau
A: 

This is the simplest way I've found do it (from this handy forum)

<!-- the select -->
<select id="thechoices">
    <option value="box1">Box 1</option>
    <option value="box2">Box 2</option>
    <option value="box3">Box 3</option>
</select>

<!-- the DIVs -->
<div id="boxes">
    <div id="box1"><p>Box 1 stuff...</p></div>
    <div id="box2"><p>Box 2 stuff...</p></div>
    <div id="box3"><p>Box 3 stuff...</p></div>
</div>

<!-- the jQuery -->
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">

$("#thechoices").change(function(){
    $("#" + this.value).show().siblings().hide();
});

$("#thechoices").change();

</script>
laurenmichell