Issues with the HTML required attribute not functioning properly are encountered within the form when it is

I am encountering an issue with my modal form. When I click the button that has onclick="regpatient()", the required field validation works, but in the console, it shows that the data was submitted via POST due to my onclick function. How can I resolve this problem?

Below is my modal code:

<div class="modal-body">
                <form class="form-horizontal" id="frm_patientreg">
                <div class="form-group">
                  <label class="control-label col-sm-3" for="pfname">First Name:</label>
                  <div class="col-sm-7">
                    <input type="text" class="form-control" id="pafname" name="pafname" placeholder="First name" required>
                  </div>
                </div>
              ... (remaining HTML code of the modal) ...

Additionally, here is the JavaScript function that triggers when the button in the footer of my modal is clicked:

function regpatient() {
  var a = $('#psex').val();
  var b = $('#pmartialstat').val();

  if(a == "0" || b == "0") {
    alert("Please select an option");
  }
  else {
    $.ajax({
    url: siteurl+"sec_myclinic/addpatient",
    type: "POST",
    data: $('#frm_patientreg').serialize(),
    dataType: "JSON",
      success: function(data) {
        alert("Successfully Added");
        $('#frm_patientreg')[0].reset();
      }
    });
  }
}

Answer №1

If I understand correctly, you are looking to prevent the default submit action of a button and only execute your custom onclick script. Here is a possible solution:

onclick="registerPatient(event)"

and

function registerPatient(event) {
    event.preventDefault();
    ...

Update

The issue might be that the required fields are not being validated by the onclick function. Implementing checks like this for the necessary values could help in preventing unwanted ajax calls.

if (!$('#patientName').val()) {
  return alert('Please make sure all required fields are filled out.');
}
// place ajax code here ...

Answer №2

Employ this code snippet

<button value="button" onclick="regpatient()" class="btn btn-primary">Register Patient</button>

Rather than utilizing the following

<button value="submit" onclick="regpatient()" class="btn btn-primary">Register Patient</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The index "id" is not defined

Hey there, I have been working on fetching data from a JSON URL located at this link. However, I seem to be encountering an error that I can't quite comprehend. If anyone has any insights or solutions, I would greatly appreciate the help. Thank you in ...

Submitting a form with AJAX to upload an image

I am facing an issue with my form submission using Ajax where I cannot upload an image within the submit. <form id="forms-items" name="forms-items" method="post" enctype="multipart/form-data"> <input id="uploadBtn" name="uploadimg" type="file" cl ...

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

Using three.js to retrieve the camera's position using orbit controls

In my journey using three.js orbit controls, I have encountered a challenge of making a skybox follow the camera's position. Despite scouring the internet, I have not come across a suitable solution. My query is straightforward - how can I obtain the ...

Stopping the Bootstrap carousel when an input is focused

I have a Bootstrap carousel with a form inside. The carousel is set to pause when hovered over, but I noticed that if the cursor leaves the carousel while typing in the inputs, it goes back to its default cycle of 5000ms. I want the carousel to remain pau ...

Implementing the passing of value from view to controller in CodeIgniter through an onclick feature

I need to pass the button's id onclick from the view to the controller using ajax, but I keep getting this error: 500 Internal Server Error This is my view: <a data-toggle="modal"data-target="#Add_Money_to_campaign" ><button onclick="add ...

problem encountered with data not being received by Java servlet

I am having difficulty sending canned json data to a servlet using jquery ajax on the Google App Engine. Despite catching the call in the debugger and inspecting the request, I consistently find that the parameters map is null... Any assistance would be g ...

Get a webpage that generates a POST parameter through JavaScript and save it onto your device

After extensive research, I have hit a roadblock and desperately need help. My task involves downloading an HTML page by filling out a form with various data and submitting it to save the responses. Using Firebug, I can see that my data is sent over POST, ...

What is the best way to assign an identifier to a variable in this scenario?

script.js $('a').click(function(){ var page = $(this).attr('href'); $("#content").load(page); return false; }); main.html <nav> <a href="home.html">Home</a> <a href="about.html">About</a> < ...

Error: An unidentified type was encountered that is not a functioning element within an anonymous PHP JavaScript function

Hello everyone, I am seeking help with a JavaScript error that is causing some trouble. Whenever I try to sort a table and implement pagination in PHP, I get an error message in the console stating "Uncaught TypeError: undefined is not a function." Despite ...

Troubleshooting: Issue with onclick event in vue.js/bootstrap - encountering error message "Variable updateDocument not found"

As a newcomer to frontend development, I have a basic understanding of HTML5, CSS, and Javascript. Recently, I started working on a vue.js project where I integrated bootstrap and axios. Everything seemed to be working fine until I encountered an issue whe ...

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...

Retrieving data from a stored procedure with XSJS and storing it in a variable

I am currently facing a situation where I need to pass a session user as a parameter to a stored procedure in order to retrieve a receiver value. This receiver value needs to be stored in a variable so that I can use it in another function within an xsjs f ...

Arrange Raphael Objects in Their Relative Positions

I've been experimenting with Raphael.js recently and I've encountered an issue related to the positioning of each Raphael object. My goal is to create multiple 'canvases' without having them overlap within a predefined div on the page. ...

Harmonize the timing of three ajax requests

Is there a way to simultaneously display data from three AJAX requests that are fired one after another? I want to echo back all the data at the same time. $.ajax ({ type: "POST", url: "page1.php", data: "var1=" + var1, suc ...

Only carry out a redirect to the specified page if the successRedirect is present in the passport.authenticate function

Encountering some difficulties with a Node Express app. After removing the successRedirect property in the auth method by passport, it fails to redirect. The below code does not redirect to the desired page when the successRedirect is removed and replaced ...

Re-attaching JQuery Slimbox after an AJAX response

After loading ajax content, I am facing issues with rebinding slimbox2. I understand that I have to rebind the function during the ajax load process, but I'm unsure how to accomplish that. Below is the code I am using to generate external content. $( ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Unable to find the module... designated for one of my packages

Within my codebase, I am utilizing a specific NPM package called my-dependency-package, which contains the module lib/utils/list-utils. Moreover, I have another package named my-package that relies on my-dependency-package. When attempting to build the pr ...