The following is a simple javascript code to set a value into a textbox. But, it doesn't seem to work. I am not able to find the flaw. Also, the javascript is working only in IE and not in Chrome/Firefox. How do I get out of this trouble?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function reportValue()
{
var form = document.getElementById("billgen");
var radioArray = form["time"];
var months;
for(var i=0;i<radioArray.length;i++)
{
if(radioArray[i].checked)
{
months = radioArray[i].value;
break;
}
}
if(months == "1")
{
e=31*100;
form["total"].value = e;
//document.getElementById("total").value = e; => not working as well
return true;
}
else{
alert("Are you sure the instructor is " + months + "?\nYou may be underestimating the instructor!");
return false;
}
}
</script>
</head>
<body bgcolor="white">
<fieldset>
<legend>Bill Generation</legend>
<form id="billgen" method="post">
<label><input type="radio" name="time" value="1" checked /> 1 Month </label>
<label><input type="radio" name="time" value="3" /> 3 Month </label>
<label><input type="radio" name="time" value="6" /> 6 Month </label>
<label><input type="radio" name="time" value="12" /> 1 Year </label>
<input type="submit" value="submit" onclick="reportValue();" />
<p>
<input type="text" id="total" name="total" />
</p>
</form>
</fieldset>
</body>
</html>
Clicing on a <input type="submit"/> causes the page to reload, so instead of "submit", either use the <button> element or use an <input type="button"/>.
Here is your code with getElementById( instead of getElementById[: JSFiddle and it works.
Just move your code to the end of your html, just before the </body> and it should work, I think the problem is that you are asigning the form to a variable before the form even exists.
Related
I am trying to check if the radio button is checked or not, and also I am trying to get the value but I do not know why it does not work. I saw a lot of post, video on internet and also some on this site, but nothing. So helpless I am posting this on the site.
This is my HTML file
function getValue(){
var checkAge = false;
for(var i=0; i<4; i++){
if(document.getElementById("age"+i).checked){
checkAge = true;
}
}
}
function loadFunctions() {
getValue();
}
window.onload = loadFunctions;
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form id="form">
<section id="age_question">
<h2>How old are you?</h2>
<label for="age-one">1-25</label>
<input type="radio" name="ageRange" id="age1" value="0"/>
<label for="age-two">26-40</label>
<input type="radio" name="ageRange" id="age2" value="5" />
<label for="age-three">41-60</label>
<input type="radio" name="ageRange" id="age3" value="8" />
<label for="age-four">60+</label>
<input type="radio" name="ageRange" id="age4" value="10" />
</section>
<section id="bmi">
<h2>What is your BMI?</h2>
<label for="bmi-level"><span>0-25</span></label>
<input type="radio" name="bmi_range" id="" value="0"/>
<label for="bmi-level"><span>26-30</span></label>
<input type="radio" name="bmi_range" id="" value="0" />
<label for="bmi-level"><span>31-35</span></label>
<input type="radio" name="bmi_range" id="" value="9" />
<label for="bmi-level"><span>35+</span></label>
<input type="radio" name="bmi_range" id="" value="10" />
</section>
<section id="family_history">
<h2>Does anybody in your family have Diabetes?</h2>
<label for="history"><span>No</span></label>
<input type="radio" name="f_history" id="history" value="0"/>
<label for="history"><span>Grandparent</span></label>
<input type="radio" name="f_history" id="history" value="7" />
<label for="history"><span>Sibling</span></label>
<input type="radio" name="f_history" id="history" value="15" />
<label for="history"><span>Parent</span></label>
<input type="radio" name="f_history" id="history" value="15" />
</section>
<section id="diet">
<h2>How would you describe your diet?</h2>
<label for="diet"><span>Low sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0"/>
<label for="diet"><span>Normal sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0" />
<label for="diet"><span>Quite high sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="7" />
<label for="diet"><span>High sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="10" />
</section>
<button onclick="getValue()">Get You BMI</button>
<p id="message"></p>
</form>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
The first thing I'll suggest you do is to clear your browser cache, or launch the dev tools using F12 and check "Disable cache" on the "Network" tab.
Edit: Changed the button type, and made checkAge global.
Okay, the button does submit the form, making all changes to the variable lost after reload. To fix that, change the button type to just button, as:
<button type="button" onclick="getValue()">Get You BMI</button>
That way, it won't reload everytime you press the button. Another thing to do is make the checkAge variable global. that way is defined as false by default.
The "age"+i thing you did was starting the iteration with i=0, therefore giving the elementId as age0. This was making the element null.
To fix that, you can change the for-loop to for(var i=1; i<=4; i++) or using the same loop you've defined, but adding i by 1 before using it.
And the code would be like so:
var checkAge = false;
function getValue(){
for(var i=0; i<4; i++){
var index = i + 1
var element = document.getElementById("age"+index)
if(element.checked){
checkAge = true;
alert("The value is"+element.value)
}
}
}
Thanks.
Make the starting index be 1 instead of 0, since your ID selectors start from 1:
function getValue() {
var checkAge = false
for (var i = 1; i <= 4; i++) {
if (document.getElementById('age' + i).checked) {
checkAge = true
}
}
console.log(checkAge)
return checkAge
}
JSFiddle Demo: https://jsfiddle.net/a3fzd2kv/2/
You don't need to check the checked value of each of the radio buttons.
Here is a simpler solution:
var form = document.getElementById('form');
var ageRange = form.ageRange.value;
The value will equal to an empty string ('') when nothing is checked. Therefore, the logic for checkAge could be simplified to:
var checkAge = ageRange !== '';
your for loop is looping through i from 0 - 3, so your document.getElementById("age"+i) will look for id="age0", "age1", "age2, "age3".
Change your 'for' loop to for(var i=1; i<5; i++)
After clicking calculate button, its not showing the return value rather showing this error: "Uncaught ReferenceError: calculateTotal is not defined". I am very new to JavaScript. Please help.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>2</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="2.js"></script>
</head>
<body>
<div id="page">
<div id="header">
<h1> 02 </h1>
</div>
<div id="body">
<p>You probably want to retire someday so let's get started!</p>
<form name="retirement savings" action="#" OnClick="calculateTotal(amountNeeded.value, investNo, annContribute,inrate)">
How much money do you need to retire: <input type="text" name="savingsGoal"><br><br>
Initial Investment: <input type="text" name="initialInvestment"><br><br>
Annual Contribution: <input type="text" name="annualContribution"><br><br>
Expected Interest Rate: Select from the following please:<br><br>
<input type="radio" name="interestRate" value="1percent">1 Percent<br>
<input type="radio" name="interestRate" value="1.5percent">1.5 Percent<br>
<input type="radio" name="interestRate" value="2percent">2 Percent<br>
<input type="radio" name="interestRate" value="2.5percent">2.5 Percent<br>
<input type="radio" name="interestRate" value="3percent">3 Percent<br>
<input type="radio" name="interestRate" value="3.5percent">3.5 Percent<br>
<input type="radio" name="interestRate" value="4percent">4 Percent<br>
<input type="radio" name="interestRate" value="4.5percent">4.5 Percent<br>
<input type="radio" name="interestRate" value="5percent">5 Percent<br>
<input type="radio" name="interestRate" value="5.5percent">5.5 Percent<br>
<input type="radio" name="interestRate" value="6percent">6 Percent<br>
<input type="radio" name="interestRate" value="6.5percent">6.5 Percent<br><br>
<input type="button" onClick="calculateTotal(savingsGoal.value, initialInvestment, annualContribution,interestRate);" value="Calculate"> <input type="reset">
</form>
<br>
<hr>
<p>You can retire in years</p>
<p>with in the bank</p>
<hr>
</div>
<div id="footer"><br>
<a href="../index.html">Return to Main Menu</li>
</div>
</body>
</html>
JS:
/*Interest Radio Button*/
var interest_rate= new Array();
interest_rate["1percent"]=1;
interest_rate["1.5percent"]=1.5;
interest_rate["2percent"]=2;
interest_rate["2.5percent"]=2.5;
interest_rate["3percent"]=3;
interest_rate["3.5percent"]=3.5;
interest_rate["4percent"]=4;
interest_rate["4.5percent"]=4.5;
interest_rate["5percent"]=5;
interest_rate["5.5percent"]=5.5;
interest_rate["6percent"]=6;
interest_rate["6.5percent"]=6.5;
function getIntrestRate() {
var interestRadio = document.getElementsByName('interestRate');
for (i=0; i < interestRadio.length; i++) {
if (interestRadio[i].checked) {
user_input = interestRadio[i].value;
}
}
return interest_rate[user_input];
}
/*Calculation*/
function calculateTotal(savingsGoal.value, initialInvestment.value, annualContribution.value, interstRate.value)(){
if ((document.calc.savingsGoal.value == null || document.calc.savingsGoal.length == 0) ||
(document.calc.initialInvestment.value == null || document.calc.initialInvestment.length == 0)||
(document.calc.annualContribution.value == null || document.calc.rate.annualContribution.length == 0)){
alert("Please fill in required fields");
return false;
}
else
{
var amount = document.calc.savingsGoal.value;
var invest = document.calc.initialInvestment.value;
var yearly = document.calc.annualContribution.value / 1200;
var interest_rate= document.calc.getInterestRate.value;
document.calc.pay.value = amount * interest_rate / (1 - (1/(1 + intr), yearly)));
}
}
Your function has invalid definition. You have extra () after parameters inside ()
function calculateTotal(savingsGoal.value, initialInvestment.value,
annualContribution.value, interstRate.value)(){
//^^remove this
Update
Few points I just noted which stays invalid in your case. So just go through the code shown in this fiddle. I've updated both html and js. I've changed the logic of getting values to function.. Its a parameter less function now. Also getIntrestRate() is a function and you were trying to access it as a variable/element and the way you were calling it was wrong. There is a spelling mistake i.e. getInterestRate. Just go through the fiddle and please note that its not fully functional. Not sure what you are getting in intr variable at the end.
calculateTotal function is not defined properly because there is a syntax error in its signature.
make it
function calculateTotal(savingsGoal, initialInvestment, annualContribution, interstRate){
you can't access a property of an object here while defining a method.
Also there is an extra parenthesis ().
I think You Not Include Jquery Library file so you include jquery library file on header its working
https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js
or search latest version jquery library file include .
Hopefully somebody can prompt me into the right direction,
I want a simple 3 radio button form, lets say 1,2,3
once 1 has been selected i want to disable options 2 and 3 until page has been refreshed
so maybe those option would grey out and not be selectable
any help appreciated cant find a thing on google
We will group radio buttons in a div:
<div class="readioBtnDiv">
<input type="radio" name="group1" value="1" />1
</div>
<div class="readioBtnDiv">
<input type="radio" name="group2" value="1" />2
</div>
<div class="readioBtnDiv">
<input type="radio" name="group3" value="1" />3
</div>
Now we will disable another radio button when one is selected:
$("input:radio").click(function() {
var $this = $(this);
var value = $this.val();
$this.closest('.readioBtnDiv')
.siblings('.readioBtnDiv')
.find('input:radio[value="' + value + '"]')
.attr("disabled","disabled");
});
Here we go, jQuery way:
HTML:
<form>
<input type="radio" value="1"> 1
<input type="radio" value="2"> 2
<input type="radio" value="3"> 3
</form>
JS:
<script>
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
})
</script>
To add jQuery to your project - simply insert
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
inside your <head> </head> tag.
UPDATE:
To keep it after page refreshes you should modify your code to this:
<form>
<input type="radio" value="1" id="radio1"> 1
<input type="radio" value="2" id="radio2"> 2
<input type="radio" value="3" id="radio3"> 3
</form>
<script>
$('#'+localStorage.selected).trigger('click');
$('#'+localStorage.selected).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
localStorage.setItem('selected', $(this).attr('id'));
})
</script>
I think all the answers are right and accurate to your question above but according to me you would find this answer more useful and understandable if you are newbie
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function myFunction1() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction2() {
document.getElementById("radio1").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction3() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio1").disabled = true;
}
</script>
</head>
<body>
<div class="block">
<input onclick="myFunction1();" type="radio" id="radio1" value="Radio1" /><label>Radio1</label>
<input onclick="myFunction2();" type="radio" id="radio2" value="Radio2" /><label>Radio2</label>
<input onclick="myFunction3();" type="radio" id="radio3" value="radio3" /><label>radio3</label>
</div>
</body>
</html>
It's a working example according to your need. Cheers :)
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/
I want to select a radio button from javascript. I am using this simple html file to test the issue. The code below works correctly on firefox and chrome, however it does not work in IE (no version works). I would like to know why the supplied code does not work on IE, and how to select a radio button in IE?
<html>
<head>
<script type="text/javascript">
function chooseOne()
{
var randomChoice = Math.round(Math.random() * 2);
if(randomChoice == 0)
{
document.getElementById("test0").checked = true;
}
else if (randomChoice == 1)
{
document.getElementById("test1").checked = true;
}
else
{
document.getElementById("test2").checked = true;
}
}
</script>
</head>
<body>
<input type="radio" id="test0" name="test" value="a" /> A<br />
<input type="radio" id="test1" name="test" value="b" /> B<br />
<input type="radio" id="test2" name="test" value="c" /> C<br />
<input type="button" name="click" value="CHOOSE" onclick="javascript:chooseOne()" />
</body>
Thanks in Advance,
Spi
First of all, you should give all your radio buttons the same name, otherwise they will act as if they are independent buttons:
<input type="radio" name="test" id="test0" value="a" /> A<br />
<input type="radio" name="test" id="test1" value="b" /> B<br />
<input type="radio" name="test" id="test2" value="c" /> C<br />
I'm guessing this is also the source of your problem. Further, once you do this, you only need to set one radio button's checked to true, that will automatically remove the selection from other buttons.
I'm not certain, but possibly you have to tell IE that your onclick code is in javascript like this:
<input type="button" name="click" value="CHOOSE" onclick="javascript:chooseOne()" />
One problem:
var randomChoice = Math.round(Math.random() * 2);
will always yield to 1