Jquery / Javascript change form action based on in

2020-07-24 03:45发布

问题:

I have a form like this

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

What I want to do is change the form action to be something like action='http://www.mysite.com/<cars_value>.html'> based on whatever is filled into the input field (which is populated by autocomplete).

Is there an easy way of doing this? I can do it with a <select> easily enough but the customer wants an input field instead!

回答1:

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>


回答2:

You can do it as follows:

$('#myForm').submit(function() {
    this.action = 'http://mysite.com/<xyz>.html';
    return true;
}


回答3:

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


回答4:

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.