Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Update select element using AJAX

To do this you will need http://webcodingeasy.com/jquery.js library. So for example in one select element we have two parents, each of them has their own children. We want to display children of selected parent in second select element.

So here is a code for select elements:

<select name='parent' id='parent' onchange='check_child()'>";
<option value='1'>Jack</option>";
<option value='2'>John</option>";
</select>
<p>&nbsp;</p>
<select name='child' id='child'>";
<option value='1'>Susan</option>";
<option value='2'>Lenny</option>";
</select>

Then we define function which will get children depending on parent using jquery AJAX request

<script type="text/javascript">
function check_child()
{
    $.getJSON("select.php",
    {
        atr: $("select#parent").val(), 
        ajax: 'true'
    }, 
    function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + 
        j[i].optionValue + '">' + 
        j[i].optionDisplay + 
        '</option>';
      }
      $("select#child").html(options);
    })
}
</script>

And this PHP code inside "select.php" file to provide data to AJAX request

<?php
if(isset($_GET['atr']))
{
echo "[ ";
    if($_GET['atr'] == 1)
    {
        echo "{optionValue: '1',".
             " optionDisplay: 'Susan'}";
        echo "{optionValue: '2',".
             " optionDisplay: 'Lenny'}";
    }
    else if($_GET['atr'] == 2)
    {
        echo "{optionValue: '1',".
             " optionDisplay: 'Carl'}";
        echo "{optionValue: '2',".
             " optionDisplay: 'Homer'}";
    }

    echo "]";
}
?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus