Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot change form action via jquery

I'm trying to change my form action to another link during submit using jquery. Please view the following code:

javascript

$(document).ready(function(){
    $("form[name='search']").submit(function(e){
        var submit=$(this);
        submit.attr('action','?search='+submit.find("input[name='tsearch']").val());
    });
});

HTML/PHP

    <form name="search" method="post">
          <input class="inputbox" type="text" name="tsearch" value="<?php echo $text_search; ?>" />

Though i can't seem to get it working. Any help here will be appreciated.

like image 627
Lawrence Avatar asked Dec 05 '25 02:12

Lawrence


2 Answers

Here's a working example: http://jsfiddle.net/RmKDT/4/

You can see by the alerts that the action is changing. You just need to resubmit the form as well.

Edit: Fixed potential infinite loop

$(function(){

  var submitted = false;
  $('form').submit(function(e){

    if (submitted == true) {

      return;

    }
    e.preventDefault();
    var action = $(this).attr('action');

    alert(action);

    $(this).attr('action', 'two.php');
    action = $(this).attr('action');

    alert(action);

    submitted = true;
    // resubmit the form
    $(this).submit();

  });

});
like image 107
mynewaccount Avatar answered Dec 07 '25 15:12

mynewaccount


Your code seems to be fine. There are a few things you can try to get this working.

  1. Be sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file else in the html head section

  2. Be sure that you've included the datatale script after you've included jQuery, as it is most certainly dependant upon that.

  3. Check whether jQuery is included properly and once only.

  4. Watch out for jQuery conflicts. There is some other library which is overridding $, so your code is not working because $ is not an alias for jQuery anymore. You can use jQuery.noConflict() to avoid conflicts with other libraries on the page which use the same variable $.

  5. alert('?search='+submit.find("input[name='tsearch']").val()) see whether you are getting the value you want.

like image 29
Techie Avatar answered Dec 07 '25 15:12

Techie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!