Home > Software design >  How to get the values of the select option for the show modal?
How to get the values of the select option for the show modal?

Time:12-23

I have a select option like this:

<form action="#" >
    <select  id="value" name="value">
        <option value="">Select an option</option>
        <option value="1" data-bs-toggle="modal" data-bs-target="#valueModal" data-id="1">Driver2</option>
        <option value="2" data-bs-toggle="modal" data-bs-target="#valueModal" data-id="2">Driver1</option>
        <option value="3" data-bs-toggle="modal" data-bs-target="#valueModal" data-id="3">Driver3</option>
        <option value="4" data-bs-toggle="modal" data-bs-target="#valueModal" data-id="4">Create date</option>
    </select>
...

I want to get the values of the select option for the show modal.

For example, when I select the below option, I want to show the modal of bootstrap 5 like this.:

<option value="2" data-bs-toggle="modal" data-bs-target="#valueModal" data-id="2">Driver1</option>

I also have a Bootstrap modal window:

<div  id="valueModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="valueModal" aria-hidden="true">
    <div >
        <form action="#" >
            <input value="" name="option_id" type="hidden">
            <div >
                <h5  id="valueModal">Modal title</h5>
                <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div >
                <div >
                    <!-- Multi Forms -->
                </div>
            </div>
            <div >
                <button type="button"  data-bs-dismiss="modal">Close</button>
                <button type="button" >Save changes</button>
            </div>
        </form>
    </div>
</div>

I would like to show the Bootstrap modal if the value value is selected.

I have tried doing this:

<script>
    $("#value").bind("change", function () {
        $('#valueModal').modal('show')(this.value === 'option_id');
    }).change();
</script>

CodePudding user response:

You can get all the child option tags by using selectElement.options and can access them by index like an array.

sel.addEventListener("change",()=>{
  let selectedOption = sel.options[sel.selectedIndex];
  console.log(selectedOption); // get the element
  console.log(selectedOption.value); //get the value attribute
  console.log(selectedOption.innerText); // get the inner text
});

const sel = document.getElementById("select");


sel.addEventListener("change",()=>{
  let selectedOption = sel.options[sel.selectedIndex];
  console.log(selectedOption); // get the element
  console.log(selectedOption.value); //get the value attribute
  console.log(selectedOption.innerText); // get the inner text
});
<select id='select'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>

  • Related