HTML onclick="myFunction" not working - javascript

First, i have checked several tutorial sites to clarify syntax such as the OnClick event and the prompt property and relocated the javascript from body to head (I heard this can fix browser-related problems).
For some reason OnClick event does nothing. I have tested website in-browser and radio buttons load correctly.
<!DOCTYPE html>
<html>
<head>
<script>
function checkSkillLevel() {
if(document.getElementById('skill_Easy').checked) {
var ok = prompt("You chose Easy");
}
else if(document.getElementById('skill_Medium').checked) {
var ok = prompt("You chose Medium");
}
else if document(getElementById('skill_Hard').checked) {
var ok = prompt("You chose Hard");
}
else {
var ok = prompt("Welcome to my tic tac toe game! To get started, please pick a skill level.");
}
}
</script>
</head>
<body>
<table cellpadding="10">
<tr>
<td><h1>Tic Tac Toe</h1></td>
</tr>
<tr>
<td>
<form action="" onclick="checkSkillLevel()">
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();">Easy<br>
<input type="radio" name="skill" value="Medium" id="skill_Medium">Medium<br>
<input type="radio" name="skill" value="Hard" id="skill_Hard">Hard<br>
</td>
</tr>
Also, I would prefer pure Javascript (no JQuery please) for any ideas.

You should add onclick to all the inputs, and correct the typo in the following line :
else if document(getElementById('skill_Hard').checked) {
Should be :
else if(document.getElementById('skill_Hard').checked) {
Hope this helps.
Snippet
function checkSkillLevel() {
if(document.getElementById('skill_Easy').checked) {
var ok = prompt("You chose Easy");
}
else if(document.getElementById('skill_Medium').checked) {
var ok = prompt("You chose Medium");
}
else if(document.getElementById('skill_Hard').checked) {
var ok = prompt("You chose Hard");
}
else {
var ok = prompt("Welcome to my tic tac toe game! To get started, please pick a skill level.");
}
}
<table cellpadding="10">
<tr>
<td><h1>Tic Tac Toe</h1></td>
</tr>
<tr>
<td>
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();"/>Easy<br/>
<input type="radio" name="skill" value="Medium" id="skill_Medium" onclick="checkSkillLevel();"/>Medium<br/>
<input type="radio" name="skill" value="Hard" id="skill_Hard" onclick="checkSkillLevel();"/>Hard<br/>
</td>
</tr>
</table>

Add an onclick-attr or an onchange-attr with the function to each radio-button and it will work.

It's all about which elements are listening to the onclick event. The form does not have onclick, it has onsubmit. The buttons have onclick, though.
<td>
<form action="" onclick="checkSkillLevel()">
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();">Easy<br>
<input type="radio" name="skill" value="Medium" id="skill_Medium">Medium<br>
<input type="radio" name="skill" value="Hard" id="skill_Hard">Hard<br>
</td>
Becomes:
<td>
<form action="">
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();">Easy<br>
<input type="radio" name="skill" value="Medium" id="skill_Medium" onclick="checkSkillLevel();">Medium<br>
<input type="radio" name="skill" value="Hard" id="skill_Hard" onclick="checkSkillLevel();">Hard<br>
</td>
Additionally, I have one other thing. Why are you using prompt() for showing the user their selection? Use alert() instead.

Related

How to check how many buttons have been clicked in javascript?

I am trying to make an attendance page with html radio buttons. So when i submit it, I want it to return how many radio buttons with title as present are checked and how many radio buttons with title as absent ae checked.
Extra info: I am using Mac OS X El Capitan, Bootstrap and tomcat for localhost and java for backend support
Please suggest answers with javascript only
HTML
<label>Present<input type="radio" name="optradio" class="radiobtn" onclick =" // please help "></label>
<label>Absent<input type="radio" name="optradio" class="radiobtn" onclick =" // please help "></label>
Use querySelectorAll('.present:checked') to select all the elements that are checked and have the class present. You can then get the length of the returned node list.
document.querySelector('form').addEventListener('submit', e => {
e.preventDefault()
let present = document.querySelectorAll('.present:checked').length
let absent = document.querySelectorAll('.absent:checked').length
console.clear()
console.log('present:', present)
console.log('absent:', absent)
})
table {
width: 100%;
}
<form>
<table>
<tr>
<td>Billy</td>
<td><label>Present<input type="radio" name="optradio[1]" class="radiobtn present"></label></td>
<td><label>Absent<input type="radio" name="optradio[1]" class="radiobtn absent"></label></td>
</tr>
<tr>
<td>Bobby</td>
<td><label>Present<input type="radio" name="optradio[2]" class="radiobtn present"></label></td>
<td><label>Absent<input type="radio" name="optradio[2]" class="radiobtn absent"></label></td>
</tr>
<tr>
<td>Joey</td>
<td><label>Present<input type="radio" name="optradio[3]" class="radiobtn present"></label></td>
<td><label>Absent<input type="radio" name="optradio[3]" class="radiobtn absent"></label></td>
</tr>
<tr>
<td>Samantha</td>
<td><label>Present<input type="radio" name="optradio[4]" class="radiobtn present"></label></td>
<td><label>Absent<input type="radio" name="optradio[4]" class="radiobtn absent"></label></td>
</tr>
</table>
<p>
<input type="submit" value="Submit">
</p>
</form>

on Focus not working when textbox selected

I have a form here which id like the users to be able to select the radio button to choose a pre-defined amount option, or press the textbox (focus) to select the custom amount. The purpose of the javascript below is to clear the textbox when a predefined amount has been selected. It also allows users to CLICK the textbox (onfocus) to enter a custom amount in the CP_otheramount field (also use the radio button as a fallback).
It all seems to be working except for the onfocus. It works perfectly on load...but try this scenario:
Load the page, click inside the textbox but then decide to change your mind by selecting the value 3 radio button (64)...and then decide to press inside the onfocus textbox amount again... it become disabled and stops you from clicking inside or writing a number in!
Can anyone see the problem here at all? Its strange because it works on Stackoverflow just not on the live site. ANy help would be really appreciated.
Here is what has been created so far:
function activate() {
$('#other').prop('checked', true);
$('#other').trigger('click');
$('#theamount').focus();
}
$('input[name="am_payment"]').on('click', function() {
if ($(this).val() === '') {
$('input[name="CP_otheramount"]').val('');
$('#theamount').removeAttr("disabled");
} else {
$('#theamount').prop("disabled", "disabled");
$('input[name="CP_otheramount"]').val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="am_payment" value="3" checked="checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11" checked="checked"> <strong>100</strong>
<input type="radio" name="am_payment" value="32" checked="checked"> <strong>250</strong>
<input type="radio" value="" name="am_payment" id="other">
<label>Other</label>
<span onclick="activate();"><input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled"/></span>
The problem with your code is that you are checking every radio button without un-checking them.
function activate() {
// $('#other').prop('checked', true); Remove this line;
$('#other').trigger('click');
$('#theamount').focus();
}
$('input[name="am_payment"]').on('click', function() {
if ($(this).val() === '') {
$('input[name="CP_otheramount"]').val('');
$('#theamount').removeAttr("disabled");
} else {
$('#theamount').prop("disabled", "disabled");
$('input[name="CP_otheramount"]').val('');
}
});
And also
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Only check one, or none by Default -->
<input type="radio" name="am_payment" value="3" checked = "checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11"> <strong>100</strong>
<input type="radio" name="am_payment" value="32"> <strong>250</strong>
<input type="radio" value="" name="am_payment" id="other">
<label>Other</label>
<span onclick="activate();"><input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled"/></span>
UPDATE:
It was working for me but I don't know why it's not working for you, so I rewrote the functions..See if this works for you.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="am_payment" value="3" checked = "checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11"> <strong>100</strong>
<input type="radio" name="am_payment" value="32"> <strong>250</strong>
<input type="radio" value="" name="am_payment" id="other">
<label>Other</label>
<span id="toggle"><input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled"/></span>
<script>
function activate(){
$('#theamount').attr('disabled',false);
$('#theamount').focus();
$('#other').click();
}
function deactivate(){
$('#theamount').val('');
$('#theamount').attr('disabled',true);
}
$('#toggle').click(function(){
activate();
});
$('input[name="am_payment"]').change(function(){
if($(this).val() != ""){
deactivate();
}else{
activate();
}
});
</script>

JavaScript/HTML counter

im trying to write Html code for a small quiz consist of 10 questions, and its written with radio buttons, i want when the user answer or click on the right answer, the counter will increase by one, if he answer the second question right, the counter will become two, so like that..
also when user click on wrong answer i want to increase another counter to display the correct and right answer at the end..
so far i wrote the following html code just for two questions but it does not work.
<html>
<head>
<title>QUIZ</title>
<script type="text/javascript">
var correct=0;
var wrong=0;
function checkans(){
var ans = document.getElementById("quiz");
if( ans.elements[1].checked)
correct++
else
wrong++
var ans2 = document.getElementById("quiz2");
if( ans2.elements[0].checked)
correct++
else
wrong++
alert("Your correct answers : "+correct+" Your wrong answers : "+wrong)
}
</script>
</head>
<body>
<form id="quiz" onsubmit="checkans()" action="">
<p><font color=red>Q1- <font color=black>He ____ it.</p>
<input type="radio" name="radiobutton" value="one"/>
<label>Don't like</label></br>
<input type="radio" name="radiobutton" value="two"/>
<label>Doesn't like</label></br>
<input type="radio" name="radiobutton" value="three"/>
<label>Don't likes</label></br>`enter code here`
<form id="quiz2" onsubmit="checkans()" action="">
<p><font color=red>Q2- <font color=black>They _____ here very often.</p>
<input type="radio" name="radiobutton1" value="four"/>
<label>don't come</label></br>
<input type="radio" name="radiobutton1" value="five"/>
<label>doesn't comes</label></br>
<input type="radio" name="radiobutton1" value="six"/>
<label>doesn't come</label></br>
<input type="submit" name="submit" value="Grade me"/>
</form>
</body>
</html>
I would set up a function that takes the correct/incorrect value as an argument, then branch accordingly.
function checkAnswer(isCorrect)
{
if(isCorrect)
{ correct++; }
else
{ wrong ++; }
}
I'd do the call on the click of the radio button. Correct would be
checkAnswer(true);
Incorrect would be:
checkAnswer(false);
You'll need to adapt this based on whether or not your user can change their answers, but this should get you started.
Use the code below, used correct answer checkbox element
<html>
<head>
<title>QUIZ</title>
<script type="text/javascript">
var correct=0;
var wrong=0;
function checkans(){
var ans = document.getElementById("quiz1CorrectAnswer");
if( ans.checked)
correct++
else
wrong++
var ans2 = document.getElementById("quiz2CorrectAnswer");
if( ans2.checked)
correct++
else
wrong++
alert("Your correct answers : "+correct+" Your wrong answers : "+wrong)
}
</script>
</head>
<body>
<form id="quiz" onsubmit="checkans()" action="">
<p><font color=red>Q1- <font color=black>He ____ it.</p>
<input type="radio" name="radiobutton" value="one"/>
<label>Don't like</label></br>
<input id="quiz1CorrectAnswer" type="radio" name="radiobutton" value="two"/>
<label>Doesn't like</label></br>
<input type="radio" name="radiobutton" value="three"/>
<label>Don't likes</label></br>`enter code here`
<form id="quiz2" onsubmit="checkans()" action="">
<p><font color=red>Q2- <font color=black>They _____ here very often.</p>
<input id="quiz2CorrectAnswer" type="radio" name="radiobutton1" value="four"/>
<label>don't come</label></br>
<input type="radio" name="radiobutton1" value="five"/>
<label>doesn't comes</label></br>
<input type="radio" name="radiobutton1" value="six"/>
<label>doesn't come</label></br>
<input type="submit" name="submit" value="Grade me"/>
</form>
</body>
</html>
Try with jquery on Element.("input:checked")
http://api.jquery.com/checked-selector/

Newbie: Need explanation of a Js function

So I am doing a HTML and JavaScript related assignment which I am not required to have any prior knowledge of these scripting and programming languages. I was required to produce a document explaining how HTML and JavaScript brings about an entry form, and how JavaScript does validation check etc.
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" /> : AS<br />
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /> </td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
There's a task where I need to create 3 additional radio buttons for different level entries and then I was required to create a function which does a confirmation check, to ask the user to either confirm or cancel the choice after they have selected on a specific level entry. As I do not have any prior knowledge of programming(or I have learnt a little during the course of my assignment), I do not know how to create a function. Therefore, I googled it and found this page (It's the same assignment btw) From what I know from this page, I am required to change the radio buttons into:
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
and implement a function as such:
function confirmation() {
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an option');
return false;
} else {
return confirm('You have chosen '+checked.value+' is this correct?');
}
And great now I have done what it said, there's now an alert box which pops out and confirms choice of radio button with the user, so clicking on the radio button will trigger an onclick event which returns the function. Now my question is how does this function do the confirmation check?
(I am sorry if I wrote too much, my previous post was put on hold by as too broad by a few of people, because I wasn't being clear enough what I am suppose to say.)
Just add result &= confirmation(); in your validation code. Some where between your two if statements.
You need to watch the click event and determine whether or not you want to permit the action:
$(document).ready(function () {
$('input[type="radio"]').on('click', function () {
var r = confirm("Are you sure?");
if (r == true) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
});
http://jsfiddle.net/LTQ9p/1/

jQuery Radio Button function not working properly

I have a form with two radio buttons and a submit button which leads to a specific form based upon the user's selection.
I wanted to use jQuery to change between the two buttons but have gotten myself a bit lost.
Here is my javascript from another file in the proj:
function goTo()
{
var yesButton = $('#yesRad');
var noButton = $('#noRad');
if (yesButton[0].checked)
{
submitForm('yesForm') && noButton.Checked==false;
}
else (noButton[1].checked)
{
submitForm('noForm') && yesButton.Checked==false;
}
Inside the jsp I have the following code:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name ="radio"id="yesRad" value="yesForm" checked="checked" />Yes<br>
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name="radio" id="noRad" value="noForm" />No<br>
</form:form>
Submit
<script>
$("#yesRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked'))
$("#yesRad").prop("checked", false);
else if($input.is(':checked'))
$("#yesRad").prop("checked",true) && $("#noRad").prop("checked",false);
});
</script>
I have gotten some functionality out of my jQuery but it's definitely far from correct..
I hope I was clear and thorough in my question. Thanks in advance!!
To begin with, don't use prop, use attr. prop is slower.
You've defined variables so let's not look them up again. In your if/else statement just use the variables.
I'm not entirely sure what you're trying to do with the &&. I suspect you're trying to set the value of the two inputs. If so, they should be separate statements. If inputb is checked there is no reason to set it to checked, so we can remove that piece.
You probably want this change to fire on both inputs.
$("#yesRad, #noRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked')){
$input.attr("checked", false);
} else if($input.is(':checked')){
$inputb.attr("checked",false);
}
});
Solved: Using javascript and taking the radio buttons out of the separate form elements.
First let's take a look at the JSP form elements involved:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<input name="radio" type="radio" id="Yes" value="yes" />Yes<br>
<input name="radio" type="radio" id="No" value="no"/>No<br>
What I did here was simply take the radio buttons out of the separate forms and grouped them together...pretty obvious; now let's look at the javascript file.
function goHere()
{
var yesButton = $('#Yes');
var noButton = $('#No');
var str ="Please select an option first then press the 'Submit' button";
if (yesButton[0].checked)
{
submitForm('yesForm');
}
else if (noButton[0].checked)
{
submitForm('noForm');
}
else
{
document.write(str.fontcolor.font("red"));
}
}
As you can see the function 'goHere();' is going to tell the submit button in the following code where we want to go based on the user's selection on our radio buttons.
Here's the call from our javascript function in a submit button on the form...
<div class="button-panel" id="Submit"><span class="buttons buttons-left"></span>
<button type="button" class="buttons buttons-middle" name="submitBtn" onClick="goHere();">Submit</button>
<span class="buttons buttons-right"></span>
That's it!! Simply put; sometimes, while it's invaluable to learn something new, if it's not broke--etc. Hope this helps someone later on down the line!

Categories