简体   繁体   中英

How to make the select option tag fill the action attribute with an url so it can open that website

I need to get the option value to fill in the action attribute in the form so it can open up a website. My code doesn't work. What is missing to complete the process?

<form action=" " name="test">
 <select name="url">
  <option value="google">google</option>
  <option value="yahoo">yahoo</option>
 </select>
<input type="submit"/>
</form>

<script>
 $("form").submit(function () {
 var selectVal = $('select').value();
 var url = '';
  if(selectVal == "google") url = 'http://www.google.com';
  else if(selectVal == "yahoo") url = 'http://www.yahoo.com';

  if(url != ''){
    window.open(url, '_blank');
  }
   }); 
 </script>

Maybe try this:

$('form').on('click', '[type=submit]', function(e) {
    e.preventDefault();
    // Get the selection option val
    var form = $(this).parents('form');
    var selectVal = $form.find('select').find(':selected').val();
    var url = '';
    switch (selectVal) {
       case 'google':
            url = 'google.com';
       break;
       case 'yahoo':
            url = 'yahoo.com';
       break;
    }

    if (url) {
       form.attr('action', url);
       form.submit();
    }
})

Hope that helps!

I need to get the option value to fill in the action attribute in the form so it can open up a website. My code doesn't work. What is missing to complete the process?

<form action="">
 <select name="url">
    <option value="https://www.google.com">google</option>
    <option value="https://www.yahoo.com">yahoo</option>
 </select>
    <input type="submit"/>
 </form>

 <script>
  function SetData(){
  var select = document.getElementById('url');
  var test_id = select.options[select.selectedIndex].value;
  document.form.action = test_id;
  form.submit();
  }
 </script>

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