-1

I have a form on my page, the user has the option to select from the dropdown and then click a 'Log' button.

On the click I want my JS to run and pass the value selected through into the payload for my slack webhook.

i.e. If option 3 was select and the user clicks 'Log'

var text = [Answered – not oncall – assisted with issue]

HTML

Select Options

<select name="option" id="option_id">
<option value="1">[No number listed]</option>
<option value="2">[Not answered]</option>
<option value="3">[Answered – not oncall – assisted with issue]</option>
<option value="4">[Answered – not oncall – unavailable]</option>
<option value="5">[Answered – oncall - unavailable]</option>
<option value="6">[Answered – oncall - available]</option>
</select>

Button

<button name="Log" type="submit" id="Log-submit" data-submit="...Sending">Log</button>

JS

$(document).ready(function() {
  $('#Log-submit').on('click', function(e) {
    e.preventDefault();
    var btn = $(e.target);
        btn.attr("disabled", "disabled"); // disable button
    var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    var text = // My Option that I selected goes here
    $.ajax({
      data: 'payload=' + JSON.stringify({
        "text": text
      }),
      dataType: 'json',
      processData: false,
      type: 'POST',
      url: url
    });
  });
});
Luke Toss
  • 356
  • 5
  • 23
  • Possible duplicate of [jQuery Get Selected Option From Dropdown](https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) – CBroe Sep 04 '17 at 13:25

2 Answers2

1

Someething like that could help you :

 $("select#option_id>option:selected").text();
Stéphane Ammar
  • 1,454
  • 10
  • 17
1

You need to use $("#option_id option:selected").text(); to get the selected text:

$(document).ready(function() {
  $('#Log-submit').on('click', function(e) {
    e.preventDefault();
    var btn = $(e.target);
        btn.attr("disabled", "disabled"); // disable button
    var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    var text = $("#option_id option:selected").text();
    console.log(text);
    $.ajax({
      data: 'payload=' + JSON.stringify({
        "text": text
      }),
      dataType: 'json',
      processData: false,
      type: 'POST',
      url: url
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="option" id="option_id">
<option value="1">[No number listed]</option>
<option value="2">[Not answered]</option>
<option value="3">[Answered – not oncall – assisted with issue]</option>
<option value="4">[Answered – not oncall – unavailable]</option>
<option value="5">[Answered – oncall - unavailable]</option>
<option value="6">[Answered – oncall - available]</option>
</select>


<button name="Log" type="submit" id="Log-submit" data-submit="...Sending">Log</button>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35