Form action attribute not working with js script [duplicate] - javascript

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

Related

How I get values updating/refreshing related input areas in Javascript?

I have a form and when I press the Try button it returns values for the 3rd and 6th input fields of the form according to the values entered in 1,2 and 5.6. Also, the 7th input field combines the 3rd and 6th results.
My question is how can I get the result values from input fields 3 and 6 without clicking the Try It button and also update the input field 7 without refreshing the page?
My code is in JSFiddle UPDATED !!
My Javascript are:
<script type="text/javascript">
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
function join_names() {
var input_name_first = document.getElementsByName('ht')[0].value;
var input_name_last = document.getElementsByName('ft')[0].value;
var input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(input_name_first, input_name_last, true);
input_name_full.value = var_name_full;
}
</script>
<script type="text/javascript">
function myFunctionFt() {
var home = document.getElementById("home_score").value;
var away = document.getElementById("away_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ft").value = results;
}
</script>
<script type="text/javascript">
function myFunctionHt() {
var home = document.getElementById("home_ht_score").value;
var away = document.getElementById("away_ht_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ht").value = results;
}
</script>
I have removed all the previous answers from this answer and added a new answer in place. I have read your last comment and you said that my code was not working for the Home Team HT Score and Away Team HT Score. Well, I had made the logic to behave this way because it makes more sense to put the result in HT Result once both of the teams have played or in other words when we have both of the inputs. In sports, it rarely happens that only one team plays. Right. So outputting the result in HT result based on one of the inputs makes no sense. But if this is what you want, you simply have to change the logic from if (!input_home || !input_away) return; to if (!input_home && !input_away) return; and it will start working the way you want. Basically in the first logic statement with "||" we are saying unless both of the inputs are available don't out into HT result and in the second statement with && we are saying id doesn't matter if one of them is not present, just take whatever is present and output it in HT result. The same thing is happening for FT. You just have to change || to &&.
Here is the final working code:
//FT and HT Result//
let name_first = document.getElementById('ht');
let name_last = document.getElementById('ft');
let input_name_first = name_first.value;
let input_name_last = name_last.value;
//HT Home//
let home = document.getElementById("home_ht_score");
let away = document.getElementById("away_ht_score");
home_ht_score.addEventListener("input", myFunctionHt);
away_ht_score.addEventListener("input", myFunctionHt);
let input_away = away.value;
let input_home = home.value;
//FT Home//
let home_ft = document.getElementById("home_score");
let away_ft = document.getElementById("away_score");
home_score.addEventListener("input", myFunctionFt);
away_score.addEventListener("input", myFunctionFt);
let input_ft_away = away_ft.value;
let input_ft_home = home_ft.value;
function myFunctionHt() {
input_away = away.value;
input_home = home.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_home && !input_away) return;
var results = "";
if (input_home > input_away) {
results = "1";
} else if (input_home < input_away) {
results = "2";
} else if (input_home = input_away) {
results = "X";
}
document.getElementById("ht").value = results;
join_names();
}
function myFunctionFt() {
input_ft_away = away_ft.value;
input_ft_home = home_ft.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_ft_home && !input_ft_away) return;
var results = "";
if (input_ft_home > input_ft_away) {
results = "1";
} else if (input_ft_home < input_ft_away) {
results = "2";
} else if (input_ft_home = input_ft_away) {
results = "X";
}
document.getElementById("ft").value = results;
join_names();
}
function join_names() {
if (!input_name_first && !input_name_last) return;
let input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(name_first.value, name_last.value, true);
input_name_full.value = var_name_full;
}
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="form-group" action="addemp" method="post" onsubmit="return true" onClick="return false">
<table border="0" cellpadding="1">
<tbody>
<tr>
<td> <label class="form-label" style="color:blue" for="name">Home Team HT Score</label> </td>
<td> <input id="home_ht_score" name="home_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:red" for="name">Away Team HT Score</label> </td>
<td> <input id="away_ht_score" name="away_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT Result</label> </td>
<td> <input id="ht" name="ht" type="text" class="form-control mb-3" oninput="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:blue" for="name">Home FT Score</label> </td>
<td> <input id="home_score" name="home_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:red" for="name">Away FT Score</label> </td>
<td> <input id="away_score" name="away_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:green" for="name">FT Result</label> </td>
<td> <input id="ft" name="ft" type="text" class="form-control mb-3" onchange="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT/FT</label> </td>
<td> <input name="htft" type="text" class="form-control mb-3" style="width: 200px;"> </td>
</tr>
<tr>
<td> </td>
<td><button class="btn btn-primary mb-4" type="submit">Save Match Result</button> </td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Angular js model value changes are not reflected in ui

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

Form validation without error on IE

I have a html code saved as a php, the form validation works in google chrome but not in IE. In IE after I hit the submit button, the page automatically goes to process form regardless of errors.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validateForm() {
var errors = 0;
var fName = document.forms["orderForm"].firstName.value;//first name validation
if (fName == null || fName == "")
{
document.getElementById('firstNameError').innerHTML = "Please enter a first name.";
errors++;
} else {
document.getElementById('firstNameError').innerHTML = "";
}
//var lName = document.forms["orderForm"].lastName.value;//last name validation
if (lName == null || lName == "")
{
document.getElementById('lastNameError').innerHTML = "Please enter a last name.";
errors++;
} else {
document.getElementById('lastNameError').innerHTML = "";
}
//var address = document.forms["orderForm"].address.value;//address validation
if (address == null || address == "")
{
document.getElementById('addressError').innerHTML = "Please enter an address.";
errors++;
} else {
document.getElementById('addressError').innerHTML = "";
}
//var city = document.forms["orderForm"].city.value;//city validation
if (city == null || city == "")
{
document.getElementById('cityError').innerHTML = "Please enter a city.";
errors++;
} else {
document.getElementById('cityError').innerHTML = "";
}
//var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if (pCodeCheck)
{
document.getElementById('postalCoderror').innerHTML = "";
}
else
{
document.getElementById('postalCoderror').innerHTML = "Please enter a valid postal code.";
errors++;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if (itemQTY < 0)
{
document.getElementById('qtyError').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError').innerHTML = "";
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if (itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError2').innerHTML = "";
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if (itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError3').innerHTML = "";
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if (wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML = "You must order atleast one item.";
errors++;
} else {
document.getElementById('itemQTY').innerHTML = "";
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3);
alert('Your total is: $' + total4 + '.00');
return errors;
}
function startValidate() {
var errors = validateForm();
if (errors == 0) {
document.forms['orderForm'].submit();
} else {
return false;
}
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" action="processForm.html" onsubmit="return startValidate()">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Quebec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
When you look at the console in IE’s developer tools (F12), you will see that there is an error message about undeclared variable lName. This causes the error checking to be aborted.
You have several lines like
//var lName = document.forms["orderForm"].lastName.value;//last name validation
Since // starts a comment in JavaScript, the line has no effect. The variable lName is not declared or defined elsewhere either.
So you need to remove those // comment starters. Note that the code does not work in Chrome either; you may have tested a different version in Chrome, or misinterpreted some behavior.
In the console, you can also see a message for line 237 about “unexpected identifier”. It is actually a serious HTML markup error; IE reports some of such errors, in a strange way. The error is that a tr element has an input element as child, which is forbidden in HTML syntax. This is why the Submit Order and Reset Form appear on top of each other and not on the same row as intended. (For usability, the Reset Form button should be removed, but I digress.)

JavaScript checking & adding text to a table dynamically on submit button click

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

Disable input fields based on selection from drop down

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();

Categories

Resources