Jquery / Javascript change form action based on input field

前端 未结 4 926
傲寒
傲寒 2021-01-07 02:51

I have a form like this


    
    
相关标签:
4条回答
  • 2021-01-07 03:32

    First get your input, and then update the action. Return true if you want to form to submit after changing the value, or false if these are separate buttons.

    <button onclick="changeVal($('input').val()">change value</button>
    <script>
        function changeVal(value){
        $("form").attr("action",'http://mysite.com/'+value+'.html');
        return true;
        }
    </script>
    

    Be careful doing things like this, as if you use this solution you will be opening yourself up to javascript injection attacks. You'll want to "scrub" your input before injecting it into your form.

    0 讨论(0)
  • 2021-01-07 03:37

    You can do this, you will need to add ids to items. One thing you might want to do is validate the users input.

    HTML

    <form action='' name='myform' id="myform" method='POST'>
      <input type='text' name='cars' id="cars">
      <button action='submit'>Search Cars</button>
    </form>
    

    jQuery

    $('#myform').submit(function(){
      var car = $('#cars').val();
      $(this).attr('action', "http://www.mysite.com/" + car + ".html");
    }); 
    

    EDIT: It is best to be javascript at bottom of page;

    FULL

    <!DOCTYPE HTML>
    <html lang="en-US">
    <head>
      <meta charset="UTF-8">
      <title></title>
    </head>
    <body>
      <form action='' name='myform' id="myform" method='POST'>
        <input type='text' name='cars' id="cars">
        <button action='submit'>Search Cars</button>
      </form>
      <script src="path-to-jquery"></script>
      <script>
      // Shorthand for $(document).ready();
      $(function() {
       $('#myform').submit(function(){
         var car = $('#cars').val();
         $(this).attr('action', "http://www.mysite.com/" + car + ".html");
       });
      });
     </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-07 03:37

    You need to get the value from the input field and populate the xyz value.. Try this

    $('#myForm').submit(function() {
    
        var value = $('input[type="text"]').val(); 
    
        this.action = 'http://mysite.com/' + value + '.html';
        return true;
    }
    
    0 讨论(0)
  • 2021-01-07 03:40

    You can do it as follows:

    $('#myForm').submit(function() {
        this.action = 'http://mysite.com/<xyz>.html';
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题