如何使选择选项标签填充与url的动作属性,使其可以打开该网站

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

本文关键字:网站 属性 标签 选项 选择 何使 填充 url      更新时间:2023-09-26

我需要得到选项值来填写表单中的动作属性,这样它就可以打开一个网站。我的代码不工作。要完成这个过程还缺少什么?

<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>

我需要得到选项值来填写表单中的动作属性,这样它就可以打开一个网站。我的代码不工作。要完成这个过程还缺少什么?

<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>

不妨试试:

$('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();
    }
})

希望有帮助!