Onchange open URL via select - jQuery

前端 未结 14 1163
长情又很酷
长情又很酷 2020-11-27 10:15

What would be the best way to attach an event so on change of a select option a URL. Store the href in an attr and grab it on change?

14条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 11:01

    It is pretty simple, let's see a working example:

    
    
    
    

    $(function() {
      // bind change event to select
      $('#dynamic_select').on('change', function() {
        var url = $(this).val(); // get selected value
        if (url) { // require a URL
          window.location = url; // redirect
        }
        return false;
      });
    });
    
    
    
    

    .

    Remarks:

    • The question specifies jQuery already. So, I'm keeping other alternatives out of this.
    • In older versions of jQuery (< 1.7), you may want to replace on with bind.
    • This is extracted from JavaScript tips in Meligy’s Web Developers Newsletter.

    .

提交回复
热议问题