Why does the JavaScript code stop execution after the for loop - javascript

This is my try at creating a registration page however after the for loop whatever follows does not execute and I'm at a loss as to why?
Below is the javascript code and the form
<script type='text/javascript'>
myArray = ['username','email','password','password2'];
reply = ['User Name','Email','Password','Password Again'];
message = "Please Type you're ";
start = "<font color = red size='-1'>";
end = "</font>";
test = 10;
obj = validate();
alert (obj);
function validate(){
for (var i=0; i<=myArray.length; i++) {
if (document.getElementById("in"+myArray[i]).value == "")
{
document.getElementById(myArray[i]).innerHTML = start+message+reply[i]+end;
test = 30;
}
}
alert ("test");
}
<form action="echo.php" method="post" name="register" onsubmit="return validate();">
<table>
<tr>
<td width="185"><font size="2">First Name</font></td>
<td width="499">
<input id = "infirst_name" name="first_name" type="text" /><div id="first_name"></div></td>
</tr>
<tr>
<td><font size="2">Last Name</font></td>
<td><input id = "inlast_name" name="last_name" type="text" /><div id="last_name"></font></div></td>
</tr>
<tr>
<td><font size="2">Username*</font></td>
<td>
<input id = "inusername" name="username" type="text" /><div id="username"></div></td>
</tr>
<tr>
<td><font size="2">Email*</font></td>
<td><input id = "inemail" name="email" type="text" /><div id="email"></div></td>
</tr>
<tr>
<td><font size="2">Password*</font></td>
<td><input id = "inpassword" name="password" type="password" /><div id="password"></div></td>
</tr>
<tr>
<td><font size="2">Repeat Password*</font></td>
<td>
<input id = "inpassword2" name="password2" type="password" /><div id="password2"></div></td>
</tr>
<tr>
<tr>
<td><font size="2">I have read and Agree to the Terms and Conditions</font></td>
<td>
<input id = "incheckme" name="checkme" type="checkbox" /><div id="checkme"></div></td>
</tr>
<tr>
<td><input type="submit" value="Register" /></td>
<td> </td>
</tr>
</table>
</form>

Try fixing your loop:
for (var i=0; i < myArray.length; i++) {
JavaScript will stop executing anything if it encounters an uncaught error. In your case it seems that you've looped past the last element (and tried to set innerHTML on an undefined object).

Most likely because you iterate past the end of the array, but reference it like there's something there.

See JS console output: perhaps it says that you have an error.
i falls out of myArray length: change the loop condition from "i<="to "i<" and you'll be fine.

Related

Enable / Disable many radioButtons having different ids

What I have built so far is that I have a form with a few radioButtons and a password field.
Now, I want to activate the password field as soon as the corresponding radioButton is clicked.
That would work so far, if id for all password fields would not be the same.
This is my code so far:
<form action="#" th:action="#{/passwordaenderung}" th:object="${UserCreationDto}" method="post" onsubmit="return checkPassword()">
<fieldset>
<table>
<thead>
<tr>
<th>Username</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<tr th:each="user, itemStat : *{users}">
<td><input type="radio" name="radiobutton" th:value="*users[__${itemStat.index}__].username}" id="raidoButtonCheck" onclick="document.getElementById('pwd').removeAttribute('disabled')" /></td>
<td><input th:field="*users[__${itemStat.index}__].username}" disabled/></td>
<td><input type="password" name="passwordField" th:field="*{users[__${itemStat.index}__].password}" id="pwd" disabled/></td>
</tr>
</tbody>
</table>
<input type="submit" id="submitButton" th:value="Speichern">
</fieldset>
</form>
So, does it look like in my browser:
And so does the interpreted / compiled code look like:
I hope someone can tell me please how do I get a different id for all password fields so that the correct one will be enabled via the
document.getElementById('pwd').removeAttribute('disabled')
You can dynamically set the ids of each input using th:id. You can use the iterator index so that it can be unique. The following code should work.
<tr th:each="user, itemStat : *{users}">
<td><input type="radio" name="radiobutton" th:value="*users[__${itemStat.index}__].username}" class="radioButton" th:onclick="${'document.getElementById('''+ itemStat.index +''').removeAttribute(''disabled'')'}" /></td>
<td><input th:field="*users[__${itemStat.index}__].username}" disabled/></td>
<td><input type="password" name="passwordField" th:field="*{users[__${itemStat.index}__].password}" th:id="${itemStat.index}" disabled/></td>
</tr>
If you want to disable all other inputs, when you click on one of them, then I would recommend adding a class to all inputs and changing your on click for function.
JS
<script>
function inputClick(id) {
var passwordFields = document.getElementsByClassName("passwordField");
for(i = 0; i < passwordFields.length; i++) {
passwordFields[i].disabled = true;
}
document.getElementById(id).removeAttribute('disabled');
}
</script>
HTML
<tr th:each="user, itemStat : *{users}">
<td><input type="radio" name="radiobutton" th:value="*users[__${itemStat.index}__].username}" class="radioButton" th:onclick="${'inputClick('''+ itemStat.index +''')'}" /></td>
<td><input th:field="*users[__${itemStat.index}__].username}" disabled/></td>
<td><input class="passwordField" type="password" name="passwordField" th:field="*{users[__${itemStat.index}__].password}" th:id="${itemStat.index}" disabled/></td>
</tr>
The js can be added somewhere in the head or body or in a external js file.

Implementing submit event in a form

How do I get the data of a form upon clicking the a submit type button like so:
var x = form_submit.username;
var y = form_submit.password;
var z = form_submit.full_name;
and also stop the form from disappearing upon clicking the "Submit" button with the code below?
<form id="form_submit">
<input type="text" id="username" name="username" required>
<table>
<tr>
<th align="left">Full Name</th><td><input type="text" id="full_name" required></td>
</tr>
<!--<tr>
<th align="left">Username</th><td><input type="text" id="username" required></td>
</tr>-->
<tr>
<th align="left">Password</th><td><input type="password" id="full_name" required></td>
</tr>
<tr>
<th align="left">Confirm Password</th><td><input type="password" id="confirm_password" required></td>
</tr>
<tr>
<th align="left">Department</th><td><input type="text" id="department" required></td>
</tr>
<tr>
<th align="left">Supervisor</th>
<td>
<select id="supervisor">
<? for(var i in supervisors){ ?>
<option value="<?=supervisors[i] ?>"><?=supervisors[i]?></option>
<?}?>
</select>
</td>
</tr>
<tr>
<th align="left">E-mail Address</th><td><input type="email" id="email" required></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Create Account" id='btn_create'></td>
</tr>
</table>
</form>
<?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form_submit').submit(function(e){
e.preventDefault();
var username = $('input[name="username"]', this).val();
alert(username);
});
});
}
</script>
I'm guessing that I should be using the "event.preventDefault()" method but I don't know where to place it.
P.S. I am using Google Sites, if it would make any difference. Thank you.
P.P.S.
Edited my post to show the right answer.
How about something as simple as that - it seems to be working - perhaps it will fit your needs
update:
From what I checked you can address the form children easily if you give them id. for example you can currently do form_submit.children.username and get the value. if you will put IDs also on all the other tags like table, tr, th, etc. you will be able to dig deeper
var form_submit = document.getElementById("form_submit");
var username = form_submit.children.username.value;
update 2:
I`ve moved the script to the bottom of the body tag so I could get refernce to the submit button. Once got the button I registered to the "click" event using addEventListener. Now the PreventDefault method worked
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form_submit">
<input type="text" id="username" name="username" required/>
<table>
<tr>
<th align="left">Full Name</th>
<td>
<input type="text" id="full_name" required/>
</td>
</tr>
<tr>
<th align="left">Password</th>
<td>
<input type="password" id="full_name" required/>
</td>
</tr>
<tr>
<th align="left">Confirm Password</th>
<td>
<input type="password" id="confirm_password" required/>
</td>
</tr>
<tr>
<th align="left">Department</th>
<td>
<input type="text" id="department" required/>
</td>
</tr>
<tr>
<th align="left">Supervisor</th>
</tr>
<tr>
<th align="left">E-mail Address</th>
<td>
<input type="email" id="email" required/>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Create Account" id='btn_create'/>
</td>
</tr>
</table>
</form>
<script>
var button = document.getElementById("btn_create");
if (button)
button.addEventListener('click', createAccount, false);
function createAccount(evt){
var form_submit = document.getElementById("form_submit");
var isValid = form_submit.checkValidity();
alert('isValid: ' + isValid);
var username = form_submit.children.username.value;
evt.preventDefault();
return false;
}
</script>
</body>
</html>
To prevent the form to actually been submitted and process the data, you must cancel the event by returning false in your called function, pay special attention that you need to use the return statement in your onClick parameter.
onclick="createAccount(this.parentNode)"
=>
onclick="return createAccount(this.parentNode)"
function createAccount(frmData){
alert(document.getElementById("form_submit").elements.namedItem("username").value);
return false;
}

Unable to fetch the input values from the form in jquery

I am fetching the values from the form page and then validating it. I am using jquery to handle the input objects and fetch the values which are entered by the user.
My HTML code is:
<form id="userDetails">
<table class="containFormTable" cellspacing="8">
<tr>
<td class="detail">Name:</td>
<td>
<input name="name" type="text" id="name" />
</td>
</tr>
<tr>
<td class="detail">Email-Id:</td>
<td>
<input name="emailId" type="text" id="emailId">
</td>
</tr>
<tr>
<td class="detail">Phone-No:</td>
<td>
<input name="phoneNo" type="text" id="phoneNo">
</td>
</tr>
<tr>
<td colspan="2" style="padding-top: 50px">
<input type="button" value="Submit" id="submit">
</td>
</tr>
</table>
</form>
My javascript file code which is fetching the data is:
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#name').find('input[name="name"]').val();
var emailId = $('#emailId').find('input[name="emailId"]').val();
var phoneNo = $('#phoneNo').find('input[name="phoneNo"]').val();
});
});
The result I am getting in the variable name or any other is "undefined".
Where am I going wrong in it?
All you need to do is get the value from the elements, like this:
var name = $('#name').val();
var emailId = $('#emailId').val();
var phoneNo = $('#phoneNo').val();
Your code was getting a reference to the form fields, then looking for child elements (which input elements don't have, hence undefined) that were the same as the element that you already found and then trying to get the value of that.
Just remove .find('input[name="name"]') from each selector
$(document).ready(function(){
$('#submit')
.click(
function() {
var name = $('#name').val();
var emailId = $('#emailId').val();
var phoneNo = $('#phoneNo').val();
console.log(name);
console.log(emailId);
console.log(phoneNo);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userDetails">
<table class="containFormTable" cellspacing="8">
<tr>
<td class="detail">Name:</td>
<td><input name="name" type="text" id="name"/></td>
</tr>
<tr>
<td class="detail">Email-Id:</td>
<td><input name="emailId" type="text" id="emailId"></td>
</tr>
<tr>
<td class="detail">Phone-No:</td>
<td><input name="phoneNo" type="text" id="phoneNo"></td>
</tr>
<tr >
<td colspan="2" style="padding-top: 50px"><input type="button" value="Submit" id="submit"></td>
</tr>
</table>
</form>

Validate a form at the client side

I wish to validate a form at the client side (before submit to server). I have a script to search for special characters (~!##) etc. If at least one exists, form should not be submitted until the user corrects the error(s). Here is my form:
<form id="setUp" method="post" action="Usercontact.php">
<table id="contact">
<tbody>
<tr>
<th class="cdtl">Name of user:</td>
<td><input type="text" name='username' required /></td>
</tr>
<tr>
<th class="cdtl">Course</td>
<td><input type="text" name='useraddy1' required /></td>
</tr>
<tr>
<th class="cdtl">Telephone</td>
<td><input type="text" name='userfone' required /></td>
</tr>
<tr>
<th class="cdtl">e-mail Address</td>
<td><input type="email" name='schemail' required /></td>
</tr>
</tbody>
</table>
<br>
<input id="postform" type="submit" onclick="err()" value="Submit form">
</form>
Below is the script
<script>
function err() {
var tbl = document.getElementById("contact");
var name = tbl.rows[0].cells[1].getElementsByTagName("input")[0].value;
var addy = tbl.rows[1].cells[1].getElementsByTagName("input")[0].value;
var fone = tbl.rows[2].cells[1].getElementsByTagName("input")[0].value;
var email = tbl.rows[3].cells[1].getElementsByTagName("input")[0].value;
var namepos = name.lastIndexOf("~`!##$%^&*)(+=}{][|\:;'.'/"',>?<");
var addypos = addy.lastIndexOf("~`!##$%^&*)(+=}{][|\:;'.'/"',>?<");
var fonepos = fone.lastIndexOf("~`!##$%^&*)(+=}{][|\:;'.'/"',>?<");
var emailpos = name.lastIndexOf("~`!##$%^&*)(+=}{][|\:;'.'/"',>?<");
if (namepos !== -1 || addypos !== -1 || fonepos !== -1 || emailpos !==
-1) {
document.getElementById("postform").addEventListener("click",
function(event){
event.preventDefault()
});
}
}
</script>
Please why is this script not working. The form is submitted even when there are special characters in any of the input fields. Appreciate
This line:
var namepos = name.lastIndexOf("~`!##$%^&*)(+=}{][|\:;'.'/"',>?<");
is checking for the entire string ("~`!##$%^&*)(+=}{][|:;'.'/"',>?<"), not each character.
As suggested in the comments, you could use the HTML5 pattern attribute:
<input name="name" pattern="[A-Za-z]{3,12}">
This would require the name to include only letters and range in length from 3 to 12 characters.
To use a regular expression to test for all the characters you listed, you could use:
var re=/[~`!##$%^&*)(+=}{\]\[|\:;'.'\"',>?<]/
var str="this#that";
if (re.test(str)) {
console.log('The string has one of the characters');
} else {
console.log('The string does not have any of the characters');
}
You need to include event. PreventDefault().. This will prevent the form from submitting if you find characters you are checking for or anything else you might be checking for.
Following suggestions above, I have now a working doc as follows:
<form id="setUp" method="post" action="Usercontact.php">
<table id="contact">
<tbody>
<tr>
<th class="cdtl">Name of user:</td>
<td><input type="text" name='username' required pattern="[A-Za-z0-9.-_]
{5,12}"/></td>
</tr>
<tr>
<th class="cdtl">Course</td>
<td><input type="text" name='useraddy1' required pattern="[A-Za-z0-9]{5,15}"
/></td>
</tr>
<tr>
<th class="cdtl">Telephone</td>
<td><input type="text" name='userfone' required pattern="[0-9.-_]{6,15}" />
</td>
</tr>
<tr>
<th class="cdtl">e-mail Address</td>
<td><input type="email" name='schemail' required pattern="[A-Za-z0-9.-_#]"
/></td>
</tr>
</tbody>
</table>
<br>
<input id='submit' type="submit" value="Submit form">
</form>
The script was removed as there is no need for it.

JavaScript - writing value into html form from script

I was wondering how I could input a value into a form with html.
So right when the user goes to the site there's numbers in the text boxes already and they use those numbers to play and "addition game".
This is what I have so far:
<script type="text/javascript">
function addSubmit() {
//trying to have num1 and num2 write into the html form
var num1= Math.floor(89+Math.random()*11);
var num2 = Math.floor(89+Math.random()*11);
/*num1 = value1
num2 = value2*/
document.getElementById("value1").value = num1;
document.getElementById("value2").value = num2;
var guess = document.getElementById("submit").value;
var answer = num1 + num2;
//have to write this to main window
if (guess == answer)
document.writeln("Congratulations you answered correctly! The answer to: "+num1+"+"+num2+"= "+answer);
else
document.writeln("Nice try, but the correct answer to: "+num1+"+"+num2+"= "+answer);
}
function addGiveUp() {
var num1 = Math.floor(89+Math.random()*11)
var num2 = Math.floor(89+Math.random()*11)
document.addition.value1.value=num1;
document.addition.value2.value=num2;
var guess = document.getElementById("submit").value;
var answer = (document.getElementById("value1").value) + (document.getElementById("value2").value);
document.writeln("Never give up! The answer to: "+num1+"+"+num2+"= "+answer);
}
</script>
<form name="addition" action="" method="get">
<table border="1">
<tr>
<td>Value 1:</td> <td><input type="text" name="value1" id="value1"/></td>
</tr>
<tr>
<td>Value 2:</td> <td><input type="text" name="value2" id="value2"/></td>
</tr>
<tr>
<td>Answer:</td> <td><input type="text" id="answer" /></td>
</tr>
<tr><td><input type="button" value="Submit" onClick="addSubmit()" id="submit" /></td><td><input type="button" value="Give Up" onClick="addGiveUp()" /></td></tr>
</table>
</form>
I appreciate any help! Thanks!
well you can put this script after the form is created:
<form name="addition" action="" method="get">
<table border="1">
<tr>
<td>Value 1:</td> <td><input type="text" name="value1" id="value1"/></td>
</tr>
<tr>
<td>Value 2:</td> <td><input type="text" name="value2" id="value2"/></td>
</tr>
<tr>
<td>Answer:</td> <td><input type="text" id="answer" /></td>
</tr>
<tr><td><input type="button" value="Submit" onClick="addSubmit()" id="submit" /></td><td><input type="button" value="Give Up" onClick="addGiveUp()" /></td></tr>
</table>
</form>
<!-- This is the script-->
<script type="text/javascript">
document.getElementById("value1").value = Math.floor(89+Math.random()*11);
document.getElementById("value2").value = Math.floor(89+Math.random()*11);​
</script>
That would generate random numbers for you and put them in the form
See here for the code: http://jsfiddle.net/wVAFt/
<input type="text" id="answer" value="5" >
or
document.getElementById("answer").value = "5";
To have numbers in input fields you can set them to have a value, like value="10" and the default value would be 10 until the user changes it.

Categories