I have a Rot13 JS function that I am attempting to link to a button. The expected output is meant to be that if I enter 'ABC' and press the Encrypt button, the encrypted text becomes 'NOP'.
The function doesn't currently link up to the buttons in HTML and when I press the encrypt button there is no response. I've included a script tag in the HTML.
EDIT: the encrypter is linked to the button, however it encrypts 'ABC' to 'ABC.
JavaScript:
function rot13() {
var input = document.getElementById("box1").value;
var output = [];
for (var i = 0; i < input.length; i++) {
var asciiNum = input[i].charCodeAt();
if (asciiNum >= 65 && asciiNum <= 77) {
output.push(String.fromCharCode(asciiNum + 13))
} else if (asciiNum >= 78 && asciiNum <= 90) {
output.push(String.fromCharCode(asciiNum - 13))
} else {
output.push(input[i])
}
}
document.getElementById("box2").value = output.join('');
}
<div class="form">
<input type="text" placeholder="plain text here..." name="plaintext" id="box1">
<br>
<button type="button" onclick="rot13()">Encrypt</button>
<button type="button" onclick="rot13()">Decrypt</button>
<br>
<input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
</div>
EDIT: corrected the JS.
There are few problems with code:
output.join('') = document.getElementById("box2") will throw error. You should set .value to output.join(''). The left hand side of = should be a variable. output.join('') returns are value and it cannot be assigned to anything.
output + input[i] will do nothing. You should use push() to add values to array.
function rot13() {
var input = document.getElementById("box1").value;
var output = [];
for (var i = 0; i < input.length; i++) {
var asciiNum = input[i].charCodeAt();
if (asciiNum >= 65 && asciiNum <= 77) {
output.push(String.fromCharCode(asciiNum + 13))
} else if (asciiNum >= 78 && asciiNum <= 90) {
output.push(String.fromCharCode(asciiNum - 13))
} else {
output.push(input[i])
}
}
document.getElementById("box2").value = output.join('');
}
<div class="form">
<input type="text" placeholder="plain text here..." name="plaintext" id="box1">
<br>
<button type="button" onclick="rot13()">Encrypt</button>
<button type="button" onclick="rot13()">Decrypt</button>
<br>
<input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
</div>
Related
i have the following code:
<input type="text" id="wisselspelers" onkeypress="return (event.charCode == 32|| event.charCode > 64 &&
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
<button id="opslaanBtn">Wisselspeler toevoegen</button>
<p id="opgeslagen"></p>
<script>
document.getElementById("opslaanBtn").addEventListener("click", myFunction)
document.getElementById("opslaanBtn").addEventListener("click", myFunction2)
var spelers, ab1, abc2, abcd3;
var spelers = [];
function myFunction() {
var input = document.getElementById("wisselspelers").value;
spelers.push(input);
abc2 = spelers.length;
ab1 = "<ul>";
for (abcd3 = 0; abcd3 < abc2; abcd3++) {
ab1 += "<li>" + spelers[abcd3] + "</li>";
}
ab1 += "</ul>";
document.getElementById("opgeslagen").innerHTML = ab1;
}
function myFunction2() {
document.getElementById("wisselspelers").value = "";
}
</script>
This code allows someone to enter a value into the input and add it to the array. I'd like to create another button, which allows a user to randomly select one of the values he added to the (empty) array.
I've tried the following code, but this code shows everything the user added and doesn't randomly select one:
<button id="gekozenBtn">Kies een random wisselspeler</button>
<h1 id="gekozen"></h1>
<script>
document.getElementById("gekozenBtn").addEventListener("click", gekozenFunction)
var rand = Math.floor(Math.random() * spelers.length);
var concat = spelers[rand];
function gekozenFunction() {
document.getElementById("gekozen").innerHTML = (concat);
}
</script>
Putting all your code in the same script tag works:
<input type="text" id="wisselspelers" onkeypress="return (event.charCode == 32|| event.charCode > 64 &&
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
<button id="opslaanBtn">Wisselspeler toevoegen</button>
<p id="opgeslagen"></p>
<button id="gekozenBtn">Kies een random wisselspeler</button>
<h1 id="gekozen"></h1>
<script>
document.getElementById("opslaanBtn").addEventListener("click", myFunction)
document.getElementById("opslaanBtn").addEventListener("click", myFunction2)
document.getElementById("gekozenBtn").addEventListener("click", gekozenFunction)
var spelers, ab1, abc2, abcd3;
var spelers = [];
function myFunction() {
var input = document.getElementById("wisselspelers").value;
spelers.push(input);
abc2 = spelers.length;
ab1 = "<ul>";
for (abcd3 = 0; abcd3 < abc2; abcd3++) {
ab1 += "<li>" + spelers[abcd3] + "</li>";
}
ab1 += "</ul>";
document.getElementById("opgeslagen").innerHTML = ab1;
}
function myFunction2() {
document.getElementById("wisselspelers").value = "";
}
function gekozenFunction() {
var rand = Math.floor(Math.random() * spelers.length);
var concat = spelers[rand];
document.getElementById("gekozen").innerHTML = (concat);
}
</script>
(I've placed the random selection inside the gekozen function so you select the random value from the most up to date spelers, maybe the original problem was that it was too early to choose a value)
For a school project, I'm trying to create a website on encryption methods, but right now I have a problem with my Caesar one. I checked so many times but I can't find out where is the problem in my code. I think the shift is what is wrong, but I don't know what I could change to make it work, and I would be very happy if someone could help me.
So, here is the html part :
<form name="formu" action="">
<label for="pseudo">Your text :</label>
<br>
<textarea name="text" id="text_encode" style="width: 30%;height: 200px">
</textarea>
<br>
<br>
<label for="methods">Select your methods : </label>
<br>
<br>
<select name="methods" id="methods">
<option value="Caesar">Caesar</option>
</select>
<br>
<br>
<input type="button" value="Encrypt" onClick=encryption()>
<br>
<br>
<textarea name="text" id="text_decoded" style="width: 30%;height: 200px"
readonly="readonly"></textarea>
</form>
And here is my javascript code:
function encryption() {
switch(document.getElementById("methods").value) {
case "Caesar":
var str = document.getElementById("text_encode").value;
var amount = prompt("Number of shift");
var output = "";
for (var i = 0; i < str.length; i ++) {
var c = str[i];
var code = str.charCodeAt(i);
if ((code >= 65) && (code <= 90))
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
else if ( (code >= 97) && (code <= 122) )
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
output += c;
}
document.getElementById("text_decoded").value=output;
break;
}
}
You can also go here if you want to test what's wrong directly: https://www.w3schools.com/code/tryit.asp?filename=FXJU1NAG37C0
The mistake is this line:
var amount = prompt("Number of shift");
This by default returns a string, but it may contain a number - so if I enter 10 in the prompt box, amount will be:
amount = "10"
To fix this, you need to parse the string into an integer:
var amount = Number(prompt("Number of shift"));
Then your code should work.
I am writing one JavaScript code
Please see the images. There are 4 text boxes where only one character can be entered .
The rightmost field's id is first and the leftmost id is fourth
4 conditions are to be fulfilled
The last text box - the rightmost/first textbox will be input first, then the second one will be filled, then the third and at last the fourth
Then the rightmost/first textbox value will shift (left shift) to the second and in this way values will shift until all 4 fields are filled - See screenshot Insert
If we place the cursor on any other element except the first/rightmost it will move the cursor to the rightmost because we will only enter input in the rightmost
There will be backspace function which will delete the rightmost/first , ie. the the first field will be deleted the fourth field value will move to third, third to second, like this, a right shift will occur in this way all elements are to be deleted - see Screenshot Delete
https://i.stack.imgur.com/w8eUg.jpg -- Screenshot Insert
https://i.stack.imgur.com/fl8Gg.jpg -- Screenshot Delete
The entire solution should be in JavaScript, no jQuery can be used
<form>
<input type="text" id="fourth" size="1" maxlength="1" />
<input type="text" id="third" size="1" maxlength="1" />
<input type="text" id="second" size="1" maxlength="1" />
<input type="text" id="first" size="1" maxlength="1" />
<html>
<head>
</head>
<body>
<form>
<input type="text" id="fourth" size="1" maxlength="1" />
<input type="text" id="third" size="1" maxlength="1" />
<input type="text" id="second" size="1" maxlength="1" />
<input type="text" id="first" size="1" maxlength="1" />
</form>
<script>
var myInputs = document.getElementsByTagName("input");
var myEditable = document.getElementById("first");
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener("click", function() {
document.getElementById("first").focus();
})
}
myEditable.addEventListener("keypress", function(evt) {
if (evt.which >= 48 && evt.which <= 57) {
// Here, we have a number. Everything gets shifted to the LEFT
if (myInputs[0].value == "") {
for (var i = 0; i < myInputs.length - 1; i++) {
myInputs[i].value = myInputs[i + 1].value;
}
myEditable.value = String.fromCharCode(evt.which);
}
} else {
evt.preventDefault(); // newly added to prevent non integer inputs in rightmost field
console.log("Sorry");
}
})
myEditable.addEventListener("keyup", function(evt) {
if (evt.which == 8) {
//myEditable.blur();
for (var i = myInputs.length - 1; i >= 1; i--) {
myInputs[i].value = myInputs[i - 1].value;
}
myInputs[0].value = "";
}
});
</script>
</body>
</html>
I am facing only one problem - non Integer input to be disabled, no JavaScript alert, simply it will not accept any non integer input.
In my code I can enter non integer in the first/rightmost field, not in others but I have to disable non integer input in first/rightmost field.
you never called preventDefault() on the event.
Notice the preventDefault in the else where you do console.log("sorry");
https://jsfiddle.net/jmuc36hs/
var myInputs = document.getElementsByTagName("input");
var myEditable = document.getElementById("first");
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener("click", function() {
document.getElementById("first").focus();
})
}
myEditable.addEventListener("keypress", function(evt) {
if (evt.which >= 48 && evt.which <= 57) {
// Here, we have a number. Everything gets shifted to the LEFT
if (myInputs[0].value == "") {
for (var i = 0; i < myInputs.length - 1; i++) {
myInputs[i].value = myInputs[i + 1].value;
}
myEditable.value = String.fromCharCode(evt.which);
}
} else {
evt.preventDefault();
console.log("Sorry");
}
});
myEditable.addEventListener("keyup", function(evt) {
if (evt.which == 8) {
//myEditable.blur();
for (var i = myInputs.length - 1; i >= 1; i--) {
myInputs[i].value = myInputs[i - 1].value;
}
myInputs[0].value = "";
}
});
How to check value in input using loop for with onchange using javascript ?
first, When user fill char. It's will be show Your Price must be a number.
And if user fill number less than 1.5 It's will show Your Price must be at least $1.50 USD.
and click Add more link to add input.
I try my code , but not work, how can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
Add more
<div id="p_scents_price">
<p>
<label>
<input type="text" class="price" id="price0" size="20" name="price[]" onchange="myFunction0()"/><p id="demo0"></p>
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script>
var list = document.querySelectorAll(".price");
for (z = 0; z < list.length; ++z) {
function myFunction'+z+'() {
var x = document.getElementById("price'+z+'").value;
var y = isNaN(x);
if(y === true)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be a number.";
}
else
{
if(x < 1.5)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be at least $1.50 USD.";
}
else
{
document.getElementById("demo'+z+'").innerHTML = "";
}
}
}
}
}
</script>
<script>
$(function() {
var scntDiv = $('#p_scents_price');
var i = 1;
$('#addScnt_price').live('click', function() {
$('<p><label><input type="text" class="price" id="price'+i+'" size="20" name="price[]" onchange="myFunction'+i+'()"/>Remove<p id="demo'+i+'"></p></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt_price').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
}
return false;
});
});
</script>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I added the alert to test if the script was working at all, once i deleted the function it did, but once I add the function the html doesn't even show the alert. I tried loading the code in a different file and calling it in the head, the body, for some reason the code won't even load much less can i get the button at the end to work.
<!DOCTYPE html>
<html>
<head>
<title> Astronomy Quiz </title>
</head>
<body>
<div>
<script>
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
</script>
<center>
<h1> Astronomy Quiz </h1>
</center>
<h3> True / False </h3>
<form id = "quiz">
<label><b>1)</b> According to Kepler the orbit of the earth is a circle with
the sun at the center.
<input type = "radio" name = "q1" value = "True" />
True
<input type = "radio" name = "q1" value = "False" />
False</label>
<br>
<br>
<label><b>2)</b> Ancient astronomers did consider the heliocentric model of
the solar system but rejected it because they could not detect parallax.
<input type = "radio" name = "q2" value = "True" />
True
<input type = "radio" name = "q2" value = "True" />
False</label>
<br>
<h3> Multiple Choice </h3>
<b>3)</b> The total amount of energy that a star emits is directly related
to its
<br>
<input type = "checkbox" name = "q3" value = "a" />
a) surface gravity and magnetic field
<br>
<input type = "checkbox" name = "q3" value = "b" />
b) radius and temperature
<br>
<input type = "checkbox" name = "q3" value = "c" />
c) pressure and volume
<br>
<input type = "checkbox" name = "q3" value = "d" />
d) location and velocity
<br>
<br>
<b>4)</b> Stars that live the longest have
<br>
<input type = "checkbox" name = "q4" value = "a" />
a) high mass
<br>
<input type = "checkbox" name = "q4" value = "b" />
b) high temperature
<br>
<input type = "checkbox" name = "q4" value = "c" />
c) lots of hydrogen
<br>
<input type = "checkbox" name = "q4" value = "d" />
d) small mass
<br>
<h3> Fill in the Blank </h3>
<label><b>5)</b> A collection of a hundred billion stars, gas, and dust is
called a
<input type = "text" name = "q5" value = "" size = "15" />
.</label>
<br>
<br>
<label><b>6)</b> The inverse of the Hubble's constant is a measure of the
<input type = "text" name = "q6" value = "" size = "15" />
of the universe.</label>
<br>
<br />
<input type = "button" value = "Grade" onclick = "quiz()" />
<input type = "reset" name = "Clear" value = "Clear" />
</form>
</div>
</body>
</html>
Try this out:- http://jsfiddle.net/adiioo7/fDDCW/
JS:-
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
on line 88:
if(get.q6.value.match(/^age$/i))
you missed ) in your javascript...
You have missed a ) here:
if(get.q6.value.match(/^age$/i)
Change this to:
if(get.q6.value.match(/^age$/i))
if (get.q6.value.match(/^age$/i) {
This like is missing a closing )
Try this:
if (get.q6.value.match(/^age$/i)) {
To find what's wrong with your JavaScript code use try-catch as follows-
<script>
try
{
/*some JS code*/
}
catch(foo)//Use any variable in place of foo
{
alert(foo);
}
</script>
This will definitely not correct the error but may help you much to find what the error is. Though this is not an answer but you may follow this approach globally anywhere anytime.