Values in the UI doesn't change even after executing the code in controller.
It displays the initial values with out a problem.
I've tried calling $scope.$apply() at the end of each function (submit and transfer) but it didn't work(it only gave an error with the $http.post()). What am i missing here?
app.controller('RegisterController', ['$scope','$http', function($scope,$http) {
$scope.user = {
email: 'admin#blah.com',
password1: '1qaz2wsx',
password2:'1qaz2wsx',
password:'1qaz2wsx',
username:'Admin',
profile_picture:'',
dobDay:'12',
dobMonth:'12',
dobYear:'1993',
date_of_birth:'',
stateMessage:'',
messageColor:'white',
};
var transfer = function(){
$http.post('http://localhost/cw/index.php/rest/resource/user/action/create',$scope.user).then(function successCallback(response) {
if(response.data.status!=null){
if(response.data.status=='success'){
$scope.user.stateMessage = 'success';
$scope.user.messageColor = "green";
}
else if(response.data.status=='failure'){
$scope.user.stateMessage = response.data.message;
$scope.user.messageColor = "red";
}
}
},function errorCallback(response) {
$scope.user.stateMessage = "Error occured.";
$scope.user.messageColor = "red";
});
};
$scope.submit = function(){
$scope.user.stateMessage="";
$scope.user.messageColor="white";
var proceed = true;
if(!validateFields()){
$scope.user.stateMessage = "All fields must be filled!";
$scope.user.messageColor = "red";
proceed = false;
}
if(validateDate($scope.user.dobDay,$scope.user.dobMonth,$scope.user.dobYear)){
$scope.user.date_of_birth= $scope.user.dobYear+"-"+$scope.user.dobMonth+"-"+$scope.user.dobDay;
}else {
proceed = false;
$scope.user.stateMessage = "Date is invalid!";
$scope.user.messageColor = "red";
}
if($scope.user.password1!=$scope.user.password2){
proceed = false;
$scope.user.stateMessage = "Passwords don't match!";
$scope.user.messageColor = "red";
}else $scope.user.password = $scope.user.password1;
if(proceed){
var file = document.getElementById('filePicker').files[0];
reader = new FileReader();
reader.onloadend = function(e) {
$scope.user.profile_picture = JSON.stringify(e.target.result);
$scope.$apply();
console.log($scope.user.profile_picture);
transfer();
}
reader.readAsDataURL(file);
}
function validateFields(){
/*some form validation*/
return true;
}
function validateDate(day,month,year){
/*some date validation*/
return true;
}
}
}]);
HTML code
<div ng-controller="RegisterController">
<span style="background-color:{{user.messageColor}}"><h4>{{user.stateMessage}}</h4></span>
</div>
<table style="text-align: left" ng-controller="RegisterController">
<tr>
<td>
Username
</td>
<td>
<input type="text" ng-bind="user.username" ng-model="user.username">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Email
</td>
<td>
<input type="email" ng-bind="user.email" ng-model="user.email">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="password" ng-bind="user.password1" ng-model="user.password1">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Retype password
</td>
<td>
<input type="password" ng-bind="user.password2" ng-model="user.password2">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Date of Birth
</td>
<td>
<input type="text" ng-bind="user.dobDay" ng-model="user.dobDay" value="DD" size="2" maxlength="2">
<input type="text" ng-bind="user.dobMonth" ng-model="user.dobMonth" value="MM" size="2" maxlength="2">
<input type="text" ng-bind="user.dobYear" ng-model="user.dobYear" value="YYYY" size="4" maxlength="4">
</td>
</tr>
<tr>
<td>
Profile picture
</td>
<td>
<input id="filePicker" type="file" ng-bind="user.profile_picture" ng-model="user.profile_picture" accept="image/*">
</td>
</tr>
<tr>
<td></td>
<td style="float:left">
<button ng-click="submit()">Submit</button>
</td>
</tr>
</table>
It seems like i cannot use the same controller in 2 instances.
Moving the status div in to the table assigned with the controller worked for me. There are ways to share data between controllers by using a service but i won't go there since this is only for a coursework.
AngularJS: share the data of the same controller in two different, not nested parts of the page
Related
This question already has answers here:
Submit form after calling e.preventDefault()
(11 answers)
Closed 11 months ago.
I wrote a simple register form with an action attribute on HTML that when the user fills the inputs
it sends them to my database. Everything works fine until I added a validation script using Javascript. The script works fine with my parameters but when I press the submit button the form doesnt execute the action attribute. One way I thought around this is make a simpler script inside my HTML but I'd prefer to keep it on a separate file.
HTML:
<script defer src = "validation.js">
.......
<form action="register_user.php" method="post" id="formRegister" name = "formRegister" >
<div class="formfield">
<table style="display: inline-table; margin: 0px 12px 0px 12px;" >
<tr>
<td> Name<b style="color:red;">*</b> </td>
<td>
<div class = "input-control">
<input type="text" name="name" size="32" id="name" >
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> Surename<b style="color:red;">*</b> </td>
<td>
<div class = "input-control">
<input type="text" name="surename" size="32" id="surename" >
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> AMKA<b style="color:red;">*</b> </td>
<td>
<div class = "input-control">
<input type="text" name="amka" size="32" id="amka" >
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> AFM<b style="color:red;">*</b> </td>
<td>
<div class = "input-control">
<input type="text" name="afm" size="32" id="afm" >
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> PID<b style="color:red;">*</b> </td>
<td>
<div class = "input-control">
<input type="text" name="pid" size="32" id="pid">
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> Age<b style="color:red;">*</b> </td>
<td>
<div class = "input-control">
<input type="text" name="age" size="32" id="age">
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> Gender </td>
<td>
<div class = "input-control">
<input type="text" name="gender" size="32">
<div class = "error"></div>
</div>
</td>
</tr>
<tr>
<td> Email </td>
<td>
<div class = "input-control">
<input type="text" name="email" size="32" id = "email">
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> Mobile Phone<b style="color:red;">*</b> </td>
<td>
<div class = "input-control">
<input type="text" name="mphone" size="32" id="mphone">
<div class="error"></div>
</div>
</td>
</tr>
<tr>
<td> Role<b style="color:red;">*</b> </td>
<td>
<div class="dropdown">
<div class = "input-control">
<select id="dropdown" name = "dropdown">
<option value= "">Select...</option>
<option value="1">Civilian</option>
<option value="2">Doc</option>
</select>
<div class="error"></div>
</div>
</div>
</td>
</tr>
</table>
<br><br>
<button type="submit" name="register" > Register </button>
</div>
</form>
Javascript (validation.js):
const formRegister = document.getElementById('formRegister');
const nameid = document.getElementById('name');
const surename = document.getElementById('surename');
const amka = document.getElementById('amka');
const afm = document.getElementById('afm');
const pid = document.getElementById('pid');
const age = document.getElementById('age');
const mphone = document.getElementById('mphone');
const dropdown = document.getElementById('dropdown');
const email = document.getElementById('email');
formRegister.addEventListener('submit', e => {
e.preventDefault();
validateInputs();
});
const setError = (element, message) => {
const inputControl = element.parentElement;
const errorDisplay = inputControl.querySelector('.error');
errorDisplay.innerText = message;
inputControl.classList.add('error');
inputControl.classList.remove('success')
}
const setSuccess = element => {
const inputControl = element.parentElement;
const errorDisplay = inputControl.querySelector('.error');
errorDisplay.innerText = '';
inputControl.classList.add('success');
inputControl.classList.remove('error');
};
const isValidEmail = email => {
const re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
const validateInputs = () => {
const nameidValue = nameid.value.trim();
const surenameValue = surename.value.trim();
const amkaValue = amka.value.trim();
const afmValue = afm.value.trim();
const pidValue = pid.value.trim();
const ageValue = age.value.trim();
const mphoneValue = mphone.value.trim();
const dropdownValue = dropdown.value;
const emailValue = email.value.trim();
var letters = /^[A-Za-z]+$/;
var symbols = /[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
var numbers = /^[0-9]+$/;
//error check
//name
if (nameidValue === ''){
setError(nameid, 'Error');
}else if(nameidValue.match(letters)){
setSuccess(nameid);
}else{
setError(nameid, 'Error');
}
//surename
if (surenameValue === '' ){
setError(surename, 'Error');
}else if (surenameValue.match(letters)){
setSuccess(surename);
}else{
setError(surename, 'Error');
}
//amka
if (amkaValue === ''){
setError(amka, 'Error');
}else if(amkaValue.length != 11){
setError(amka,'Error');
}else{
setSuccess(amka);
}
//afm
if (afmValue === ''){
setError(afm, 'Error');
}else if(afmValue.length != 9){
setError(afm,'Error');
}else {
setSuccess(afm);
}
//pid
if (pidValue === ''){
setError(pid,'Error');
}else if(pidValue.length != 8){
setError(pid, 'Error');
}else{
setSuccess(pid);
}
//age
if (ageValue === ''){
setError(age, 'Error');
}else {
setSuccess(age);
}
//mphone
if (mphoneValue === ''){
setError(mphone,'Error');
}else if(mphoneValue.length != 10){
setError(mphone, 'Error')
}else {
setSuccess(mphone);
}
//dropdown
if (dropdownValue == ""){
setError(dropdown, 'Error');
}else{
setSuccess(dropdown);
}
};
It won't submit the form due to this line:
e.preventDefault();
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
My suggestion is you resubmit the form after your validation logic has run providing the form is valid.
You're preventing the default action of the browser to submit the post request to the given route.
Try removing the "e.preventDefault" from the script.js. That should send the data to the route
I am consuming wcf service into angular js application . I am trying to invoke multi request from angular js application to wcf service . But the problem is when i run the application i got following errors in google chrome console windows .
Uncaught SyntaxError: missing ) after argument list
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?
Here is the script code .
///// <reference path="../angular.min.js" />
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Tittle = "";
$scope.First_Name = "";
$scope.Last_Name = "";
$scope.Gender = "";
$scope.DOB = "";
$scope.Mobile = "";
$scope.House_No = "";
$scope.Streent_Name = "";
$scope.Country = "";
$scope.Post_Code = "";
$scope.Occupation = "";
}
$scope.CeditCardApplication = function () {
var ApplicationDeatils = {
Tittle: $scope.Tittle,
First_Name: $scope.First_Name,
Last_Name: $scope.Last_Name,
Gender: $scope.Gender,
DOB: $scope.DOB,
Mobile: $scope.Mobile,
House_No: $scope.House_No,
Streent_Name: $scope.Streent_Name,
Country: $scope.Country,
Post_Code: $scope.Post_Code,
Occupation: $scope.Occupation
};
myService.ApplicationDeatilsCheck(ApplicationDeatils).then(function (pl) {
console.log(pl.data)
if (pl.data) {
$scope.msg = "User information is correct !"
myService.ApplicationCreditScoreCheck(ApplicationDeatils1).then(function (p2) {
console.log(p2.data)
if (p2.data) {
$scope.msg = "We can offer you £6000";
}
else {
$scope.msg = "Application failed !";
console.log("Some error Occured" + err);
}
}, function (err) {
$scope.msg = "Application failed!";
console.log("Some error Occured" + err);
});
};
}
}]);
app.service("myService", function ($http) {
this.ApplicationDeatilsCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccountCheck", JSON.stringify(ApplicationDeatils));
}
this.ApplicationCreditScoreCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/cheekCreditScore", JSON.stringify(ApplicationDeatils));
}
})
Here is the HTML CODE ..
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/CreditCardApplicationScript/ApplicationCheck.js"></script>
</head>
<body >
<table id="tblContainer" data-ng-controller="Web_Client_Controller">
<tr>
<td></td>
</tr>
<tr>
<td>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Tittle</span>
</td>
<td>
<input type="text" id="Tittle" data-ng-model="Tittle" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Fisrt Name</span>
</td>
<td>
<input type="text" id="first_name" required data-ng-model="First_Name" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Last Name</span>
</td>
<td>
<input type="text" id="last_name" data-ng-model="Last_Name" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Gender</span>
</td>
<td>
<input type="text" id="gender" required data-ng-model="Gender" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Date Of Brith</span>
</td>
<td>
<input type="text" id="dob" data-ng-model="DOB" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Moblie/Telephone No</span>
</td>
<td>
<input type="text" id="mobile" required data-ng-model="Mobile" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> House No/Door No</span>
</td>
<td>
<input type="text" id="house_no" required data-ng-model="House_No" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Streent Name</span>
</td>
<td>
<input type="text" id="streent_name" required data-ng-model="Streent_Name" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Country</span>
</td>
<td>
<input type="text" id="country" required data-ng-model="Country" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Post Code</span>
</td>
<td>
<input type="text" id="post_code" required data-ng-model="Post_Code" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Occupation</span>
</td>
<td>
<input type="text" id="occupation" required data-ng-model="Occupation" require="" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="CeditCardApplication" value="CeditCardApplication" data-ng-click="CeditCardApplication()" />
</td>
</tr>
</table>
<div style="color: red;">{{msg}}</div>
</td>
</tr>
</table>
</body>
</html>
Here is the screen shot when i run the application ..
The error is correct, you're missing a ) character and a }. Here's the code formatted a little better for ease of reading:
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Tittle = "";
$scope.First_Name = "";
$scope.Last_Name = "";
$scope.Gender = "";
$scope.DOB = "";
$scope.Mobile = "";
$scope.House_No = "";
$scope.Streent_Name = "";
$scope.Country = "";
$scope.Post_Code = "";
$scope.Occupation = "";
}
$scope.CeditCardApplication = function () {
var ApplicationDeatils = {
Tittle: $scope.Tittle,
First_Name: $scope.First_Name,
Last_Name: $scope.Last_Name,
Gender: $scope.Gender,
DOB: $scope.DOB,
Mobile: $scope.Mobile,
House_No: $scope.House_No,
Streent_Name: $scope.Streent_Name,
Country: $scope.Country,
Post_Code: $scope.Post_Code,
Occupation: $scope.Occupation
};
myService.ApplicationDeatilsCheck(ApplicationDeatils).then(function (pl) {
console.log(pl.data)
if (pl.data) {
$scope.msg = "User information is correct !"
myService.ApplicationCreditScoreCheck(ApplicationDeatils1).then(function (p2) {
console.log(p2.data)
if (p2.data) {
$scope.msg = "We can offer you £6000";
} else {
$scope.msg = "Application failed !";
console.log("Some error Occured" + err);
}
}, function (err) {
$scope.msg = "Application failed!";
console.log("Some error Occured" + err);
});
};
}); // <-- missing )
} // <-- missing }
}]);
app.service("myService", function ($http) {
this.ApplicationDeatilsCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccountCheck", JSON.stringify(ApplicationDeatils));
}
this.ApplicationCreditScoreCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/cheekCreditScore", JSON.stringify(ApplicationDeatils));
}
});
This is one of those times where indentation and code-readability is super important.
Am using this function for the form submission just after one last check of 2 fields. But when submitting the form using javascript it returns the Object is not a function error. Didnt pasted the entire code of this page. pasted the required fields for this function. Any helps appreciated
<script type="text/javascript">
function validamt(strval){
var letters = /^[0-9]+(\.[0-9]{1,2})?$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function validno(strval){
var letters = /^\d+$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function finalcheck(){
var discount=$("#discount").val();
var stax=$("#stax").val();
var err=0;
if(discount!="In Rupees only" || stax!="(%)"){
if(!validno(stax)){err=1; alert('Invalid Service Tax');$("#stax").focus();}
if(!validamt(discount)){err=1;alert('Invalid Discount Amount');$("#discount").focus();}
}
alert(err);
if(err==0){
try{
document.getElementById('billsetupprocess').action="storebilling.php";
document.getElementById('billsetupprocess').submit();
}
catch(e){
alert(e);
}
}
}
</script>
<form name="billsetupprocess" id="billsetupprocess" method="post" action="storebilling.php" enctype="multipart/form-data" >
<table>
<tr>
<td>Discount</td>
<td><input name="discount" type="text" class="txtclass" id="discount" value="<?php if($discount!=""){echo $discount;} else {echo("In Rupees only");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='In Rupees only'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='In Rupees only';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/></td>
<td></td>
<td> </td>
</tr>
<tr>
<td>servicetax</td>
<td><input name="stax" type="text" class="txtclass" id="stax" value="<?php if($discount!=""){echo $servicetax;}else {echo("(%)");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='(%)'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='(%)';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/>
</td>
<td></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input name="submit" id="submit" type="button" value="Save Setup" onclick="finalcheck()" class="btnclass" /></td>
<td> </td>
<td> </td>
</tr>
</table>
Basically my HTML looks like this:
<form method="post" name="htmlform" onsubmit = "checkFields()">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" size="30" maxlength="50"/>
/td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio" name="sex"
value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
When the form is submitted, the onsubmit() event checks if first_name textfield is blank, if it is then the label or span to its left is appended to output "first name*" + " you must enter a first name" and similarly for last name and sex.
The problem is that the text in the table does not update with appendchild. When I enclosed the statement in an alert for debugging the message is appended then disappears.
The JavaScript code is below for the onsubmit = "checkFields()".
function checkFields() {
var firstName = document.getElementById("first_name").value;
var lastName = document.getElementById("last_name").value;
if (firstName == "") {
//<span style='color:red'> Please enter a first name </span>
var nameHint = " Please enter a first name";
var node = document.getElementById("firstNameSpan");
//alert(node.appendChild(document.createTextNode(nameHint)) );
//not working
node.appendChild(document.createTextNode(nameHint));
} if (lastName == "") {
//additional code
}
}
Thanks in advance, your help is much appreciated. Also are there any JavaScript debuggers?
Regards
David D
I believe your sample code is not working due to incorrect html. document.getElementById("last_name") will return undefined.
http://jsfiddle.net/5E6my/1/
Thanks all, Im getting the ropes of JFiddle the split screen is very useful although the error messages are not useful for debugging. Here is the completed code (1) HTML (2) JavaScript.
<form method="post" name="htmlform" onsubmit="return checkFields();">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" id="last_name" size="30"
maxlength="50" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" id = "sexMessage">
Please select Male or Female*</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio"
name="sex" value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
The JavaScript code to react to the onsubmit button's unfilled fields in the form are: (any ways to make this code simpler??)
window.checkFields = function()
{
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
if(firstName.value == "")
{
//<span style='color:red'> Please enter a first name </span>
var nameHint = " *Please enter a first name ";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="red";
} else{
var nameHint = " First Name *";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="black";
}
if (lastName.value == "")
{
//additional code
var nameHint = " *Please enter a last name";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="red";
} else{
var nameHint = " Last Name *";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="black";
}
var radios = document.getElementsByName("sex");
var radioValue = ""
for(var i=0; i<radios.length; i++)
{
if(radios[i].checked)
{
radioValue = radios[i].value;
}
}
if(radioValue === "")
{
var sexNode = document.getElementById("sexMessage");
var nameHint = "*You did not choose a sex";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="red";
} else {
var sexNode = document.getElementById("sexMessage");
var nameHint = "Please select Male or Female*";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="black";
}
return false;
}
The trick is to use as Yury suggested was the onsubmit="return checkfields()" and then in the code block to use window.checkFields = function() { etc.
One question that I have... is JQuery a lot simpler to use, im learning JavaScript before JQuery... should I skip to JQUery instead. Also does JQuery support the AJAX framework?
Much appreciated
David
I have a drop down box and some text input fields below it. Based on which item from the drop down menu the user selects, I would like to disable some of the fields. I think I am failing to target the input fields correctly but I can't figure out what the problem is:
Here is the script I have gotten so far:
$(document).ready(function(){
var customfield = $('#customfields-tf-19-tf');
var customfield1 = $('#customfields-tf-20-tf');
var customfield2 = $('#customfields-tf-13-tf');
$(function() {
var call_table = {
'Condominium': function() {
customfield.attr("disabled");
},
'Co-Op': function() {
customfield1.attr("disabled");
},
'Condop': function() {
customfield2.attr("disabled");
}
};
$('#customfields-s-18-s').change(function() {
call_table[this.value]();
});
});
});
And the layout for my form:
<td width="260" class="left">
<label for="customfields-s-18-s">Ownership (Required):</label>
</td>
<td class="right">
<select name="customfields-s-18-s" class="dropdown" id="customfields-s-18-s" size="" >
<option value="Condominium"> Condominium</option>
<option value="Co-Op"> Co-Op</option>
<option value="Condop"> Condop</option>
</select>
</td>
</tr>
<tr>
<td width="260" class="left">
<label for="customfields-tf-19-tf">Maintenance:</label>
</td>
<td class="right">
<input type="text" title="Maintenance" class="textInput" name="customfields-tf-19-tf" id="customfields-tf-19-tf" size="40"/>
</td>
</tr>
<tr id="newsletter_topics">
<td width="260" class="left">
<label for="customfields-tf-20-tf">Taxes:</label>
</td>
<td class="right">
<input type="text" title="Taxes" class="textInput" name="customfields-tf-20-tf" id="customfields-tf-20-tf" size="40" />
</td>
</tr>
<tr>
<td width="260" class="left">
<label for="customfields-tf-13-tf" class="required">Tax Deductibility:</label>
</td>
<td class="right">
<input type="text" title="Tax Deductibility" class="textInput" name="customfields-tf-13-tf" id="customfields-tf-13-tf" size="40" />
</td>
</tr>
I believe that in order to disable an input you need to use:
$(input).attr("disabled", "disabled");
Also, some of these functions might prove useful for you:
$.fn.enable = function() {
return this.removeAttr('disabled');
}
$.fn.disable = function() {
return this.attr('disabled', 'disabled');
}
$.fn.disenable = function(val) {
if (val)
return this.enable();
else
return this.disable()
}
$.fn.toggleEnabled = function() {
if (this.attr('disabled') == 'disabled')
return this.enable();
else
return this.disable();
}
once they've been defined, you can then use them on any jQuery variable, like so:
$(input).toggleEnabled();