admin管理员组

文章数量:1123773

I have a very simple HTML form like this:

<form id="assessment" name="assessment" hx-post="/assessment-result.php"
    hx-target=".questions_list" hx-swap="outerHTML transition:true swap:200ms"
    onsubmit="return checkAnswers(event);">
    ...
</form>

And also a very simple JS function that validate this form:

<script>
    function checkAnswers(event) {
        event.preventDefault();

        if(invalid){
            alert('Invalid form');
            return false;
        }else{
            return true;
        }
    }
</script>

The problem is, even if checkAnswers() return false, the form is still submitted.

  • I tried using hx-on:submit=checkAnswers(event), it still didn't work.
  • I tried adding hx-trigger="submit" and it still didn't work.

Can anyone please give a simple example that make it just work?

Thank you very much in advance for your help.

I have a very simple HTML form like this:

<form id="assessment" name="assessment" hx-post="/assessment-result.php"
    hx-target=".questions_list" hx-swap="outerHTML transition:true swap:200ms"
    onsubmit="return checkAnswers(event);">
    ...
</form>

And also a very simple JS function that validate this form:

<script>
    function checkAnswers(event) {
        event.preventDefault();

        if(invalid){
            alert('Invalid form');
            return false;
        }else{
            return true;
        }
    }
</script>

The problem is, even if checkAnswers() return false, the form is still submitted.

  • I tried using hx-on:submit=checkAnswers(event), it still didn't work.
  • I tried adding hx-trigger="submit" and it still didn't work.

Can anyone please give a simple example that make it just work?

Thank you very much in advance for your help.

Share Improve this question asked yesterday Ellery LeungEllery Leung 6553 gold badges12 silver badges24 bronze badges 1
  • Do you need one more return? return return false?. Also are you sure the method is running? The alert is triggering? – Tushar Shahi Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 0

Thank you for all your effort. I found the answer: Use htmx:confirm instead of hx-on:submit:

<form id="assessment" name="assessment" 
    hx-post="/assessment-result.php"
    hx-target=".questions_list" 
    hx-swap="outerHTML transition:true swap:200ms" 
    hx-trigger="submit"
    hx-include=".questions_list input[type=radio]:checked">
...
</form>
document.body.addEventListener('htmx:confirm', (event) => {
        event.preventDefault();

        if( invalid ) {
            swal('Invalid form');
        }else{
            // https://htmx.org/events/#htmx:confirm
            // true to skip the built-in window.confirm()
            event.detail.issueRequest(true);
        }
});

本文标签: How to validate form submission using HTMXStack Overflow