Search code examples
jquerytwitter-bootstrap-3html-selectdropdown

Show a bootstrap modal if option is selected or else open url


Im trying to combine two different functions of jquery in to one function.

First funtion is when a dropdown is selected then if the "value" is a URL then jump to that URL but if the dropdown do not have a URL then check if it got a modal that it can open!

$(function() {
  // bind change event to select
  $modal = $('#LoginRegister');
  if ($(this).val() === 'LoginRegister') {
    $modal.modal('show');
  } else {
    $('#designselectedchange').on('change', function() {
      var url = $(this).val(); // get selected value
      if (url) { // require a URL
        window.location = url; // redirect
      }
      return false;
    });
  }
});
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<select title="Select Design" class="selectpicker" id="designselectedchange" name="design">
  <option value="/frequently-asked-questions/index.html?question=client-id-register-login-view-progress-previous-order-quotations">pop up</option>
  <option value="LoginRegister">Login modal</option>
</select>

<div class="modal fade" id="LoginRegister" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Login/Register</h4>
      </div>
      <div class="modal-body">
        test
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->


Solution

  • Simpler solution - test the first char for being an ID:

    $(function() {
      $('#designselectedchange').on('change', function() {
        var val = $(this).val();
        if (val) {
          if (val.indexOf("#") === 0) $(val).modal('show');
          else window.location = val;
        };
      });
    });
    
    <select title="Select Design" class="selectpicker" id="designselectedchange" name="design">
      <option value="/frequently-asked-questions/index.html">pop up</option>
      <option value="#LoginRegister">Login modal</option>
    </select>