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>
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>
I've sorted this but now it's came back on... I've tried changing the for loops but it still seems to generate duplicate French words. It's suppose to not show the french word twice in the application run.
My jsFiddle is an exact replica:
http://jsfiddle.net/jamesw1/w8p7b6p3/17/
Javascript:
//James Wainwright's Mobile Apps Assignment
//Arrays of french and english words.
var
RanNumbers = new Array(6),
foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
//Generate random numbers and make sure they aren't the same as each other.
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu using for loop. This loop runs once (on document load)
document.getElementById('generatedWord').textContent = foreignWords[number];
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Output the previous.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Declare variables 'outside' the onclick function so it ensures they work correctly.
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
var counter = 0;
var outputted = '';
//Create arrays that will hold the options they chose, the correct answer for that particular question, and ofcourse the generated word.
var guessedList = new Array(6);
var correctList = new Array(6);
var wordGenerated = new Array(6);
//On click, Get new word, Calculate how many they got right/wrong, Show the user what they entered, show them the correct values they should've guessed and more...
document.getElementById('submitAns').onclick = function () {
//Declare variables for function.
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
//Check if guess is right or wrong, if right add 1 to correct pile..Visa versa.
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Generate a word here. ( call wordGen() )
wordGen();
//Create dynamic select menu for options they have to choose from.
document.getElementById('generatedWord').textContent = foreignWords[number];
//Generate a random number, so that the 'Correct' answer can be randomly put in a position in the select menu. (It won't always be in the same position...It changes depending on the random number
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Outputting to the html page.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Checking of the answers below, Accumilating correct and wrong answer.
//Count number of guesses
numGuesses++;
//Counter for placing guessed, correct and foreign word into there arrays.
counter++;
wordGenerated[counter] = foreignWords[number];
guessedList[counter] = document.getElementById('guesses').options[select.selectedIndex].text;
correctList[counter] = translate[number];
//Once the application has finished...It will produce the following output.
if (numGuesses == 6) {
document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
$('#submitAns').hide();
outputted = "<table>";
for(var d=1;d<wordGenerated.length;d++){
outputted += "<tr><td><span id='guessedWord'>Question " + d + ":</td> <td>Generated word: " + wordGenerated[d] + "</td> <td>Guessed Word: " + guessedList[d] + "</td> <td><span id='correctWord'>Correct Word: " + correctList[d] + "</span></td></td>";
}
outputted += "</table>";
outputted += "<style type='text/css'>#hint{ display:none; }</style>";
//Output it to the html page.
document.getElementById('details').innerHTML = outputted;
}
};
document.getElementById('hint').onclick = function () {
alert(correctAns.charAt(0));
};
Html:
<div data-role="page" id="page1" data-add-back-btn="true">
<div data-role="header">
<h1>James' Translation Guessing Game</h1>
</div>
<div data-role="content" class="main">
<h2 id="display" style="color:rgba(204,51,204,1);">Guess what the generated french word translates to in English!</h2><br />
<!-- What question we're upto -->
<h2 id="numGuess">Question #</h2 >
<!-- The generated French Word Aswell as end of app details-->
<div align="center" class="frenchWord" style="position:">
<!--Generated french word details-->
<div style="background-color:rgba(51,51,51,0.5);border-radius:4px 10px 2px;"align="center" id="generatedWord"></div>
<br />
<br />
<!-- Show the user there guessed answers, correct and foreign word -->
<div id="details"></div>
</div>
<!-- Select menu output -->
<div align="center" id="output"></div>
<img id="hintImg" style="" src="images/hint.png" alt="Hint" />
<!-- Buttons, Call Functions -->
<button type="button" style='opacity:0.5' id="submitAns" onClick="translate();">Check</button>
<input type="button" value="New Game" onClick="document.location.reload(true)">
<script>
//Simple animation
$(document).ready(function(){
$("#generatedWord").animate({
opacity: 0.8,
margin: "40px 0px 100px 0px",
width: "20%",
padding: "30px",
}, 1500 );
});
</script>
</div>
<div data-role="footer">
<h4>James Wainwright</h4>
</div>
</div>
This might do it. Before assigning a number to the RanNumbers array I delete it from the original RanNumbers array to prevent duplication. It might make more sense to just maintain a separate array of numbers to be used in the questions but I tried to change as little as possible.
Updated Fiddle
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * RanNumbers.length);
while(temp==correctAns){
temp = Math.floor(Math.random() * RanNumbers.length);
delete(RanNumbers.indexOf(temp)); // delete it so we can add it down below
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
Ok what I have here is an array that is 6x6 with numbers. The part that I'm having issues with is I need to use an onchange in the drop down list to only choose the column that is selected. So if I select column 5 it will only display the numbers in that column. I have spent sometime on line looking for a way to do to this so I'm turning to everyone here. I am only using java script to create this too
<script type="text/javascript">
// create a var for a 2-D array (6x6)
var afNumbers = new Array(6)
var i
var j
for (i = 0; i <= 5; i++)
afNumbers[i] = new Array(6)
//fill the array by using a nested for loop
//loop through each row
for (i = 0; i <= 5; i++)
{
//loop through each item in those row
for (j = 0; j <= 5 ; j++) {
afNumbers[i][j] = i + j
}
}
//function to print the array in the text area
function vPrint() {
var strOut = ""
for (i = 0; i <= 5; i++)
{
//loop through each item in those row
for (j = 0; j <= 5 ; j++)
{
strOut += afNumbers[i][j] + "\t"
}
strOut += "\r"
}
document.getElementById('taOut').value = strOut
}
function vDiagonal() {
var strOut = ""
for (i = 0; i <= 5; i++) {
//loop through each item in those row
for (j = 0; j <= 5 ; j++) {
if (i == j)
strOut += afNumbers[i][j] + "\t"
else strOut += "" + "\t"
}
strOut += "\r"
}
document.getElementById('taOut').value = strOut
function vColumn()
{
if (document.getElementById('PrintMenu').value == "1")
{
document.getElementById('').innerHTML = afNumbers[j] + strOut
}
}
}
</script>
</head>
<body>
<form id="frm2DArray" style="text-align:center">
<h2>Two Dimensional Arrays</h2>
<input type="button" id="btnPrint" value="Print Array" onclick="vPrint()"/><br /><br />
<input type="button" id="btnTranspose" value="Print Transpose" /><br /><br />
<input type="button" id="btnDiagonal" value="Print Diagonal" onclick="vDiagonal()" />
<h3>Print</h3>
<select id="PrintMenu" onchange="vColumn()">
<option value="1">Column 1</option>
<option value="2">Column 2</option>
<option value="3">Column 3</option>
<option value="4">Column 4</option>
<option value="5">Column 5</option>
</select>
<br />
<textarea id="taOut" rows="40" cols="80"></textarea>
</form>
</body>
</html>
First off I'm noticing a disconcerting lack of semicolons in your code. Put those after your statements!
You can get the value of the printmenu and store in in a variable.
var col = document.getElementById('PrintMenu').value;
From there you can loop across the array with that value.
afNumbers.forEach(function(entry) {
document.write(entry[col]);
});
That should spit out each of the numbers in the column.
I am working on a form where there user can add multiple inputs like:
<script type="text/javascript">
<!--
var counter = 0;
var limit = 4;
window.onload = moreFields;
function moreFields() {
if (counter == limit) {
alert('You have reached the limit of adding ' + counter + ' inputs');
}
else
var newFields = document.getElementById('sa-groep').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var hetId = newField[i].id
if (hetId)
newField[i].id = hetId + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
counter++;
}
This works fine, all input get their unique id, but then i figured out that to catch all the input values it is better through getElementsByClassName
so then i made this to catch the values:
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i] + "<br />");
}
}
the html code is:
<body>
<div id="sa-groep" style="display: none">
<input class="SA" id="sa_" value=" " />
<select class="RC" id="rc_">
<option>Rating</option>
<option value="excellent">Excellent</option>
<option value="good">Good</option>
<option value="ok">OK</option>
</select><br /><br />
<input type="button" value="Remove review"
onclick="this.parentNode.parentNode.removeChild(this.parentNode)" /><br /><br />
</div>
<span id="writeroot"></span>
<input type="button" onclick="moreFields()" value="Give me more fields!" />
<input type="button" onclick="getClassValue()" value="Send form" />
</body>
But the only thing it show is : 3011 contains: So what am i doing wrong?
At first look I suggest you to change document.write (which replace all the text of your document) and instead use console.log("something..") or the property innerHTML in a specific div.
document.write, as I said before, replace all the the page with the string passed.
The problem beside the curly bracket (thanks #James) was the cloning of an hidden fields wich gave an empty result at the first spot in the arrays. To delete the first element of an array i had to delete that with shift() It works, probably it can be better but this is my solution:
function getClassValue() {
var secAut = []; // array met de namen van de secundaire auteurs
var readyItems = document.getElementsByClassName('auteur');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
}
var secAutMinus = secAut.shift(); // 1 element verwijdert uit array ivm dat de eerste input leeg is (display: none)
var relCode = []; // 2e array met de relatiecodes
var relCodeready = document.getElementsByClassName('relcode');
for(var i = 0; i < relCodeready.length; i++){
relCode.push(relCodeready[i].value);
}
var relCodeMinus = relCode.shift(); // 1st element verwijderen
for(var k= 0; k < secAut.length; k++){
console.log(3012+k+ ' contains: ' + secAut[k] + ' is ' + relCode[k] + '<br/>'); // uitlezing arrays minus het eerste lege element
}
}
In this function the loop needs to start from 1 because the 0th element is the hidden (cloned) one.
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for (var i = 1; i < readyItems.length; i++) {
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i - 1] + "<br />");
}
}
There are a couple of other problems, missing curly brace after the else in moreFields.
Here's a working fiddle