简体   繁体   中英

javascript onsubmit redirect fail

This script works as shown.

I want to replace:

alert(q2) ;

with:

window.location.href = q2 ;

to redirect, but it doesn't work.

    <form onSubmit=" var q = document.getElementById('addTable') ; var q2 = 'http://www.mysite.com/add/' + q.options[q.selectedIndex].text + '/' ; alert (q2) ; ">

    Add a new record in 
    <select id="addTable">

    <option value="" >[choose a table]</option>
    <option value="articles" >articles</option>
    <option value="blogs" >blogs</option>

    </select>
    <input type="submit" value="go">
    </form>

You need to return false; (or use event.preventDefault(); ) from your handler. Also, I suggest binding a handler, and not using inline JavaScript.

<form id="addForm">
   Add a new record in 
   <select id="addTable">
     <option value="">[choose a table]</option>
     <option value="articles">articles</option>
     <option value="blogs">blogs</option>
   </select>
   <input type="submit" value="go">
</form>

<script type="text/javascript">
   document.getElementById('addForm').addEventListener('submit', function(e){
      e.preventDefault();
      var q = document.getElementById('addTable'),
      q2 = 'http://www.mysite.com/add/' + q.options[q.selectedIndex].text + '/';
      window.location.href = q2;
   });
</script>

it would be better to do this as follows

<script>
 function go(){
 var q = document.getElementById('addTable') ; var q2 = 'http://www.site.com.au/add/' +     q.options[q.selectedIndex].text + '/' ; window.location=q2 ;
}
</script>

<form>

    Add a new record in 
    <select id="addTable">

    <option value="" >[choose a table]</option>
    <option value="articles" >articles</option>
    <option value="blogs" >blogs</option>

    </select>

    <input type="button" value="go" onclick="go()">
    </form>

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