felix001
felix001

Reputation: 16691

Django / Jquery Form Submission

Im trying to create a simple input box with form validation, but im not 100% sure how issue a post to a URL if successful. Im not 100% sure if I need to issue the post just within the jquery script or if I also need to amend anything within the views.py file...

<html>
 <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>

<body>

<script src="{{ STATIC_URL }}js/jquery.js"></script>

<script type="text/javascript">
jQuery(function(){
        $("#btn-search").click(function(){
        $(".error").hide();
        var hasError = false;
        var searchReg = /^[a-zA-Z0-9-]+$/;
        var searchVal = $("#search-text").val();
        if(searchVal == '') {
            $("#search-text").after('<span class="error">Please enter a search term.</span>');
            hasError = true;
        } else if(!searchReg.test(searchVal)) {
            $("#search-text").after('<span class="error">Enter valid text.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
                            else {
                                    $("#search-text").after('<span class="error">Search term accepted.</span>');
                                    return false;
                            }
    });
});
</script>

<form method="post" name="form1" action="/whatmask_output/">
{% csrf_token %}
     <fieldset>
          <div><label>Search:</label><input type="text" name="search-text" id="search-text" value="" size="32" /></div>
          <div><label></label><input type="submit" value="Submit" id="btn-search" /></div>
     </fieldset>
</form>

</body>
</html>

Any ideas ??

Upvotes: 1

Views: 995

Answers (2)

Blazemonger
Blazemonger

Reputation: 92893

Two things to change. First, replace

$("#btn-search").click(function(){

with

$("form").submit(function(){

since it's possible to submit a search form by hitting return/enter within the text box, bypassing the button entirely.

Second, change

else {
    $("#search-text").after('<span class="error">Search term accepted.</span>');
    return false;
}

to

else {
    $("#search-text").after('<span class="error">Search term accepted.</span>');
    return true;
}

This should allow the submit to proceed without further intervention.

Upvotes: 1

John Fable
John Fable

Reputation: 1091

Give your form an id:

<form method="post" id="form1" name="form1" action="/whatmask_output/">

And whenever you are ready to submit use:

$('#form1').submit();

Upvotes: 0

Related Questions