Home > Net >  Is there a way to POST the value and the content of html form option?
Is there a way to POST the value and the content of html form option?

Time:01-11

I have a form that uses a dynamic dropdown to choose the options. I am using PHP to pull the data from my database.

I am looking for a way to send both the option value(bunker_id) as well as the content(bunker_name).

I am pretty new to coding and have looked at some tutorials. Tutorial 1

I'm a little lost. I assumed that this would let me use $bunker_name=$_POST['name'] in my action page to get the content, but when I perform an echo($bunker_name) nothing appears on the page.

Is there a better way to get both the value and content?

bunker_id = {1,2,3,...} bunker_name = {Bunker K1, Bunker T2, Bunker X, ...}

<label for="bunker_id">Bunker</label>
        <select name="bunker_id" id="bunker_id" required>
        <option value="%" bunk_name="All">All</option>
        <?php
            while($data=mysqli_fetch_array($result_bunker)){
                echo "<option value='".$data['bunker_id']."' bunk_name='".$data['bunker_name']."'>".$data['bunker_name']."</option>";
            }
        ?>
        <input type="hidden" id="name" name="name" value=""/>
        </select>
$(function() {
            $(#bunker_id).change(function(){
                var bunkerName =$('option:selected', this).attr('bunk_name');
                $('#name').val(bunkerName);
            });
        });

CodePudding user response:

Here my soluition...

$(function() {
    // Trigger event when #bunker_id on change
    $("#bunker_id").on('change', function(){
        // get bunker name from selected option
        var bunkerName = $(this).find(':selected').data('bunker');
        // get bunker id from selected option
        var bunkerId = $(this).val();
        // result
        console.log(`Bunker ID: ${bunkerId} | Bunker Name: ${bunkerName}`);
    });
});
<label for="bunker_id">Bunker</label>
<select name="bunker_id" id="bunker_id" required>
    <option value="%" data-bunker="All">All</option>
    <option value="1" data-bunker="Bunker 1">Bunker 1</option>
    <option value="2" data-bunker="Bunker 2">Bunker 2</option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  •  Tags:  
  • Related