简体   繁体   中英

How can I record the value of a bootstrap dropdown menu after submit is pressed?

My form has one dropdown menu and 4 text input boxes. When the form is submitted, I need to console.log all the values. So far no problem with the text boxes but I can't record the number selected on the drop down menu. Can someone please help thanks in advance.

This is my html:

  <div class="container-of-forms">
      <div class="dropdown">
        <button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
          2
          <span class="caret"></span>
        </button>
        <ul id="list" class="dropdown-menu dropdown-info" aria-labelledby="dropdownMenu1">
          <li><a href="#">2</a></li>
          <li><a href="#">3</a></li>
          <li><a href="#">4</a></li>
        </ul>
      </div>

      <!-- Text Input Boxes -->
      <div class="container-inner">
        <input class="text-input-box" id="choice1" type="text" name="" value="" placeholder="Choice 1"> <br>
        <input class="text-input-box" id="choice2" type="text" name="" value="" placeholder="Choice 2"> <br>
        <input class="text-input-box invisible threeChoices" id="choice3" type="text" name="" value="" placeholder="Choice 3"> <br>
        <input class="text-input-box invisible fourChoices" id="choice4" type="text" name="" value="" placeholder="Choice 4">
      </div>
    </div>

And this is the javascript:

document.getElementById("submit").addEventListener("click", function(e) {
  e.preventDefault();
  var choice1 = $("#choice1").value;
  var choice2 = $("#choice2").value;
  var choice3 = $("#choice3").value;
  var choice4 = $("#choice4").value;
  var numberOfChoices = $("#dropdownMenu").value;
  console.log(numberOfChoices);}

But it is not printing the numberOfChoices...please help...thanks

The issue is that we're attempting to access the value of a button which has no value attribute set.

We might suggest setting the value , but in this case as you're using a third-party control, let's just access the text inside the button instead:

var numberOfChoices = $("#dropdownMenu").text();

Note that text() will return all text of the selected node and all descendents, which in this case includes the caret span which has no inner text, thus returning just the selected "value" from the bootstrap dropdown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM