Form Displays Input Warning But Still Submits - javascript

I have a form in which I want users to input data. However, I do not want users to insert certain words. The code I have added recognizes these words and a popup message appears. When the user acknowledges the message, the form submits the data regardless. I've no idea why this happens. The code is listed below.
HTML Form
<form name="form1" action="#" method="post" required>
<label>Line 1: </label>
<input type="text" name="firstline" required onClick="select_area()"><br/>
<label>Line 2: </label>
<input type="text" name="secondline" required onClick="select_area2()"><br/>
<label>Line 3: </label>
<input type="text" name="thirdline" required onClick="select_area3()"><br/>
<input type="submit" name="submit_btn" id="submit" value="Submit" onClick="validate_text();">
<input type="reset" id="reset" value="Reset">
</form>
JavaScript File
var swear_words_arr=new Array("word1","word2","word3");
var swear_alert_arr=new Array;
var swear_alert_count=0;
function reset_alert_count()
{
swear_alert_count=0;
}
function validate_text()
{
reset_alert_count();
var compare_text=document.form1.firstline.value;
for(var i=0; i<swear_words_arr.length; i++) {
for(var j=0; j<(compare_text.length); j++) {
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var compare_text=document.form1.secondline.value;
for(var i=0; i<swear_words_arr.length; i++) {
for(var j=0; j<(compare_text.length); j++) {
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var compare_text=document.form1.thirdline.value;
for(var i=0; i<swear_words_arr.length; i++) {
for(var j=0; j<(compare_text.length); j++) {
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var alert_text="";
for(var k=1; k<=swear_alert_count; k++){
alert_text+="\n" + "(" + k + ") " + swear_alert_arr[k-1];
}
if(swear_alert_count>0) {
alert("The message will not be sent!!!\nThe following illegal words were found:\n_______________________________\n" + alert_text + "\n_______________________________");
document.form1.text.select();
} else {
document.form1.submit();
}
}
function select_area()
{
document.form1.firstline.select();
}
function select_area2()
{
document.form1.secondline.select();
}
function select_area3()
{
document.form1.thirdline.select();
}
window.onload=reset_alert_count;

There is no part in your function that blocks the action of the form.
For example, like 'return false' or 'preventdefault'.
You can use onClick, but onsubmit is recommended so that you can use the function to submit via keyboard.
var swear_words_arr = new Array("word1", "word2", "word3");
var swear_alert_arr = new Array;
var swear_alert_count = 0;
function reset_alert_count() {
swear_alert_count = 0;
}
function validate_text() {
reset_alert_count();
var compare_text = document.form1.firstline.value;
for (var i = 0; i < swear_words_arr.length; i++) {
for (var j = 0; j < (compare_text.length); j++) {
if (swear_words_arr[i] == compare_text.substring(j, (j + swear_words_arr[i].length)).toLowerCase()) {
swear_alert_arr[swear_alert_count] = compare_text.substring(j, (j + swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var compare_text = document.form1.secondline.value;
for (var i = 0; i < swear_words_arr.length; i++) {
for (var j = 0; j < (compare_text.length); j++) {
if (swear_words_arr[i] == compare_text.substring(j, (j + swear_words_arr[i].length)).toLowerCase()) {
swear_alert_arr[swear_alert_count] = compare_text.substring(j, (j + swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var compare_text = document.form1.thirdline.value;
for (var i = 0; i < swear_words_arr.length; i++) {
for (var j = 0; j < (compare_text.length); j++) {
if (swear_words_arr[i] == compare_text.substring(j, (j + swear_words_arr[i].length)).toLowerCase()) {
swear_alert_arr[swear_alert_count] = compare_text.substring(j, (j + swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var alert_text = "";
for (var k = 1; k <= swear_alert_count; k++) {
alert_text += "\n" + "(" + k + ") " + swear_alert_arr[k - 1];
}
if (swear_alert_count > 0) {
alert("The message will not be sent!!!\nThe following illegal words were found:\n_______________________________\n" + alert_text + "\n_______________________________");
return false;
//document.form1.text.select(); <- This is incorrect syntax.
}
}
function select_area() {
document.form1.firstline.select();
}
function select_area2() {
document.form1.secondline.select();
}
function select_area3() {
document.form1.thirdline.select();
}
window.onload = reset_alert_count;
<form name="form1" action="#" method="post" onsubmit="return validate_text();">
<label>Line 1: </label>
<input type="text" name="firstline" required onClick="select_area()"><br />
<label>Line 2: </label>
<input type="text" name="secondline" required onClick="select_area2()"><br />
<label>Line 3: </label>
<input type="text" name="thirdline" required onClick="select_area3()"><br />
<input type="submit" name="submit_btn" id="submit" value="Submit">
<input type="reset" id="reset" value="Reset">
</form>

Related

Javascript form clears instantly and flashes one answer

I have an html page that uses a javascript as a statistical calculator, it just needs to print the results into the text boxes i have displayed, but when i hit my submit button, the screen displays the mean value for a split second. no other fields work or stay.
My html file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<script src="script.js"></script>
<title>Script Calculator</title>
</head>
<body class="calculator">
<h2 class="stats">Statistical Calculator</h2>
<p> Enter 5-20 values within 0-100 inside the box below.<br>
Each value should be separated by one space.
</p>
<form>
<textarea id="numbers" name="numberarea" rows="4" cols="40"></textarea> <br>
<br>
<input type="submit" id="subbutton" onclick="performStatistics()"
value="Submit">
<input type="reset">
<br><br>
Max: <input type="text" id ="maxnum" name="max" readonly>
<br>
Min: <input type="text" id="minnum" name="min" readonly>
<br>
Mean: <input type="text" id="meannum" name="mean" readonly>
<br>
Median: <input type="text" id="mednum" name="med" readonly>
<br>
Mode: <input type="text" id="modenum" name="mode" readonly>
<br>
Standard Deviation: <input type="text" id="stddev" name="std" readonly>
<br>
Sum: <input type="text" id="sumnum" name="sum" readonly>
<br>
Variance: <input type="text" id="varinum" name="vari" readonly>
<br>
</form>
<hr>
ePortfolio
</body>
</html>
My javascript is as follows:
function performStatistics() {
var newarray = document.getElementById("numbers").value;
var array = newarray.split(" ");
for (var i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > 100) {
alert("Enter positive values from 0-100")
return false;
}
}
if (array.length < 5 || array.length > 20) {
alert("Enter at least 5 values & no more than 20");
return false;
}
document.getElementById("meannum").value = calcMean(array);
document.getElementById("mednum").value = calcMedian(array);
document.getElementById("modenum").value = calcMode(array);
document.getElementById("stddev").value = calcStdDev(array);
document.getElementById("sumnum").value = calcSum(array);
document.getElementById("varinum").value = calcVariance(array);
document.getElementById("maxnum").value = findMax(array);
document.getElementById("minnum").value = findMin(array);
return false;
}
function calcMean(array) {
return calcSum(array) / array.length;
}
function calcMedian(array) {
var med = 0;
var arraylen = array.length;
arraylen.sort();
if (arraylen % 2 === 0) {
med = (array[arraylen / 2 - 1] + array[arraylen / 2]) / 2;
//takes average of an even array
} else {
med = array[(arraylen - 1) / 2];
//takes middle value of odd array
}
return med;
}
function calcMode(array) {
var mode = [];
var counter = [];
var i;
var holder;
var maxfreq = 0;
for (i = 0; i < array.length; i += 1) {
holder = array[i];
counter[array] = (counter[holder] || 0) + 1
if (counter[holder] > maxfreq) {
maxfreq = counter[holder];
}
}
for (i in counter)
if (counter.hasOwnProperty(i)) {
//returns boolean value^
if (counter[i] === maxfreq) {
mode.push(Number(i));
//pushes value into (end of) array
}
}
return mode;
}
function calcStdDev(array) {
return Math.sqrt(calcVariance(array)).toFixed(2);
}
function calcSum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += Number(array[i]);
}
return sum.toFixed(2);
}
function calcVariance(array) {
var avg = calcMean(array);
var newarray = [];
var vari;
for (i = 0; i < array.length; i++) {
newarray[i] = (array[i] - avg) * (array[i] - avg);
}
vari = calcSum(newarray) / newarray.length;
return vari.toFixed(2);
}
function findMax(array) {
var newarray = array;
var maxnum = Math.max(newarray);
return maxnum;
}
function findMin(array) {
var newarray = array;
var minnum = Math.min(newarray)
return minnum;
}
You need to prevent the submit button from submitting the form.
window.onload=function(){
document.getElementById('subbutton').addEventListener('click', function(ev){
ev.preventDefault(); // prevent the page submit
});
}
You can remove the onclick from the HTML, and add this to your script:
// When the DOM (HTML) is ready
addEventListener('DOMContentLoaded', function() {
// When the form gets submitted (click on submit or enter key)
document.forms[0].addEventListener('submit', function (event) {
performStatistics();
// Prevent the form from refreshing the page
event.preventDefault();
});
});
Note: your script is included in the <head> of your document. Waiting for DOMContentLoaded will ensure the document is ready no matter where your script is called. But you could skip that part if you include your script at the very bottom, before the closing </body> tag.

JavaScript change background color of input field in specified value

I'm going to use JavaScript for changing color of input field in specified value. I've created it, but it doesn't work, the input field background color didn't changed.
[...] other fields
<td>
<input type="text" name="ha_tpc[]" id="ha_tpc" onkeyup="getWarning()" size="5" value="<?php $a=set_value('ha_tpc[0]'); echo $a; ?>"/></td>
[...] other fields
and here the javascript:
<script type="text/javascript">
function getWarning() {
var obj = document.getElementsByTagName('input');
for(var i=0; i<obj.length; i++) {
if (obj[i].name == "ha_tpc[]") {
var hatpc = obj[i].value;
if (hatpc != 5) {
document.bgColor = "#E74C3C";
};
}
}
}
</script>
function getWarning() {
var obj = document.getElementsByTagName('input');
for(var i=0; i<obj.length; i++) {
if (obj[i].name == "ha_tpc[]") {
var hatpc = obj[i].value;
if (hatpc != 5) {
document.bgColor = "#E74C3C";
obj[i].style.backgroundColor = "green";
};
}
}
}
<input type="text" name="ha_tpc[]" id="ha_tpc" onkeyup="getWarning()" size="5" />
obj[i].style.backgroundColor = "green";
You forgot to add it to input.

HTML --- Javascript/JSON

okay here is the question -- .. i tried it but my js isn't working and idk where i am wrong here is the question
THE PROBLEM IS AFTER THE JS EXECUTED IT DOESN'T RUN ... LIKE IDK WHERE THE PROBLEM IS ; I KNOW IT LOADS BUT IT DOES'NT WORK
<html>
<head>
<script src="q2.js" type="text/javascript"> </script>
</head>
<div > Input 1 <input type="text" id ="input1"></div>
<div> Input 2 <input type="text" id ="input2"> </div>
<div> Result <div id="result"> </div></div>
<button onclick= "compute()">Compute</button>
</body>
</html>
the js is here
function compute(){
var n = (document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var i,j;
if (Number(n)){
}
else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)){
}
else {
alert("Error! Please put a valid Number - on input 2 ");
}
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
result.innerHTML += "X";
if(j == (m-1)){
result.innerHTML += "<br />";
}
}
}
}
result.innerHTML += "X";
You forgot to set the variable result:
var result = document.getElementById("result");
And there is a loneley ( in var n = (document.getElementById("input1").value; wich will through syntax error
And you might want to clear the content of your "result"-container when calling the function again: result.innerHMLT = ''
function compute() {
var n = document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var result = document.getElementById("result");
result.innerHMLT = ''
var i, j;
if (Number(n)) {} else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)) {} else {
alert("Error! Please put a valid Number - on input 2 ");
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
result.innerHTML += "X";
if (j == (m - 1)) {
result.innerHTML += "<br />";
}
}
}
}
<div>Input 1
<input type="text" id="input1">
</div>
<div>Input 2
<input type="text" id="input2">
</div>
<div>Result
<div id="result"></div>
</div>
<button onclick="compute()">Compute</button>

Javascript to alert a user that the same info has already been entered

First I should say I am a javascript newbie so forgive my ignorance.
I'm creating a form that has three functions and also uses array:
Add - To accept a name (if field left blank it should ask the user to enter a name in an alert box)
Find - To verify a name has not already been entered (in an alert box)
List - To list the names that have been entered (in an alert box)
I have the list function working (good). The alert to enter a name comes up after you enter a name as well as when you leave the field blank (not good)
and I can't get the find function to work at all.
My code is below and I've tried so many iterations and searched so many sites for help, also tried firebug; I'm hoping someone can point me in the right direction.
Untitled
<body>
<script type="text/javascript">
var a = new Array();
function list() {
var s = "";
for (i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add() {
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
if (myTextField.value == "") {
alert("Please enter a name");
return false;
}
function find() {
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField) {
alert("Sorry, the name " + a[i] + " already exists. Try again");
}
}
}
</script>
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="list()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
</body>
</html>
You have done it almost, but some lil errors.. here you can check it jsfiddle
HTML:
<input type="text" id="myText" /><br>
<input type="button" value="Add a name" class="add_button"/>
<input type="button" value="List the names" class="list_button"/>
<input type="button" value="Find" class="find_button"/>
JS:
$(".add_button").live("click", function(){
add()
});
$(".list_button").live("click", function(){
list()
});
$(".find_button").live("click", function(){
find()
});
var a = new Array();
function list()
{
var s = "";
for(i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
if (myTextField.value == "")
{
alert ("Please enter a name");
return false;
}
myTextField.value = "";
}
function find()
{
//If the name already exists you should get a warning
var status = true;
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
{
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
status = false;
break;
}
}
if(status==true)
{
a[a.length] = myTextField.value;
}
myTextField.value = "";
}
The code had a couple of errors, here's a working version: http://jsfiddle.net/sAq2m/2/
html:
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="listItems()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
js:
var a = [];
function listItems()
{
var s = "";
for(var i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
return false;
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
var v = myTextField.value
if (!v){
v = prompt("You have not entered a name, please enter one.");
}
a.push(v);
console.log(a);
myTextField.value = "";
return false;
}
function find()
{
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
return;
}
}

onBlur in innerHtml blocks the function

I have 2 functions, one that is creating dynamicly a table with input fields, which dimensions are based on a variable k, inserted by the user, and another one that reads the values inserted again by the user in every field of the table and inserts them in a 2 dimensional array that I can call later.
The problem is that the create table function does not work with onBlur inserted in it's code.
The code is as follows:
<head>
<script>
var k;
function genArray () {
var A = [];
for (var i = 0; i < k; i++) {
A[i] = [];
for (var j = 0; j < k; j++) {
var id = "A" + (i + 1) + (j + 1);
A[i][j] = parseFloat(document.getElementById(id).value);
if (isNaN (A[i][j])) {
alert ('Valoarea 'A[i][j]' nu este un numar. Reintroduceti valoarea');
}
}
}
}
function readGrad() {
k = parseInt(document.getElementById("grad").value);
if (isNaN(k)) {
alert('Gradul introdus nu este intreg, reintroduceti gradul matricii');
}
if (k == 0) {
alert ('Determinantul trebuie sa fie mai mare ca 1');
}
if (k == 1) {
alert ('Determinantul trebuie sa fie mai mare ca 1');
}
return k;
}
function genTable(i,j) {
//var i,j = parseInt(document.getElementById("grad").value);
var myTable = '<TABLE BORDER="1" BORDERCOLOR="BLACK">\n <TBODY>\n';
for (i = 0; i < 1; i++) {
myTable += ' <TR>\n';
for (j = 0; j < k+1; j++) {
myTable += ' <TD>'+j+'</TD>\n';
}
myTable += ' </TR>\n';
}
for (i = 1; i < k+1; i++) {
myTable += ' <TR>\n';
for (j = 0; j < 1; j++) {
myTable += ' <TD>'+i+'</TD>\n';
}
for (j = 1; j < k+1; j++) {
myTable += ' <TD><input class="element" id="A' + i + j + '" onblur="genArray()"></TD>\n';
}
myTable += ' </TR>\n';
}
myTable += ' </TBODY>\n</TABLE>\n';
document.getElementById('container').innerHTML = myTable;
}
</script>
</head>
<body style="background-color: #777; color: ddd;">
<div style="margin: 20px;">
<h1>Program de calculare determinant matrice de orice grad.</h1>
</div>
<div>
Introduceti gradul matricei
<input id="grad" type="text" value="" style="width: 50px;" onChange="readGrad()">
<input style="margin-top: 20px;" type="button" name="Calculate determinant" value="Generati tabel" onClick="genTable()">
</div>
<form name="Det Matrice">
<div style="margin-top: 100px; float: left; width: 100%;">
Introduceti valorile:
<table style="text-align: center;">
<div id="container"></div>
</table>
<br>
</div>
</body>
After correct the syntax error of the alert, genTable() works. But you have logic problem in your code. You add onblur event handler to every text field in the generated table cell. So every cell input will trigger a call to the onblur event handler which will iterate the whole table. I don't think this is what you want. Besides, during the iteration, your parseFloat function will fail on all the empty cells. You should only trigger one call to genArray() perhaps by using a button.
Try onblur="genArray()" instead of onBlur="genArray()"
Notice that it is all in lower case letters!
Your code works fine. Just correct the syntactical error in line 15 like described by jbabey in the comments.

Categories

Resources