ASMSaief ASMSaief - 2 months ago 18
PHP Question

PHP Select Option from other select value

If select 'Man' in first select Then second select option show Man's product from database.
If select 'Woman' in first select Then second select option show Woman's product from database.
How can I set this system?

<form method="post" action="" >

<label>Category</label></br>
<select name="cat">
<option value="Man">Man</option>
<option value="Woman">Woman</option>
</select></br></br>


<label>Product</label></br>
<select name="product">
<option value="">Select Product</option>
</select></br></br>
<input type="submit" name="submit" value="Submit"/>
</form>

Answer Source

$(document).ready(function(){
    $("select.cat").change(function(){
        var selectCat = $(".cat option:selected").val();

//sample data - code starts here
        var data  = '[{"id":1,"name":"product 1"},{"id":2,"name":"product 2"}, {"id":3,"name":"product 3"}]';
        data = jQuery.parseJSON( data ); 
//sample data ends here
$('#response').html('');
       $('#response').append(' <label>Product:</label><select class="product" id="product"> </select> ');

       $('#response select').append($("<option />").val('').text('Select'));

       $.each(data,function(index, value){

           $('#response select').append($("<option  />").val(value.id).text(value.name));
       });
//add above code to your ajax success - code ends here.. 
        //return false;
        $.ajax({
            type: "GET",
            url: "process-ajax.php",
            data: { cat : selectCat } 
        }).done(function(data) {
        });
    });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form>
    <table>
        <tr>
            <td>
                <label>Category:</label>
                <select class="cat">
                    <option>Select</option>
                    <option value="1">Man</option>
                    <option value="2">Woman</option>
                </select> 
            </td>
            <td id="response">
            </td>
        </tr>
    </table>
</form>