mr_bulrathi
mr_bulrathi

Reputation: 554

Display Bootstrap modal window on submit

Sorry for noob question. I've read Show Twitter Bootstrap modal on form submit and copy-pasted some code from there, but it didn't help.

I'm trying to implement the following behavior on my page:

if 'id_field1' and 'id_field2' fields were populated, then, when user presses 'submit' button, the form must be submitted and following modal window should be displayed:

"[add another] or [redirect to other page]?".

else simple alert must be displayed ("id_field1" and "id_field2" fields must be filled)

But my code currently renders modal window if the fields were not populated, and doesn't submit anything.

html

<form method="POST">

    <input class="form-control" id="id_field1" name="field1" type="text" required="">
    <input class="form-control" id="id_field2" name="field2" type="text" required="">         

    <button type="button" class="btn btn-xl btn-success" data-toggle="modal" data-target="#myModal" id="formsubmit">Add item</button>
</form>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog modal-sm">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Item was successfully added</h4>
            </div>
            <div class="modal-body">
                <p>Add another?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Yes</button>
                <a href="some_url" class="btn btn-primary">No</a>
            </div>
        </div>
    </div>
</div>

jQuery

$(function(){
    $( "#formsubmit" ).click(function() {
        $( "form" ).submit(function(evt){

        field1 = $( '#id_field1' ).val();
        fiedl2 = $( '#id_field2' ).val();

        if((field1 === '') && (field2 === '')){
            alert("You must enter tenant's name and phone at least");
            evt.preventDefault();
        } else {
            $( '#myModal' ).modal('show');
        }
        });
    });
});

Thank you so much.

Upvotes: 0

Views: 1233

Answers (1)

fmc
fmc

Reputation: 490

You have to first set your field values to variables.

$(function(){
$( '#formsubmit' ).click(function() {
    var1 = $( '#id_field1' ).val();
    var2 = $( '#id_field2' ).val();
    if((var1 === "") && (var2 === "")) {
        alert("field1 and field2 must be populated");
        return false;
    } else {
        $( '#myModal' ).modal('show');
    }
  });
});

Updated.

Upvotes: 1

Related Questions