I wanted to chain 3 selects and I got it working using this code. http://jsfiddle.net/FJFFJ/1/
The issue I now have is, how do I fetch the selected values from each dropdown in PHP? For example, the above creates 3 select boxes when the page is opened. When I click on "+" button and add more rows of selects, how do I fetch the values from all selects which were added dynamically and save those to mysql database in php?

Recommended Answers

All 12 Replies

The select elements have to have name attributes and be enclosed in form tags containing the action and method attributes in order to properly pass the values to the server. Something like:

<form action="process.php" method="post">
    <select class="pais" name="sel_pais">
        <option value="1">Argentina</option>
        <option value="2">Chile</option>
    </select>
    <select class="provincia" name="sel_provincia>
        <option value="1" class="1">San Juan</option>
        <option value="2" class="1">Mendoza</option>
        <option value="3" class="2">La Serena</option>
        <option value="4" class="2">Santiago</option>
    </select>
    <select class="ciudad" name="sel_ciudad>
        <option value="1" class="1">Rawson</option>
        <option value="2" class="2">Godoy Cruz</option>
        <option value="3" class="3">Coquimbo</option>
        <option value="4" class="4">Chiñihue</option>
    </select>
</form>

The process.php will do the processing (= storing into database) of the data which is stored in the $_POST global array, again just an example:

// initialize an array for possible error messages
$error_array = array();

// check if value for the country exixts and is not empty string
if(isset($_POST['sel_pais']) && !empty($_POST['sel_pais'])) {
    // trim the value and escape it if it goes to the DB
    $pais = mysqli_real_escape_string(trim($_POST['sel_pais']));
} else {
    // if no value add the error to the error_array
    $error_array[] = 'No country selected!';
}

// check if value for the province exixts and is not empty string
if(isset($_POST['sel_provincia']) && !empty($_POST['sel_provincia'])) {
    // trim the value and escape it if it goes to the DB
    $provincia = mysqli_real_escape_string(trim($_POST['sel_provincia']));
} else {
    // if no value add the error to the error_array
    $error_array[] = 'No province selected!';
}

// check if value for the city exixts and is not empty string
if(isset($_POST['sel_ciudad']) && !empty($_POST['sel_ciudad'])) {
    // trim the value and escape it if it goes to the DB
    $ciudad = mysqli_real_escape_string(trim($_POST['sel_ciudad']));
} else {
    // if no value add the error to the error_array
    $error_array[] = 'No city selected!';
}

// now check if there were any errors
if(!empty($error_array)) {
    // display the errors
    foreach($error_array as $error_message) {
        echo "$error_message<br>";
    }
    echo 'Go back and select all the data!';
} else {
    // insert the data into database
    ...
}

this is what I did but irrespective of what i select, echo statement prints only the value "1" for the first dropdown.

<?php
if(isset($_POST['submit'])){
    foreach($_POST['semester'] as $sem){
        echo $sem;
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.5.js'></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">


  <link rel="stylesheet" type="text/css" href="/css/result-light.css">



      <script type='text/javascript' src="http://www.appelsiini.net/download/jquery.chained.mini.js"></script>


  <style type='text/css'>
    #template{
    display:none;
}
  </style>



<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(function() {

    // Form element cloning
    var i = 0;
    $('#clone').click(function() {

        $('#template').clone().appendTo('#filter');
        $('#filter #template').attr('id', 'duplicate' + i);
        $('#filter div:hidden').show();


        chainItWithId(i);
        i++;
    });
    $('#remove').click(function() {
        $('#filter > div').last().remove();
    });

    $('#clone').click();
});

function chainItWithId(id) {
    $('#duplicate' + id + ' .department').chained('#duplicate' + id + ' .semester');
    $('#duplicate' + id + ' .subject').chained('#duplicate' + id + ' .department');
}


function chainTemp() {
    $('#template .department').chained('#template .semester');
    $('#template .subject').chained('#template .department');
}
});//]]>  

</script>
</head>

<body>
<div id="filter">
            <a id="clone" href="#">+</a> <a id="remove" href="#">-</a>

        </div>
        <form name="request" action="<?php $_SERVER['PHP_SELF']?>" method="post">
        <div id="template">
            <select class="semester" name="semester[]">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
            <select class="department" name="department[]">
                <option value="EEE" class="1">EEE</option>
                <option value="ECE" class="1">ECE</option>
                <option value="MECH" class="2">MECH</option>
                <option value="CSE" class="2">CSE</option>
            </select>
            <select class="subject">
                <option value="1" class="EEE ECE">S1</option>
                <option value="2" class="ECE">S2</option>
                <option value="3" class="MECH">S3</option>
                <option value="4" class="CSE">S4</option>
                                <option value="5" class="MECH">S5</option>
                <option value="6" class="CSE EEE">S6</option>
            </select>
        </div>
        <input type="submit" name="submit" value="submit" />
</form>
</body>
</html>

Select names should not have the [] appended to them (you use this approach for grupped elements like radio button or checkbox groups). So:

<select class="semester" name="semester">

The third select element does not have a name attribute at all, so add it.

And this is how you display the values:

if(isset($_POST['submit'])) {
    foreach($_POST as $value) {
        echo $value;
    }
}

I you do not want to use the 'submit' element, you can skip it:

if(isset($_POST['submit'])) {
    foreach($_POST as $key => $value) {
        if($key != 'submit') {
            echo $value;
        } 
    }
}

Thanks, I did what you said.
The output can be viewed at http://theinfectedmind.com/svbb/chained.php
I am not getting in output what I have selected.

and the code I used,

<?php
if(isset($_POST['submit'])) {
    foreach($_POST as $key => $value) {
        if($key != 'submit') {
            echo $value;
        } 
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.5.js'></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">


  <link rel="stylesheet" type="text/css" href="/css/result-light.css">



      <script type='text/javascript' src="http://www.appelsiini.net/download/jquery.chained.mini.js"></script>


  <style type='text/css'>
    #template{
    display:none;
}
  </style>



<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(function() {

    // Form element cloning
    var i = 0;
    $('#clone').click(function() {

        $('#template').clone().appendTo('#filter');
        $('#filter #template').attr('id', 'duplicate' + i);
        $('#filter div:hidden').show();


        chainItWithId(i);
        i++;
    });
    $('#remove').click(function() {
        $('#filter > div').last().remove();
    });

    $('#clone').click();
});

function chainItWithId(id) {
    $('#duplicate' + id + ' .department').chained('#duplicate' + id + ' .semester');
    $('#duplicate' + id + ' .subject').chained('#duplicate' + id + ' .department');
}


function chainTemp() {
    $('#template .department').chained('#template .semester');
    $('#template .subject').chained('#template .department');
}
});//]]>  

</script>
</head>

<body>
<div id="filter">
            <a id="clone" href="#">+</a> <a id="remove" href="#">-</a>

        </div>
        <form name="request" action="<?php $_SERVER['PHP_SELF']?>" method="post">
        <div id="template">
            <select class="semester" name="semester">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
            <select class="department" name="department">
                <option value="EEE" class="1">EEE</option>
                <option value="ECE" class="1">ECE</option>
                <option value="MECH" class="2">MECH</option>
                <option value="CSE" class="2">CSE</option>
            </select>
            <select class="subject" name="subject">
                <option value="1" class="EEE ECE">S1</option>
                <option value="2" class="ECE">S2</option>
                <option value="3" class="MECH">S3</option>
                <option value="4" class="CSE">S4</option>
                                <option value="5" class="MECH">S5</option>
                <option value="6" class="CSE EEE">S6</option>
            </select>
        </div>
        <input type="submit" name="submit" value="submit" />
</form>
</body>
</html>

There are two problems:

  1. The new select elements do not get inserted within exiting form tags but outside. Probably the div with the id=filter should be inside the form.
  2. the newly inserted select elements all have the same name which is semester. You have to make up a logic in the js script that will assign a sequential name attribute to each inserted select element.

okay, will check on that.. but even without adding any additional elements, if i print the values using php, I am not getting what I have selected. instead, i am getting the first element in the <option>.

but even without adding any additional elements, if i print the values using php, I am not getting what I have selected. instead, i am getting the first element in the <option>.

I have had a look at the jquery code. The problem is that you call the $('#clone').click() on line 54 of your last posted code. This function call generates a new set of select elements immediately on page load and this set is hidden. The elements have the same name attributes as the first set that is visible. Upon clicking of a submit button the unchanged values of the second hidden set override the selected values of the first set in the $_POST array.

The solution is to remove the call to the .click() function on line 54 and let the user call it by clicking on + sign (which is how this method should be used).

The problem of same name attributes still remains though. The jquery code should be amended to assign different names to new sets of select elements. I am not an expert in jquery but will have a look at it once I find time.

ok thanks guys for the help.. I am no expert in jQuery as well.. will wait until I get working solution.

I took some time to have a closer look at the jquery code as well. I changed it a bit to make it clear and working. See the comments in the code and consider the following:

  • I made the template containing the filter (the three select elements within a div) hidden: <div id="template" style="display:none;">; this template is only used for clonning when user clicks +. This is neccessary to get the filter clonned before it gets chained (otherwise you can not clone select elements with all the possible values)
  • the template is within the div with id=template, while the added filters are within the div with id=filters
  • upon clonning the id of the clonned div has to be changed from the 'template' to filter + somesequentalnumber
  • upon clonning also the id and name attributes of the select elements have to be changed (just by adding same somesequentalnumber to them)
  • after that the select elements have to be chained
  • on page load the first set of select elements is cloned, added and chained so you have the first filter (the template filter remains hidden)
  • when you process the $_POST array you first unset (remove) the elements that you actually do not need (the submit button and the values of the three template select elements)

I hope this is what you are after. Also I hope that changing the code did not break your existing project. But this way it is clear how everything works.

This is the changed code:

<?php
if(isset($_POST['submit'])) {

    // unset the elements in the $_POST array that are not needed
    // (the submit element and the three select elements
    // from the template)
    unset($_POST['submit']);
    unset($_POST['semester']);
    unset($_POST['department']);
    unset($_POST['subject']);

    // loop through posted elements and display them
    foreach($_POST as $key => $value) {
        echo "$key: $value<br />";
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="http://www.appelsiini.net/download/jquery.chained.mini.js"></script>


<script type='text/javascript'>//<![CDATA[                                     
$(window).load(function(){

    $(function() {

        // variable to number the added filters, starting with 1
        var i = 1;

        // this function clones the filter from the hidden template
        // when user clicks the + sign
        $('#clone').click(function() {

            // clone the three select elements from the template div
            // and append it to the filters div
            $('#template').clone().appendTo('#filters');

            // in the filters div change the cloned template div's id attribute
            // from 'template' to 'filter' + i
            // and show the div (the template's div has display:none property)
            $('#filters #template').attr('id', 'filter' + i).show();

            // also change the three selects' id
            // and name attributes (append ther current i to them)
            $('#filters #semester').attr('id', 'semester' + i).attr('name', 'semester' + i);
            $('#filters #department').attr('id', 'department' + i).attr('name', 'department' + i);
            $('#filters #subject').attr('id', 'subject' + i).attr('name', 'subject' + i);

            // with the chainItWithId() chain the select elements (depending on their id)
            chainItWithId(i);

            // increase the number i
            i++;
        });

        // this function removes the last div within the div with id=filters
        $('#remove').click(function() {
            $('#filters > div').last().remove();
        });
    });

    // this function chains the three select elements together
    // using the Chained Selects jQuery Plugin
    // see http://www.appelsiini.net/projects/chained
    function chainItWithId(id) {

        // the chaining occurs in the last appended div ('#filter' + id)
        var targetDiv = '#filter' + id;

        // chain the divs in the targetDiv
        $(targetDiv + ' .department').chained(targetDiv + ' .semester');
        $(targetDiv + ' .subject').chained(targetDiv + ' .department');
    }

    // on load fire the click event to create the first set of filters
    // (the template remains hidden)
    $('#clone').click();
});//]]>  
</script>

</head>

<body>
    <div id="filter">
        <a id="clone" href="#">+</a>
        <a id="remove" href="#">-</a>
    </div>

    <form name="request" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

        <!-- Beginning ot he hidden div containing the template for the filter -->
        <div id="template" style="display:none;">
            <select class="semester" id="semester" name="semester">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
            <select class="department" id="department" name="department">
                <option value="EEE" class="1">EEE</option>
                <option value="ECE" class="1">ECE</option>
                <option value="MECH" class="2">MECH</option>
                <option value="CSE" class="2">CSE</option>
            </select>
            <select class="subject" id="subject" name="subject">
                <option value="1" class="EEE ECE">S1</option>
                <option value="2" class="ECE">S2</option>
                <option value="3" class="MECH">S3</option>
                <option value="4" class="CSE">S4</option>
                <option value="5" class="MECH">S5</option>
                <option value="6" class="CSE EEE">S6</option>
            </select>
        </div>
         <!-- End ot he hidden div containing the template for the filter -->

         <!-- This is where all the filters will be placed -->
        <div id="filters">
        </div>

        <input type="submit" name="submit" value="submit" />
    </form>
</body>
</html>
commented: Thanks a lot for this code! It helped me. Is it possible to calculate the sum of values selected in the third dropdown list of all rows added by user? +0

that works like charm.. i now get the count of $_POST and do $_POST['semester.$count'] and so on to get the values for each selected element and insert into DB.
Thanks and appreciate your help.

Hi guys, I have seen how to clone elements and gives sequential numbers for their names and ids attributes, the questions is how did you insert the additional information into the database? any help would be appreciated.

commented: I think it's better for you to create another thread of this questions @phpcake +0

I have website that enables user to select favourite websites, date of visiting the website, comments like how satisfied with the website they visited on that day. Initially there are four rows are hard coded and inserted into the mysql database. Then there is a add button enabling user to choose more website to add onto the existing ones, and also associated date of visiting and comments. The question is how can I insert the additional selected fav website into database.

Here is my code https://jsfiddle.net/j8odptds/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.