0

My event.preventdefault is not working. Actually I want when the user clicks the add button, it will ask to "enter the field first" if all the field are blank.

For this, I use the flag like this to prevent the data saved if all fields are blank as below: (also when i click the button it shows enter the field and after that it will go to ajax function even i applied event.preventdefault(); I don't know exactly where I am wrong)

Thanks in advance,

Here is my code:

 <tr>
        <td>
            <button type="button" name="add">     //this is my add button
                Add
            </button>
        </td>
   </tr>
       $("#tabs").tabs();
       $("button").button();
       $("button").click(function(event){
            var flagg=0;
            if( $("#patient_name").val() == "" )
            {
                flagg=1;
            }
            if(flagg == 1)
            {
                alert("enter the patient name!!");
                event.preventDefault();
            }

        form_name = $(this).parents("form").attr('name');
        var params    = $("#" + form_name).serialize();
        params=params.replace(/&/g,'~^~^^');
        table_name = "patient_info";
        button_name = "temp";

        $.ajax({
             type: "POST",
             url: "ajax1.php",
             data: "params=" + params + "&button_name=" + button_name,
             success: function(msg){
                 //alert(msg);
                if (msg == "true")
                {
                    alert("Patient data sucessfully saved!");
                    window.location.replace("ivf2.php?id=" + $("#id").val());
                }   
                else    
                {
                    //alert("Failed to save, please check and try again!");
                }
        }
        });
  });

2 Answers 2

1

event.preventDefault simply stops any other attached event from running (e.g. something in onclick or href). It doesn't make your own javascript code stop.

Do this:

if(flagg == 1)
    {
        alert("enter the patient name!!");
        event.preventDefault();
        return;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

At the line if(flagg == 1) you are calling the event.preventDefault(), but then you are continuing on with your ajax post. At that point you want to return via return; from your click handler so that it does not continue submitting the form.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.