form action with javascript

后端 未结 4 1270
半阙折子戏
半阙折子戏 2020-12-05 02:12

I have a form that must execute a javascript function on submit, the function then posts data to my php send mail file and the mail is sent. But it only works in fire fox. T

4条回答
  •  执笔经年
    2020-12-05 02:57

    Absolutely valid.

        

    So for a short answer: yes, this is an option, and a nice one. It says "when submitted, please don't go anywhere, just run this script" - quite to the point.

    A minor improvement

    To let the event handler know which form we're dealing with, it would seem an obvious way to pass on the sender object:

        

    But instead, it will give you undefined. You can't access it because javascript: links live in a separate scope. Therefore I'd suggest the following format, it's only 13 characters more and works like a charm:

          
    

    ... now you can access the sender form properly. (You can write a simple "#" as action, it's quite common - but it has a side effect of scrolling to the top when submitting.)

    Again, I like this approach because it's effortless and self-explaining. No "return false", no jQuery/domReady, no heavy weapons. It just does what it seems to do. Surely other methods work too, but for me, this is The Way Of The Samurai.

    A note on validation

    Forms only get submitted if their onsubmit event handler returns something truthy, so you can easily run some preemptive checks:

        
    

    Now isMyFormValid will run first, and if it returns false, server won't even be bothered. Needless to say, you will have to validate on server side too, and that's the more important one. But for quick and convenient early detection this is fine.

提交回复
热议问题