How to run a function that added to onsubmit attribute by jquery attr

I'm working on a page, and I want to do something when form submitted; This is the form:

<form class="tsf" action="/search" style="overflow:visible" id="tsf" method="GET" name="f" onsubmit="return q.value!=''" role="search">

I just wrote this code to add a new function before return q.value!=''

$("#tsf").attr('onsubmit', "do_something(); return q.value!=''");

And I defined do_something after that:

function do_something(){
   alert("success");
}

But console return an error:

Uncaught ReferenceError: do_something is not defined

How can I call and run this function (do_something) using this way?

Note: For some reasons, I'm only able to add my function to onsubmit and I am just looking for a way to run do_something() in this way!

Answers 1

  • Maybe you can set it off first and then create a new handler

    function do_something(){
       alert("success");
    }
    function attachNewMethod()
    {
      $('#tsf').prop('onclick',null).off('click');
      $("#tsf").attr('onsubmit', "do_something(); return q.value!=''");
    }
    

    Updated fiddle


Related Articles