0

I'm pretty new to JavaScript and I've been fiddling around with this dropdown menu below.

<form id="bootstrapSelectForm" method="post" class="form-horizontal">
        <div class="form-group">
        <label class="col-xs-3 control-label">Time period</label>
        <div class="col-xs-5 selectContainer">
            <select name="time" class="form-control">
                <option value="all">All</option>
                <option value="1month">1 month</option>
                <option value="2months">2 months</option>
                <option value="3months">3 months</option>
                <option value="6months">6 months</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary btn-sm">Ok</button>
    </div>
</form>

<script type="text/javascript">
    function submitClick() {
        // Somehow fetch data from dropdown
    }
</script>

What I want to do is to retrieve the name/value of the selected item in the dropdown when clicking on the "submit" button and then do something with that value. But I'm a little lost at where to begin with this and any hint or help is greatly appreciated.

Khaine775
  • 2,715
  • 8
  • 22
  • 51

2 Answers2

1

There will be an event passed to your form submit function that will contain all the fields of the form in an array property of the event. You can look through that event via console.log(event) in order to get at what those properties are. In your case the select field will actually be the first element in the properties array of the event since it's the first form element.

So you want something more like this:

<script type="text/javascript">
    function submitClick(event) {
        //prevent the page from posting when you submit the form
        event.preventDefault();

        //print the value of the select field
        console.log(event[0]);
    }
</script>

Another thing to keep in mind is that you have to add an event listener to the form for this function to trigger. So somewhere in your code you will need something like:

document.getElementById("bootstrapSelectForm").addEventListener("submit", submitClick);
Jason
  • 31,834
  • 7
  • 59
  • 78
1

Take a look at this: Get selected value in dropdown list using JavaScript? I would suggest that you take a look at jQuery too as its much simpler and easier to understand. for example getting the value of a drop down can be done in 1 simple line of code. like this: $('#id_of_select_tag').find('option:selected').val();

Community
  • 1
  • 1