I am checking whether someone has selected a property type (house/flat) and then checking the sub list of either houses or flats to see whether they have selected a sub-type of there selected property (ie. house -> semi-detached etc.)
The house validation is working fine, the flats validation isn't however even though their syntax is the same, I feel like I'm missing something really obvious here.
jsfiddle: http://jsfiddle.net/dyates88/vCmnW/iddle
jQuery:
valid = true;
if (index === 2) {
if (!$("#htype div").hasClass("selected")) {
alert("Please select a Property type!");
valid = false;
} else if ($("#htype div").attr('sel') == 'true' && $("#htype div").attr('id') == 'flat' && !$("#flats div").hasClass("selected")) {
alert("Please Select a flat type!");
valid = false;
} else if ($("#htype div").attr('sel') == 'true' && $("#htype div").attr('id') == 'house' && !$("#houses div").hasClass("selected")) {
alert("Please Select a house type!");
valid = false;
}
Related
WDrodownList
When I am selecting a value from dropdown list say "Practice List" and clicking on save button, and again modifying that item I can see that the dropdown list is not holding its selected value i.e., "Practice List". Instead it is holding its default value i.e., "My List". How can I make it hold the selected value after saving the data?
Here's my html code:
<select id="{{::prefix}}_Select_Practice" name="FreeTextDrugSchedule" ng-options="option as option.name for option in data.practiceOptions" class="form-control medium" ng-model="data.saveIn" style="margin-bottom: 5px;">
<option value="" selected="selected">My list</option>
</select>
<button id="{{::prefix}}_Button_Submit" class="btn btn-primary" ng-click="validations = null; doSubmit()">{{submitVerb}}</button>
Here's my js file code:
$scope.doSubmit = function (dataToSubmit) {
$scope.submitted = true;
if (dataToSubmit) {
if ($scope.data.saveIn) {
dataToSubmit.dataToSubmit.saveIn = $scope.data.saveIn;
}
$scope.data = dataToSubmit.dataToSubmit ? dataToSubmit.dataToSubmit : dataToSubmit;
}
validateSubmission();
// TODO simplify this validation
if ($scope.EnterDetailsForm.$invalid || $scope.showEffectiveDateError ||
$scope.showEffectiveDateRangeError || ($scope.sigValidations &&
$scope.sigValidations.length)
|| ($scope.data.pharmacy1 && $scope.data.pharmacy1 == $scope.data.pharmacy2)
|| ($scope.showMDD && (!$scope.data.medication.maximumDailyDose || ($scope.showMDD == 'pd' && !$scope.data.medication.maximumDailyDoseUnit)))
|| $scope.showProviderError
|| $scope.showSupervisorError
|| $scope.drugMinError
|| $scope.showPrimaryError) {
$scope.validations.push({
name: 'Invalid Entry',
msg: 'Please correct all errors on this form to continue.'
});
if ($scope.entity == 'Prescription') {
$scope.scrollToError = true;
}
} else if ($scope.entity == 'Prescription' && !validateDuration()) {
$scope.$emit('ghostMessage', 'The length of the prescription should not be more than 365 days');
} else { //proceed with submission
// prepare the data to be submitted to the alert checker
var dataToSubmit = prepareDataToSubmit();
// validate payload before submit
if (dataToSubmit.medication.lastRefillDate && dataToSubmit.medication.startDate && dataToSubmit.medication.lastRefillDate.date < dataToSubmit.medication.startDate.date) {
$scope.$emit('ghostMessage', 'Last written date cannot be before start date.');
} else if (dataToSubmit.medication.lastRefillDate && dataToSubmit.medication.stopDate && dataToSubmit.medication.lastRefillDate.date > dataToSubmit.medication.stopDate.date) {
$scope.$emit('ghostMessage', 'Last written date cannot be after stop date.');
} else if (dataToSubmit.medication.diagnoses && dataToSubmit.medication.diagnoses.length == 2 && dataToSubmit.medication.diagnoses[0].code &&
dataToSubmit.medication.diagnoses[0].code == dataToSubmit.medication.diagnoses[1].code) {
$scope.$emit('ghostMessage', 'You may not specify the same diagnosis code for both primary and secondary diagnoses');
} else if ($scope.entity != 'FavoriteRx' && $scope.showDAWGenericWarning && !$scope.formularyCheckedForDAWWarning) {
checkFormularyAlertsForDAWWarning(dataToSubmit);
} else {
$scope.formularyCheckedForDAWWarning = false;
// check dose alerts if necessary
dataToSubmit.schedules = angular.copy(schedules);
if ($scope.entity == 'Prescription' && doseCheckNeeded) {
checkDoseAlerts(dataToSubmit);
} else { // done; process submission
$scope.submit({data: dataToSubmit, optionCodes: $scope.optionCodes});
$scope.loading = 0;
}
}
}
};
I'm not exactly sure what you are asking for, or what you mean by "saving" the data, but I will try to offer some assistance.
I don't know angular.js, but my suggestion would be to wrap the select in a form (which I assume you're doing) and then set the value using the post value in angluar.js (if you can do that). That way, if you reload the page, it will not load the default value. Additionally, if you're merely inspecting the element in a browser after you select a new option, it won't show you that a new option is selected (i.e. the selected="" attribute will still be on the default).
I have some form validation on my website.
If the account code field contains "XXX" and the reference field is blank, I want an alert to come up for the user to populate the reference field.
I have read that indexOf is the function I need, but the code below does not appear to work. Any ideas?
<SCRIPT>
if (form.account.value.indexOf("XXX") != -1 & form.reference.value == "") {
alert("Please Enter Reference Number");
form.reference.focus( );
return false;
}
</script>
Can you try:
if (form.account.value.indexOf("XXX") != -1 && form.reference.value == "") {
alert("Please Enter Reference Number");
form.reference.focus( );
return false;
}
This corrects the AND clause, which uses && not &.
The following validation code was handed to me and it just looks so repetative. How could I learn from his example on how to reduce the duplicate processes that occur for each input field that is being validated below....? I want to be more efficient with JavaScript, not repeat the same functions over and over again just because a form adds on a new input element...
function isRequired(){
firstNameRequired();
lastNameRequired();
stateRequired();
gradYearRequired();
relationshipRequired();
birthdayRequired();
}
function firstNameRequired(){
var firstName = document.forms['subscribeForm']['First Name'].value;
if (firstName == null || firstName ==''){
alert('Please enter your first name.');
document.subscribeForm.elements['First Name'].style.backgroundColor='yellow';
return false;
}
}
function lastNameRequired(){
var lastName = document.forms['subscribeForm']['Last Name'].value;
if (lastName == null || lastName ==''){
alert('Please enter your last name.');
document.subscribeForm.elements['Last Name'].style.backgroundColor='yellow';
return false;
}
}
function stateRequired(){
var state = document.forms['subscribeForm']['State'].value;
if (state == null || state ==''){
alert('Please enter your state of residence.');
document.subscribeForm.elements['State'].style.backgroundColor='yellow';
return false;
}
}
function gradYearRequired(){
var gradYear = document.forms['subscribeForm']['Graduation Year'].value;
if (gradYear == null || gradYear ==''){
alert('Please enter your graduation year.');
document.subscribeForm.elements['Graduation Year'].style.backgroundColor='yellow';
return false;
}
}
function relationshipRequired(){
var relationship = document.forms['subscribeForm']['ABC Link Relationship'].value;
if(relationship == null || relationship == ''){
alert('Please enter your relationship to ABC.');
document.subscribeForm.elements['ABC Link Relationship'].style.backgroundColor='yellow';
return false;
}
}
function birthdayRequired(){
var birthDay = document.forms['subscribeForm']['Birthdate'].value;
if(birthDay == null || birthDay == ''){
alert('Please enter your birthday.');
document.subscribeForm.elements['Birthdate'].style.backgroundColor='yellow';
return false;
}
}
...
<input type="submit" class="submitBtn" value="" onclick="isRequired()" />
Also, I have the flexibility to work in jQuery if need be.
Detect what parts in your code are repetitive and what parts do change from field to field. For example, you could create a function that takes two parameters: the field name and its label.
function validateRequiredField(name, label)
{
var value = document.forms['subscribeForm'][name].value;
if (value == null || value == '') {
alert('Please enter your ' + label);
document.forms['subscribeForm'][name].style.backgroundColor = 'yellow';
return false;
}
}
Then you can just call this function passing the name and the label as parameter:
validateRequiredField('First Name', 'first name');
validateRequiredField('ABC Link Relationship', 'relationship to ABC');
// ...
Keep in mind that these validations should be done also in server side, because someone can just disable JavaScript and send your form skipping your client side validation functions.
Because the only data being passed is the object and the alert message, instead of a whole custom function, use a single function with object and message params.
function isRequired(){
required(document.forms['subscribeForm']['First Name'],'first name');
required(document.forms['subscribeForm']['Last Name'],'last name');
required(document.forms['subscribeForm']['State'],'state of residence');
required(document.forms['subscribeForm']['Graduation Year'],'graduation year');
required(document.forms['subscribeForm']['ABC Link Relationship'],'relationship to ABC');
required(document.forms['subscribeForm']['Birthday'],'birthday');
}
function required(object,message){
if (!obj) {
alert('Please enter your '+message);
obj.style.backgroundColor='yellow';
return false;
}
return true;
}
First of all I would recommend to use IDs to read out the form fields:
<input type="text" id="firstname" />
This allows you to use jQuery('#firstname') to select this input field.
Second, here's how I'd go about the task of making the code smaller:
What are you trying to do here?
You always read some value from the form (depending on an ID of sorts).
Then you check if that value is null.
If the value is not set you want to display an error message (depending on the ID again).
And you also want to mark the field that was missing and then return false.
So I'd code a function that does exactly that:
// function having a parameter for the ID and the custom error message
function checkFormField(fieldID, errorMsg) {
// read value from field using jquery
value = $(fieldID).value();
// check for null or empty
if (value == null || value == '') {
// display custom error message
alert(errorMsg);
// change color of field using jQuery
$(fieldID).css('background', 'yellow');
return false;
}
}
Now you can reuse this function for every field you want to check. The new isRequired method would look like this:
function isRequired(){
checkFormField('#firstname', 'Please enter your first name.');
checkFormField('#lastname', 'Please enter your last name.');
// and so on...
}
Note that this example would require name attributes that can be used as identifiers (no spaces)
<input name="first_name" type="text" />
<input name="last_name" type="text" />
js:
function validateRequired(slug, field){
// test for passing condition
if (field.value !== null && field.value !== '') {
return true;
}
else {
alert('Please enter your ' + field.str);
}
return false;
}
/**
* Validate a form using a ruleset object
*
*/
function validateFields(ruleset, form){
var field = {};
var errors = 0;
// Loop though the ruleset
for(var index in ruleset) {
//
if (ruleset.hasOwnProperty(index)) {
field = ruleset[index];
// check if input exists
if (form[index]){
field.value = form[index].value
}
if (ruleset[index].required) {
if (!validateRequired(field)){
errors++;
field.invalid = true;
}
}
// you could add more rules here...
}
}
return errors === 0;
}
var valid = validateFields({
first_name : {
required : true,
str: 'first name'
},
last_name : {
required : true,
str: 'last name'
}
// ...
}, document.forms['subscribeForm']);
Now the form is one form, here is the new broken code
<script language="javascript" type="text/javascript">
function verifyIt(){
if((document.form1.baseline_08.value != "" && Number(document.form1.baseline_08.value) && document.form1.baseline_08.value != "-1")){
if((document.form1.baseline_09.value != "" && Number(document.form1.baseline_09.value) && document.form1.baseline_09.value != "-1")){
document.form1.submit();
return true;
}else{
alert("Please select how old you were when you started smoking every day.");
return false;
}
}
function submit2(){
document.form1.direction.value = "back";
document.form1.submit();
}
</script>
Now the verify doesnt work at all. I just dont see what is wrong with this now.
The problem I am having is the form1 is the only one being recognized. I believe it is because of my if statement structure. Basicly I only get the return from the form1. What is wrong with my js?
I believe it is because of my if statement structure.
Yes, you are always returning after checking form1. However, you cannot submit multiple forms at a time, so you should combine them into one. Then use
function verifyIt() {
if(!(document.form.baseline_08.value == "" && Number(document.form.baseline_08.value) && document.form.baseline_08.value != "-1")){
alert("Please select how old you were when you started smoking every day.");
return false;
}
if(!(document.form.baseline_09.value != "" && Number(document.form.baseline_09.value) && document.form.baseline_09.value != "-1")){
alert("Please select when you would smoke after waking up.");
return false;
}
document.form.submit();
}
I've been struggling over this all day. All the other validation works fine except for the check boxes. It seems to validate it but doesn't detect when things are checked. Meaning, I'll check a box and it'll still say to enter in a contact time, no matter what box I check. Please help!!
Its just the one for selecting the best time to contact you that's acting up.
Here's my check boxes:
<input id="best_contact_time" name="best_contact_time" value="Morning 7-12" class="inputCheckbox" type="checkbox">Morning (7-12)<br>
<input id="best_contact_time" name="best_contact_time" value="Afternoon 12-5" class="inputCheckbox" type="checkbox">Afternoon (12-5)<br>
<input id="best_contact_time" name="best_contact_time" value="Evening 5-9" class="inputCheckbox" type="checkbox">Evening (5-9)<br>
And my validation code:
function submitme() {
// Validate required fields
if (get_element('lastname').value == '') {
alert('Please enter your last name');
return false;
}
if (get_element('first_name').value == '') {
alert('Please enter your first name');
return false;
}
if (get_element('phone').value == '') {
alert('Please enter a phone number');
return false;
}
if (get_element('email').value == '') {
alert('Please enter an email address');
return false;
}
var ischecked = 0;
for (var i = 0; i < document.rental.best_contact_time.length; i++) {
var e = document.rental.best_contact_time;
if (e.checked == true)
{ ischecked = 1; }
}
if (ischecked == 0) {
alert('Please enter the best time to contact you');
return false;
}
if (get_element('approximate_start_date').value == '') {
alert('Please enter an approximate start date');
return false;
}
document.forms[0].submit();
return true;
}
Since you have multiple elements with the same name, document.rental.best_contact_time will be a NodeList not an HTMLElementNode.
You would need to loop through the list (treat it like an array) and check each one in turn.