简体   繁体   中英

How can I get the selected value from a drop down list

I am trying to use a dynamically generated dropdown list to populate a table. I have a drop down list that is generated from my database (it grabs all the years available for a specific player). I want to be able to select a year from the dropdown and have it update my table. I have the dropdown being generated, but I am not able to get the selected value from the dropdown. I have code below that I found here, but it doesn't seem to work. Here is the code I have so far:

<input name="update" type="submit" value="Update" />
</form>
<p></p>
<form  action="player_login.html">
<input type="submit" value="Logout" />
</form>
</div>

<div style="float: left">
    <p></p>
<h1>Player Stats</h1>
<table width="300" border="1" cellpadding="2" cellspacing="2">

<?php
    // get "id" field from player table
    $login_id = $_COOKIE["DB"];
    $id = "select id from player where login_id='$login_id';";
    $result1=mysql_query($id)  or die('Select1 Query failed: ' . mysql_error());
    $row = mysql_fetch_array($result1);

    // create a dropdown from stats table in db
    echo "--Select Year--";
        $years_query = "select year from stats where player_id='$row[id]';";
        $years = mysql_query($years_query, $connect);

        // fill array with db info
        $var = array();
        while ($row2 = mysql_fetch_array($years))
        {
            $var[] = $row2['year'];
        }

        // create dropdown
    echo'<select name="years" id="years">'; 
    // For each value of the array assign variable name "city" 
    foreach($var as $year)
    { 
            echo'<option value="'.$year.'">'.$year.'</option>'; 
    }    
    echo'</select>';

    // get selected option from dropdown
    $selected_key = $_POST['years'];
    $selected_val = $var[$_POST['years']];
    echo "<p></p>selected key: " . $selected_val; // this wont print anything???

    $search_query="select * from stats where player_id='$row[id]' and year=2013;";
    $result=mysql_query($search_query)  or die('Select2 Query failed: ' . mysql_error());
    $num_cols = mysql_num_fields($result);
    $line = mysql_fetch_row($result);

    // create table with results
    echo "<tr>";
    echo "<td>Year</td>";  
        $j=1;
        echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
    echo "</tr>";
    echo "<tr>";
    echo "<td>Total Points</td>";  
        $j=2;
        echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
    echo "</tr>";
    echo "<tr>";
    echo "<td>PPG</td>";  
        $j=3;
        echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
    echo "</tr>";


?> 

</table>
</div>

I see that you use $_POST and since form is not submitted and thus data of $_POST is not set. Best available option I have used to catch the event and send the AJAX Query fetch results and update it.

I have done this with the help of J Query as under

$('#years').change(function() {
   $.ajax({
           //request of AJAX
    type : 'POST',
    url : 'players_data.php',
    dataType : 'json',
    data: {
        //Data with $_POST request
        years : $('#years').val();

    },
    success: function(data){
    //Things to be done with returned data
    }
}};

Create a new file players_data.php and there you write the code for fetching data from the db as:

// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???

$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query);
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
$return['year']=$line;
echo json_encode($return);

I see that you are using $_POST , and why do you don't use a form ?

//This is for get the form
    echo '<script type="text/javascript">
        //<![CDATA[
        function get_form( element )
        {
            while( element )
            {
                element = element.parentNode
                if( element.tagName.toLowerCase() == "form" )
                {
                    return element
                }
            }
            return 0; //error: no form found in ancestors
        }
        //]]>
    </script>';

//create a form
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
// create dropdown; onchange will send the form when selected index changes...
echo '<select name="years" id="years" onchange="get_form(this).submit(); return false;">'; 
    // For each value of the array assign variable name "city" 
    foreach($var as $year)
    { 
            echo'<option value="'.$year.'">'.$year.'</option>'; 
    }    
    echo'</select></form>';

And that's all! :D

I'm seeing too that you are using an unique form for update all the page... It's isn't work, because you only have a submit button and no more element in the form, please read that: http://www.w3schools.com/tags/tag_form.asp

From your code i can see that u want to get the value from the select box and immediately populate the table and display the results..use jquery to get the value of selected object and assign the javascript variable to a php variable. and insert into the db..

       <script type="text/javascript">
   $( "#years" ).change(function() {
     var value=document.getElementById("years").value;
         alert(value);
       </script>

assign the variable to php and execute you php query.

              <?php
             $data = "<script>document.write(value)</script>";
                  //execute  your query here..
        ?>

Also have a look at ajax..it does that so well...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM