Javascript: display an alert when a form is checked? - javascript

I have created a simple web app that has 2 form selections, when the user makes their selection from each I want an alert to display showing them the choices they made.
I have attempted this below but when both forms are checked the alert is not displayed. What am I missing? Note see the comment:
//BELOW IS NOT BEING DISPLAYED BUT SHOULD BE
Current code:
<!DOCTYPE html>
<html>
<body>
<h1>Calculator</h1>
<p>Select the importance of this:</p>
<form method="get">
<input type="checkbox" name="Severity" value="negligible"> Negligible<br>
<input type="checkbox" name="Severity" value="minor"> Minor<br>
</form>
<p>Select the Probability of this:</p>
<form method="get">
<input type="checkbox" name="Probability" value="improbable"> Improbable<br>
<input type="checkbox" name="Probability" value="remote"> Remote<br>
<input type="checkbox" name="Probability" value="occasional"> Occasional<br>
<button onclick= "analyseThis()"> Analyse this </button> <br>
<script>
function analyseThis(){
var severities = document.getElementsByName('Severity');
var probs = document.getElementsByName('Probability');
var severity = undefined;
for(var i = 0; i < ages.length; i++)
{
if(severities[i].checked)
{
age = severities[i].value;
}
}
var probability = undefined;
for(var i = 0; i < probs.length; i++)
{
if(probs[i].checked)
{
probability = probs[i].value;
}
}
//BELOW IS NOT BEING DISPLAYED BUT SHOULD BE
alert("Severity is: " + age + "Probability is: " + probability);
}
</script>
</body>
</html>

I would use JQuery and use the click function of the button to submit.
Here is an example:
$(document).ready(function () {
$("{form id/class button id/class OR button id/class}").click(function(e) {
e.preventDefault();
//perform validation
//if everything is good...
$("{form id/class}").submit();
});
});

Something funny is happening:
Your function analyseThis() does get called, but there is an
error when it is being evaluated.
The form on the page is being "submitted", so the page reloads
and you never see the error.
To prevent the page from reloading (so you can see your error) do this:
Pass in the event object to your analyseThis() function from the onclick hander:
<button onclick= "analyseThis(event)"> Analyse this </button>
Make your analyseThis() accept the event object, and call .preventDefault() on it so that the page doesn't reload:
function analyseThis(e){
e.preventDefault()
// the rest of your function body here....
}
After you do that, you will see the underlying error output in the console:
ReferenceError: ages is not defined (line 33, col 17)
for(var i = 0; i < ages.length; i++)
If you do want the form to be submitted, just remember to remove the e.preventDefault() call after debugging the code.

You have an error in your code - you are checking ages.length in your loop which is probably undefined (no ages variable in your code) in the first loop and your code execution should stop there.
Working JSBin code here:
http://jsbin.com/yelihugune/1/

You have a bug in your code.
for(var i = 0; i < ages.length; i++)
{
if(severities[i].checked)
{
age = severities[i].value;
}
}
'ages' is not yet defined in your code, nor is 'age'. This will be throwing an error, stopping your code from running. This is why the alert is not going.
Declare the ages array.

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

For Loop Only Running Through Once

In the following program, for some reason, the for loop runs through once, and then does not repeat. I believe the error is with the bold code. Help is very much appreciated. This is a program used to change a text box to caps, title case, etc. Title case being the first letter of each word capitalized. Thank you.
<html>
<head>
<script type="text/javascript">
function titlize(){
tLength=tBox.box.value.length
character=new Array()
for(i=1; i<tLength+1; i++){
**character[i]=tBox.box.value.slice(i-1,i)**
document.write(character[i])
if(i==1){
character[i]=character[i].toUpperCase()
}else if(character[i-1]==" "){
character[i]=character[i].toUpperCase()
}else{
character[i]=character[i].toLowerCase()
}
document.write(i)
document.write(character[i])
}
}
function upperC (){
toUpperCase(tBox.box.value)
}
function verify (){
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
if(tBox.lowercase.checked){
tBox.box.value=tBox.box.value.toLowerCase()
}
if(tBox.titlecase.checked){
titlize()
}
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
}
</script>
</head>
<body>
<form name="tBox">
<input type="text" name="box" value=""><br>
<input type="checkbox" name="uppercase" onClick=verify(this.form)>Uppercase<br>
<input type="checkbox" name="lowercase" onClick=verify(this.form)>Lowercase<br>
<input type="checkbox" name="titlecase" onClick=verify(this.form)>Titlecase<br>
</form>
</body>
</html>
tBox is your form not your textbox, so trying to get it's value and then the length of that value is not valid. The code needs to access your textbox, so it should be:
// Scan for the first textbox. Give that textbox a unique id to be
// able to write a more specific query.
tLength= document.querySelector("input[type='text']").value.length;
character=new Array()
// Not sure why you were writing: i < tLength +1 as that will
// cause your loop to go one character too far. Remember,
// arrays start from 0 and length starts from 1.
for(i=1; i < tLength; i++){
Lastly, avoid document.write() because if you use it on a document that has finished being parsed, it will cause the entire existing document to be thrown out.
Based on the code above. You have document.write statements in your function, which is causing issues in overwriting your DOM. I've removed those, and that will allow it to function normally. Also, I added tBox.box.value = character.join("") to put the text back into the text box.
https://plnkr.co/edit/qOPIxwH16hJUlj0RFBhv?p=preview
function titlize() {
tLength=tBox.box.value.length;
character=new Array();
for(i=1; i < tLength + 1; i++){
console.log('print')
character[i]= tBox.box.value.slice(i - 1,i)
//document.write(character[i])
if(i==1) {
character[i]=character[i].toUpperCase()
} else if(character[i-1]==" ") {
character[i] = character[i].toUpperCase()
} else {
character[i]=character[i].toLowerCase()
}
console.log(i)
console.log(character[i])
}
tBox.box.value = character.join("")
}

How do you return all the posible value in a switch statement

So i was wondering how do i shows the result once someone inputs the letter A.
the problem is it shows up for a few seconds and disapears
here's my code:
function pop(){
var text = document.getElementById('Search_Text').value;
var res = text.split("");
for (var i = 0; i < res.length; i++){
switch(res[i]) {
case "a":
alert("a");
break;
case "A":
document.getElementById("result").innerHTML="C";
break;
}
}
}
<form onsubmit="">
<input type="text" id="Search_Text"></input>
<button type="submit"onclick="pop()">change</button>
</form>
<p id="result"></p>
You have a submit type button inside a <form> tag.
Clicking that button will cause the browser to reload the page.
Since there are many ways to stop this from happening ... One suggestion could be to put return false; inside the onsubmit attribute of the <form> tag:
<form onsubmit="return false;">
I think that's because you are submitting the form and the page reloads. Thats why you see the result only for a few seconds.
Try this:
function pop(event){
event.preventDefault();
var text =document.getElementById('Search_Text').value;
var res = text.split("");
...
}
My hunch is that you've misunderstood the correct use of forms, and that what you're really trying to do is spit out letters individually onto a page after having typed into a text box and clicked the button.
A for loop does everything as fast as the processor will allow it, so if you're rendering to a page, it's going to be pretty fast.
If you want to see things clearly, you'll have to use JavaScript timing events with callbacks. Here's an example:
function pop(){
var text = document.getElementById('Search_Text').value;
var res = text.split("");
var element = document.getElementById("result");
var duration = 500;
showNextLetter();
function showNextLetter () {
if (res.length) {
element.innerHTML += res.shift();
setTimeout(showNextLetter, duration);
}
}
}
<form onsubmit="">
<input type="text" id="Search_Text"></input>
<button type="submit"onclick="pop()">change</button>
</form>
<p id="result"></p>

Trouble updating div with javascript function

I'm working on a FizzBuzz solution. I had it working fine when I called the function onload and set the input variable with a prompt (see comments in my code), but when I added a form, called the function onclick, and tried to set the variable using getElementById, my function would not print to the div. In the original version, the output is visible after the function completes. In the updated version, the output flashes briefly and then disappears. It is as if I am immediately refreshing the screen. Any suggestions? Thanks
<script>
function fizzbuzz(){
// var num = prompt("Enter a number: ");
var num = document.getElementById("number").value;
var div3 = document.getElementById("div3");
for(var i=0; i<num; i++){
if (i%3===0 && i%5===0){
div3.innerHTML = div3.innerHTML+"Fizz Buzz<br>";
}else if (i%3===0){
div3.innerHTML = div3.innerHTML+"Fizz<br>";
}else if (i%5===0){
div3.innerHTML = div3.innerHTML+"Buzz<br>";
}else{
div3.innerHTML = div3.innerHTML+(i+1)+"<br>";
}
}
}
</script>
</head>
<body>
<!--body onload = "fizzbuzz()"-->
<div id = "div1">
<h1>Fizz Buzz</h1>
<form>
<p>Enter a number:</p><p><input type="text" name="number" id="number"/><input type="submit" value="Submit" onclick = "fizzbuzz()"/></p>
</form>
<div id="div3"></div>
</div>
</body>
Your button is of type submit - which is causing the page to post back / refresh, hence why you see it flash. Either prevent the default action with e.preventDefault or change your input to type of button, or use return false;
Prevent Default:
<!--Pass in event to the func-->
<input type="submit" value="Submit" onclick = "fizzbuzz(event)"/>
//Use it
function fizzbuzz(e) {
e.preventDefault();
...
}
Or use type button
<input type="button" value="Submit" onclick = "fizzbuzz()"/>
Or return false
function fizzbuzz(e) {
...
...
return false;
}
Your <input type="submit"> is submitting your form – and reloading the page – after your click handler runs.
You need to return false from the handler to prevent that.

Checkbox js toggling incorrectly

I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>​
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2

Categories