I am trying to create a form that, if you do not fill out any of the fields, will show an alert message if you hit submit. I am trying to work with angular validation to make this happen; however, it is not working at all. Here is the code I currently have:
(1) HTML Event Form file
function mainController($scope, $http) {
$scope.formData = {};
$http.get('/api/events')
.success(function(data) {
$scope.events = data;
initMap(data);
for(i = 0; i < data.length; i++){
console.log(data[i].eventLocation);
//placeMarker(data[i]);
//test(data);
}
//placeMarker(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createEvent = function() {
$http.post('/api/events', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.events = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}
// ATTEMPT AT FORM VALIDATION
$scope.validateForm = function() {
if (document.getElementById("inputName").value == "" || document.getElementById("inputType").value == "" || document.getElementById("inputLocation").value == "" || document.getElementById("inputDetails").value == "") {
alert("Please fill in all required fields!");
return false;
}
}
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="col-lg-6">
<!-- Validate form -->
<form name="myForm" onsubmit="return validateForm()">
<div class="form-group">
<label>Event Name</label>
<input type="text" name="inputName" class="form-control" ng-model="formData.eventName" placeholder="Event name">
</div>
<div class="form-group">
<label>Type</label>
<select class="form-control" id="inputType" ng-model="formData.eventType">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
</div>
<div class="form-group">
<label>Location</label>
<select class="form-control" id="inputLocation" ng-model="formData.eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label>Event Details</label>
<textarea class="form-control" name="inputDetails" ng-model="formData.eventDetails" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button id="add-event"type="submit" class="btn btn-primary" ng-click="createEvent()">Submit</button>
</div>
</form>
you can do this using ng-submit for form validation
<form name="myForm" ng-submit="validateForm()">
and for the validation use ng-model variable to validate the form
$scope.validateForm = function() {
if (!$scope.formData.eventName || !$scope.formData.eventType ) {
alert("Please fill in all required fields!");
return false;
}
Demo
Do angularjs way. https://scotch.io/tutorials/angularjs-form-validation
angular.module('exApp', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.save = function(invalid){
if(!invalid){console.log('Form Submitted');}
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="exApp" ng-controller="ctrl">
<div>
<form name="form" class="css-form" novalidate>
<label>Name:
<input type="text" ng-model="name" name="userName" required="" />
</label>
<br />
<div ng-show="form.$submitted || form.userName.$touched">
<div ng-show="form.userName.$error.required">Tell us your name.</div>
</div>
<label>E-mail:
<input type="email" ng-model="email" name="userEmail" required="" />
</label>
<br />
<div ng-show="form.$submitted || form.userEmail.$touched">
<span ng-show="form.userEmail.$error.required">Tell us your email.</span>
<span ng-show="form.userEmail.$error.email">This is not a valid email.</span>
</div>
Gender:
<label><input type="radio" ng-model="gender" value="male" />male</label>
<label><input type="radio" ng-model="gender" value="female" />female</label>
<br />
<label>
<input type="checkbox" ng-model="agree" name="userAgree" required="" />
I agree:
</label>
<input ng-show="agree" type="text" ng-model="agreeMe" required="" />
<br />
<div ng-show="form.$submitted || form.userAgree.$touched">
<div ng-show="!agree || !agreeMe">Please agree and sign.</div>
</div>
<input type="button" value="Reset" />
<input type="submit" value="Save" ng-disabled="form.$invalid || form.$pristine" ng-click="save(form.$invalid)" />
</form>
</div>
Angular provides some help when using forms. It provides different objects to the form. They are very helpful while validating forms:
$pristine: true, if the user has not interacted with the form yet
$dirty: true, if the user has interacted with the form
$valid: true, if all controls are valid
$invalid: true, if at least one control is invalid
$error: it contains references to all invalid controls
You can use this object through the form object, in your case myForm. So you can check if the user fills any field using:
$scope.validateForm = function(myForm) {
if(myForm.$pristine) {
alert("Please fill in all required fields!");
}
}
Try this :
Add ng-submit into your element with myForm.$valid condition.
Add one ng-click="submitted=true" event on submit button that will trigger when click on the submit button.
Add required attribute in all the input fields or mandatory fields.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.validateForm = function() {
alert("submitting");
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="myForm" ng-submit="myForm.$valid && validateForm()" novalidate>
<p ng-show="submitted==true && myForm.inputName.$invalid">Event name is missing.</p>
<p ng-show="submitted==true && myForm.inputType.$invalid">Event type is missing.</p>
<p ng-show="submitted==true && myForm.inputLocation.$invalid">Event Location is missing.</p>
<p ng-show="submitted==true && myForm.inputDetails.$invalid">Event details is missing.</p>
<div class="form-group">
<label>Event Name</label>
<input type="text" name="inputName" class="form-control" ng-model="formData.eventName" required placeholder="Event name">
</div>
<div class="form-group">
<label>Type</label>
<select class="form-control" name="inputType" id="inputType" ng-model="formData.eventType" required>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
</div>
<div class="form-group">
<label>Location</label>
<select class="form-control" name="inputLocation" id="inputLocation" ng-model="formData.eventLocation" required>
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label>Event Details</label>
<textarea class="form-control" name="inputDetails" ng-model="formData.eventDetails" rows="2" placeholder="Add details about your event" required></textarea>
</div>
<div class="text-center">
<button id="add-event"type="submit" class="btn btn-primary" ng-click="submitted=true">Submit</button>
</div>
</form>
</div>
Related
I have a form with more than 10 input/select options but i wish to show most of this form inputs when 4 of my fields specifically are filled.
I've done some research and found
$('input[type="text"]').each(function(){
// do my things here...
});
but this has 2 issues:
It doesn't work when i fill inputs
One of my fields is select option and here only tries to get inputs
Code
$(function() {
// show choices DIV only if all fields are filled.
$('input[type="text"]').each(function() {
if ($(this).val() != "") {
$('.choices').show();
} else {
$('.choices').hide();
}
});
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<form action="" method="POST">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<div class="sm-form-design">
<input id="seq_no" type="text" class="form-control" name="seq_no" required>
<label for="seq_no" class="control-label">Seq No.</label>
</div>
</div>
</div>
<div class="col-md-9">
<div class="form-group">
<div class="sm-form-design">
<input id="question" type="text" class="form-control" name="question" required>
<label for="question" class="control-label">Question</label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 sm-form-design">
<select name="type" id="type" class="form-control">
<option value="dropdown">Dropdown</option>
<option value="multiple">Multiple</option>
<option value="radio">Radio Buttons</option>
<option value="input">Input</option>
</select>
<label for="type" class="control-label">Type</label>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="sm-form-design">
<input type="text" name="quiz_time" class="form-control" id="masked-input-time" required>
<label for="quiz_time" class="control-label">Time *</label>
</div>
</div>
</div>
</div>
<!-- show this part when all fields above are filled -->
<div class="row choices">
<div class="col-md-12">
<h5>Choices:</h5>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
Question
How can I validate all my first 4 fields before showing rest of the form?
Any idea?
While Shiladitya's answer works, and is closest to your own code, I find it cleaner to handle forms by serializing data into an object as input occurs. This allows you to more easily reason about validation, as you only have to validate an object, not DOM elements.
Here is a pared down example:
$(function() {
const formData = {}
const $form = $('#form-a')
const $partTwo = $('#part-2')
// some real validation here
const isValidPartOne = data =>
data.a && data.b && data.c
const showPartTwo = () => $partTwo.show()
$form.on('input', ({target}) => {
formData[target.name] = target.value
// form data is available at all times
console.log('formData =', formData)
if (isValidPartOne(formData)) {
showPartTwo()
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form-a">
<div id="part-1">
PART 1
<input name="a" />
<input name="b" />
<select name="c">
<option value="" disabled selected>Choose One</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
</div>
<div id="part-2" style="display:none;">
PART 2
<input name="d" />
</div>
</form>
Here you go with a solution
$(function() {
$('.choices').hide();
// show choices DIV only if all fields are filled.
$('select').change(function() {
validateInput();
});
$('input[type="text"]').keyup(function() {
validateInput();
});
function validateInput() {
var valid = true;
$('input[type="text"], select').each(function() {
if ($(this).val() === "") {
valid = false;
}
});
if (valid) {
$('.choices').show();
} else {
$('.choices').hide();
}
}
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<form action="" method="POST">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<div class="sm-form-design">
<input id="seq_no" type="text" class="form-control" name="seq_no" required>
<label for="seq_no" class="control-label">Seq No.</label>
</div>
</div>
</div>
<div class="col-md-9">
<div class="form-group">
<div class="sm-form-design">
<input id="question" type="text" class="form-control" name="question" required>
<label for="question" class="control-label">Question</label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 sm-form-design">
<select name="type" id="type" class="form-control">
<option value="dropdown">Dropdown</option>
<option value="multiple">Multiple</option>
<option value="radio">Radio Buttons</option>
<option value="input">Input</option>
</select>
<label for="type" class="control-label">Type</label>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="sm-form-design">
<input type="text" name="quiz_time" class="form-control" id="masked-input-time" required>
<label for="quiz_time" class="control-label">Time *</label>
</div>
</div>
</div>
</div>
<!-- show this part when all fields above are filled -->
<div class="row choices">
<div class="col-md-12">
<h5>Choices:</h5>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
OnChange of any input, please iterate through all the inputs just to check whether each input is empty or has value.
Here you go with a solution for your problem 1 that you mentioned in the comment box
$(function() {
$('.choices').hide();
// show choices DIV only if all fields are filled.
$('select').change(function() {
validateInput();
});
$('input[type="text"]').keyup(function() {
validateInput();
});
// --- Whenever you make an action you can call this method to validate your inputs ----
function validateInput() {
var valid = true;
$('input[type="text"], select').each(function() {
if ($(this).val() === "") {
valid = false;
}
});
if (valid) {
$('.choices').show();
} else {
$('.choices').hide();
}
}
});
I am not in a place to properly test but looking at your function I would make the following changes,
$(function() {
// show choices DIV only if all fields are filled.
var flag = false
$('input[type="text"]').each(function() {
if ($(this).val() != "") {
flag = true
} else {
flag = false
}
});
if (flag) {
$('.choices').show();
} else {
$('.choices').hide();
}
});
$('input[type="text"]').keyup(function() {
// call function
});
$('input[type="text"]').keydown(function() {
// call function
});
I am able to validate my form using javascript, but even if the form data is invalid the next process is done with regards to the submit button. I am unable to stop the page from loading the other page that is supported to be loaded only if there are no errors in my form after javascript validation
script type="text/javascript">
function matchpass(){
var firstpassword=document.myform.psw.value;
var secondpassword=document.myform.pswrepeat.value;
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
if(firstpassword==secondpassword)
{
return true;
}
else
{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>
</div>
<form name="myform" action="RegisterControllerServlet" method="post" >
<input type="hidden" name="command" value="ADD">
<div class="container">
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email"><b>Enter your Employee id</b></label>
<input type="text" name="de_eid" >
<label for="email"><b>Email</b></label>
<input type="text" name="email">
<Select name="is" class="custom-select" style="width:500px; background-color: #A0A0A0; height:40px;">
<option value="">Choose Occupation</option>
<option value="Doctor">Doctor</option>
<option value="Receptionist">Receptionist</option>
<option value="labassistant">Lab assistant</option>
<option value="pharmacist">Pharmacist</option>
</Select>
<br><br>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="pswrepeat" required>
<hr>
<button type="submit" class="registerbtn" onclick="matchpass();">Register</button>
</div>
I want the page not to redirect the user to the page that is supposed to be loaded only if there are no errors in validation
Your <form> tag should have the onsubmit property -- not the <button>'s onclick at the bottom.
<form
name="myform"
action="RegisterControllerServlet"
method="post"
onsubmit="return matchpass()"
>
So I have a form that takes data and controller accesses it but I'm getting an error if the user clicks on the button without filling all the fields, so I want to disable the Proceed button until user has input all the fields. How do I achieve this? The fields are in div and I tried wrapping all the divs below including the button in a form but couldn't make it work. I have seen other examples like this but they do not use ng-click.
<form novalidate name="passengerForm">
<div class="col-md-12">
<div class="booking-details-container">
<div class="row">
<div class="col-md-12">
<h4 class="text-primary">
<strong>Contact Person Details</strong>
</h4>
</div>
</div>
<div class="row">
<div class="col-md-4">
<label for="">Contact Name <font color="red">*</font><input type="text"
ng-model="contactName" class="form-control-sm">
</label>
</div>
<div class="col-md-4">
<label for="">Email <input type="email"
ng-model="contactEmail" class="form-control-sm">
</label>
</div>
<div class="col-md-4">
<label for="">Number <font color="red">*</font><input type="text" id="contactNo" ng-model="contactNumber"
class="form-control-sm">
</label>
</div>
</div>
<div class="divider-h"></div>
<div data-ng-repeat="passenger in passengerList track by $index">
<div class="row">
<div class="col-md-12">
<h4 class="text-primary">
<strong>Passenger Details</strong>
</h4>
</div>
<div class="col-md-3">
<label for="">Type <font color="red">*</font><select type="text"
ng-model="passenger.paxType" class="form-control-sm" ng-disabled="true">
<option value="ADULT" ng-selected="passenger.paxType == 'ADULT'" >Adult</option>
<option value="CHILD" ng-selected="passenger.paxType == 'CHILD'">Child</option>
<!-- <option value="INFANT">Infant</option> -->
</select>
</label>
</div>
<div class="col-md-3">
<label for="">Title <font color="red">*</font><select type="text"
ng-model="passenger.title" class="form-control-sm">
<option value="Mister">Mr.</option>
<option value="Miss">Ms.</option>
<option value="Mrs" ng-show="passenger.paxType == 'ADULT' " >Mrs.</option>
</select>
</label>
</div>
<div class="col-md-3">
<label for="">First Name <font color="red">*</font><input type="text"
ng-model="passenger.firstName" class="form-control-sm"></label><br>
</div>
<div class="col-md-3">
<label for="">Last Name <font color="red">*</font><input type="text"
ng-model="passenger.lastName" class="form-control-sm"></label>
</div>
<div class="clearfix"></div>
<div class="col-md-4">
<label for="">Nationality <font color="red">*</font><select type="text"
ng-model="passenger.nationality" class="form-control-sm">
<option value="" selected disabled>Select
Nationality</option>
<option value="NP">Nepalese</option>
<option value="IN">Indian</option>
<%-- <c:forEach var="nationality" items="${nationality}">
<option value="NP">${nationality}</option>
</c:forEach> --%>
</select>
</label>
</div>
<div class="col-md-8">
<label for="">Remarks <input type="text"
ng-model="passenger.paxRemarks" class="form-control-sm">
</label>
</div>
</div>
<div class="divider-h"></div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<!-- <button class="btn btn-xs btn-default">+ Add Passenger</button> -->
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="col-md-2 pull-right" style="margin-top: 20px;">
<button ng-disabled="invalid" type="button" class="btn btn-primary btn-block" ng-click="proceedARS()">{{loadingButtonProceed}}</button>
</div>
</form>
Controller.js:
My controller.js is actually thousands of lines of code, I have just included the relevant parts:
$scope.$watch('passengerForm.$invalid',function(x,y){ $scope.invalid = $scope.passengerForm.$invalid; }, true)
$scope.proceedARS = function () {
$scope.ARSMessage = '';
if ($scope.contactName === undefined || $scope.contactName === null || $scope.contactName === "") {
$scope.ARSMessage = 'Please fill all the required fields';
return;
}
if ($scope.contactEmail === undefined || $scope.contactEmail === null || $scope.contactEmail === "") {
$scope.contactEmail = "";
}
if ($scope.contactNumber === undefined || $scope.contactNumber === null || $scope.contactNumber === "") {
$scope.ARSMessage = 'Please fill all the required fields';
return;
}
if ($scope.contactNumber.length != 9 && $scope.contactNumber.length != 10) {
$scope.ARSMessage = 'Contact Number Length Invalid';
return;
}
if ($scope.selectedOutbound == undefined || $scope.selectedOutbound == "" || $scope.selectedOutbound == null) {
$scope.ARSMessage = "Please select one of the flights for departure";
return;
}
if ($scope.flightAvailability.tripType == 'R') {
if ($scope.selectedInbound == undefined || $scope.selectedInbound == "" || $scope.selectedInbound == null) {
$scope.ARSMessage = "Please select one of the flights for arrival";
return;
}
}
$scope.loadingFunction();
Try This,
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="">
<p>Try writing in the input field:</p>
<form novalidate name="myForm">
<label>First Name</label>
<input name="fname" ng-model="fname" required>
<div ng-show="myForm.fname.$valid === false">Please enter first name</div>
<div></div>
<label>Last Name</label>
<input name="lname" ng-model="lname" required>
<div ng-show="myForm.lname.$valid === false">Please enter last name</div>
<button type="submit" ng-disabled="!myForm.$valid" >save</button>
</form>
</body>
I have created plunker and its working fine,
Add required attribute to all required fields.
<input type="text" ng-model="contactName" class="form-control-sm" required>
Try this
<form name="myForm">
<input type="text" name="name" ng-model="name" required />
<button ng-disabled="{{ myForm.$invalid }}">Save</button>
</form>
Try this
function Controller($scope) {
$scope.save = function(user) {
console.log(user);
$scope.user = user;
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<html ng-app>
<div ng-app="demo1">
<div ng-controller="Controller">
<form novalidate name="myForm">
<input type="text" name="name" ng-model="data.name" required />
<input type="text" name="lastname" ng-model="data.lastname" required />
<button type="button" ng-disabled="myForm.$invalid"
ng-click="save(data)">Save</button>
</form>
{{user}}
</div>
</div>
</html>
Problem: I would like to be able to alert the user if a particular field is empty. Here is how the form looks:
When the user enters a zip code and selects search, I would like a pop up to display to alert the user to select a distance and not display the results. If the user enters hospital name and city drop down, I do not want the alert to appear. Only when the zip code is entered and when the search button is selected.
Here is the form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance">
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
and here is the script that alerts when the miles is blank:
function validateForm() {
var x = document.forms["UrgentCareSearch"]["distance"].value;
if (x == "" || x=="null") {
alert("Please select distance");
return false;
}
UPDATE
I have done the following and it still does not work the way I want to (which is to show the alert when the search button is entered and when the user has entered a zip code. Meaning once the user has entered a zip code and click on the search button to populate the results, the alert will appear notifying to select the miles and the results will not show until user has entered how many miles and click search again):
function validateForm() {
var x = document.forms["UrgentCareSearch"]["miles"].value;
var $zip = $('#zip');
if ((x == "" && $zip != "") ||(x=="null" && $zip != "")) {
alert("Please select distance");
return false;
}
and this is what I when I used required:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return checkTextField()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles" required>
<option value=""></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
adding required to each of the input or select elements would prevent the form from being submitted if they are left blank
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" required /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City" required>
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required>
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
Or there can jquery touch look at this
first give your form an id lets say myform
$(document).ready(function()
{
$('#myform').submit(function()
{
var name = $("#hospital").val();
var name = $("#city").val();
if(name == "" || name == " ")
{
alert("Please enter name");
return false;
}
if(city == "" || city== " ")
{
alert("Please enter city");
return false;
}
//Just like this and at the end when you are satisfied
$(this).submit();
});
});
From what I understand by your problem statement, you can do the following in your validation function.
function validateForm() {
var miles = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
if (zip && !miles) {
event.preventDefault(); // This will prevent the form submit
alert("Please enter the Miles.");
return false; // Does't submit the form (for IE)
}
}
Also, when calling the function, just call the function directly.
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="validateForm();">
I would like to choose between form_two and for_three in the main_form(fiddle at the bottom of the post). Under the main form should be one of the two forms(form_two/form_three). I can choose between the two forms, but they are not editable, because they are not in the source code, if I inspect the code with the browser.
I would like to have a datepicker from jquery in it, to submit the date. But I have got the problem, that I can see the two(form_two/form_three) different forms in the browser, but if I look in the source code, there is no form in the dom.
Here is my code:
Form to select one of these forms (main_form)
<!-- Content begin -->
<div id="content">
<form method="post" onsubmit="return false">
<fieldset name="inseration_option">
<legend>Inseratauswahl</legend>
<label for="choice">Auswahl:</label>
<select name="choice" id="choice" size="1">
<option value="joboffers" selected="selected">Jobangebot aufgeben</option>
<option value="workeroffers">Job finden</option>
</select>
<button value="ok" id="choice_btn" name="choice_btn" >Los</button>
</fieldset>
</form>
</div>
<div id="form"></div>
<!-- Content end -->
form_two
<!-- Content begin -->
<div id="content">
<form action="index.php?site=suche_inserat" method="post">
<fieldset name="search_option">
<legend>Suche Inserate</legend>
<fieldset>
<legend>Jobinformationen</legend>
<label for="j_select">Jobart:</label><br>
<select name="j_select" size="1">
<option>Gelegenheitsjob</option>
<option>Ausbildungsplatz</option>
<option>Praktika</option>
<option>Fachkräfte</option>
</select><br>
<label for="j_cat">Berufsfeld:</label><br>
<select name="j_cat" size="1">
<option>Bau, Architektur, Vermessung</option>
<option>Dienstleistung</option>
<option>Elektro</option>
<option>Gesellschaft-, Geisteswissenschaften</option>
<option>Gesundheit</option>
<option>IT, Computer</option>
<option>Kunst, Kultur, Gestaltung</option>
<option>Landwirtschaft, Natur, Umwelt</option>
<option>Medien</option>
<option>Metall, Maschinenbau</option>
<option>Naturwissenschaften</option>
<option>Produktion, Fertigung</option>
<option>Soziales, Pädagogik</option>
<option>Technik, Technologiefelder</option>
<option>Verkehr, Logistik</option>
<option>Wirtschaft, Verwaltung</option>
</select><br>
<label for="j_destrict">Stadtteil:</label><br>
<select name="j_destrict" size="1">
<option>Charlottenburg</option>
<option>Friedrichshain</option>
<option>Hellersdorf</option>
<option>Köpenick</option>
<option>Kreuzberg</option>
<option>Lichtenberg</option>
<option>Marzahn</option>
<option>Mitte</option>
<option>Neuköln</option>
<option>Pankow</option>
<option>Reinickendorf</option>
<option>Schöneberg</option>
<option>Spandau</option>
<option>Steglitz</option>
<option>Tempelhof</option>
<option>Treptow</option>
<option>Zehlendorf</option>
</select><br>
<label for="j_date">Gesucht ab Datum:</label><br>
<input type="date" name="j_date"><br>
<label for="j_cash">Vergütung:</label><br>
<input type="text" name="j_cash"><br>
<label for="j_title">Titel:</label><br>
<input type="text" name="j_title"><br>
<label for="j_desc">Beschreibung:</label><br>
<textarea name="j_desc"></textarea>
</fieldset>
<fieldset>
<legend>Auftraggeberinformationen</legend>
<label for="j_company">Unternehmen/Firma:</label><br>
<input type="text" name="j_company"><br>
<label for="j_street">Straße/Nr.:</label><br>
<input type="text" name="j_street"><br>
<label for="j_plz">PLZ:</label><br>
<input type="text" name="j_plz"><br>
<label for="j_town">Ort:</label><br>
<input type="text" name="j_town"><br>
<label for="j_pic">Foto/Logo:</label><br>
<input type="file" name="j_pic">
</fieldset>
<fieldset>
<legend>Kontaktinformationen</legend>
<label for="j_email">E-Mail-Adresse:</label><br>
<input type="text" name="j_email"><br>
<label for="j_phone">Telefonnummer:</label><br>
<input type="text" name="j_phone"><br>
<label for="j_fax">Fax:</label><br>
<input type="text" name="j_fax">
</fieldset>
<button name="search_btn">Inserieren</button>
</fieldset>
</form>
</div>
<!-- Content end -->
form_three
<!-- Content begin -->
<div id="content">
<form action="index.php?site=finde_inserat" method="post">
</fieldset>
<fieldset name="find_option">
<legend>Finde Inserat</legend>
<fieldset>
<legend>Jobinformationen</legend>
<label for="w_select">Jobart:</label><br>
<select name="w_select" size="1">
<option>Gelegenheitsjob</option >
<option>Ausbildungsplatz</option>
<option>Praktika</option>
<option>Fachkräfte</option>
</select><br>
<label for="w_cat">Berufsfeld:</label><br>
<select name="w_cat" size="1">
<option>Bau, Architektur, Vermessung</option>
<option>Dienstleistung</option>
<option>Elektro</option>
<option>Gesellschaft-, Geisteswissenschaften</option>
<option>Gesundheit</option>
<option>IT, Computer</option>
<option>Kunst, Kultur, Gestaltung</option>
<option>Landwirtschaft, Natur, Umwelt</option>
<option>Medien</option>
<option>Metall, Maschinenbau</option>
<option>Naturwissenschaften</option>
<option>Produktion, Fertigung</option>
<option>Soziales, Pädagogik</option>
<option>Technik, Technologiefelder</option>
<option>Verkehr, Logistik</option>
<option>Wirtschaft, Verwaltung</option>
</select><br>
<label for="w_destrict">Stadtteil:</label><br>
<select name="w_destrict" size="1">
<option>Charlottenburg</option>
<option>Friedrichshain</option>
<option>Hellersdorf</option>
<option>Köpenick</option>
<option>Kreuzberg</option>
<option>Lichtenberg</option>
<option>Marzahn</option>
<option>Mitte</option>
<option>Neuköln</option>
<option>Pankow</option>
<option>Reinickendorf</option>
<option>Schöneberg</option>
<option>Spandau</option>
<option>Steglitz</option>
<option>Tempelhof</option>
<option>Treptow</option>
<option>Zehlendorf</option>
</select><br>
<label for="w_date">Verfügbar ab Datum:</label><br>
<input type="text" name="w_date" id="w_date"><br>
<label for="w_cash">Vergütung:</label><br>
<input type="text" name="w_cash"><br>
<label for="w_title">Titel:</label><br>
<input type="text" name="w_title"><br>
<label for="w_desc">Beschreibung:</label><br>
<textarea name="w_desc"></textarea><br>
<label for="w_pic">Profilbild/Foto:</label><br>
<input type="file" name="w_pic">
</fieldset>
<fieldset>
<legend>Kontaktinformationen</legend>
<label for="w_email">E-Mail-Adresse:</label><br>
<input type="text" name="w_email"><br>
<label for="w_phone">Telefonnummer:</label><br>
<input type="text" name="w_phone"><br>
<label for="w_fax">Fax:</label><br>
<input type="text" name="w_fax">
</fieldset>
<button name="find_btn">Inserieren</button>
</fieldset>
</form>
</div>
And the JS File
$(document).ready(function(){
var pfad = "";
$("#choice_btn").click(function(){
//console.log($("#choice").val());
if ( $("#choice").val() == "joboffers" ){
pfad = "sites/suche_inserat.php";
}else{
pfad = "sites/finde_inserat.php";
//console.log($("#choice").val());
}
$( "#form" ).load( pfad );
$( "#w_date" ).datepicker();
/*
$.ajax({
url: pfad,
type: "POST",
async: true,
success: function(callback) {
//console.log(callback);
$("#form").innerHTML(callback);
}
})
*/
})
});
Sorry for my english!! I hope somebody can help me!
edit: Here is a fiddle: click
(I do not know, how to make more html windows in fiddle) :(
I made it this way(jsfiddle) now. Maby could someone have a look at it.
I have took all forms in one file. So I do not need three diffrent files and have to load them into it.
$(document).ready(function(){
$("#form_1").hide();
$("#form_2").hide();
$("#choice_btn").click(function(){
if ( $("#choice").val() == "joboffers" ){
$("#form_2").hide();
$("#form_1").show();
}else{
$("#form_1").hide();
$("#form_2").show();
}
})
$("#j_date").datepicker();
$("#w_date").datepicker();
});