Moe
Moe

Reputation: 470

Twitter bootstrap set field from dropdown

I'm using twitter bootstrap for front end. I have a text field and a drop down menu next to it:

 <div class="input-group">
     <input type="text" class="form-control" name="opening_hr" id="opening_hr" required>

      <div class="input-group-btn">
      <button type="button" class="btn btn-default dropdown-toggle"
      data-toggle="dropdown"><span class="caret"></span></button>
      <ul class="dropdown-menu pull-right" id="opening_hr_select">

      @foreach($hours as $hour)
         <li><a>{{$hour}}</a></li>
      @endforeach

   </ul>
 </div>

I've tried created a javaScript function which takes two parameters the text field I want to edit and the drop down menu that has been selected:

 $(function(){

   $(".dropdown-menu li a").click(function(){

   var elem = document.getElementById("opening_hr");

   elem.text($(this).text());
   elem.val($(this).text());
 });

 });

the above is simpler function without parameter I tried testing (no luck). what I would like to achieve is to take the selected value and set it as the text field value.

please help, thank you.

Upvotes: 0

Views: 260

Answers (3)

Moe
Moe

Reputation: 470

Found a simple way to achieve what I want done, without the use jQuery or JavaScript. The following is my solution:

<!-- Opening times -->
     <div class="row">
        <div class="col-lg-3">
           <label for="opening_time">Opening Time</label>

                 <div class="input-group">
                  <span class="input-group-addon">Hour</span>
                  <input type="number" max="24" min="1" class="form-control" name="opening_hr"
                                       id="opening_hr"
                                       required>

                   <span class="input-group-addon">Minute</span>
                   <input type="number" max="60" min="0" class="form-control" name="opening_min"
                                       id="opening_min"
                                       required>
                   </div>
         </div>
      </div>

Upvotes: 0

chris342423
chris342423

Reputation: 451

I recommend to dig deeper into Jquery. One of its Main Features is the Support of selectors, so in you use Jquery you should use it to Access a DOM Element rather than using getelementbyid.

ps: my ipad hates capitals, sorry.

Upvotes: 0

Gruff Bunny
Gruff Bunny

Reputation: 27986

The problem is that the variable elem is not a jQuery object so trying to call val will not work. As you are already using jQuery, change the elem assignment to:

var elem = $("#opening_hr");

and to set the input use:

elem.val($(this).text());

or combine them together:

$("#opening_hr").val( $(this).text() )

Upvotes: 1

Related Questions