Compare the value of selected radio button - javascript

I have below code for radio button. When particular user select the 2nd radio button(value="Selection_MQ--") then I need to check if user has selected that particular button only then show message via alert message correct answer, and if select first one(value="Selection_MA--") then wrong answer. how I can do this?
<td valign="center"><input type="radio" class="question selection" name="Answer_1" id="Answer_1" value="Selection_MA--" /></td>
<td valign="center"><span class="answer text">No</span></td>
<td valign="center"><input type="radio" class="question selection" name="Answer_1" id="Answer_1" value="Selection_MQ--" /></td>
<td valign="center"><span class="answer text">Yes</span></td>
var Answer_1_data = $('input[name="Answer_1"]:checked').val();

Using Jquery
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[type='button']").click(function(){
var Answer_1_data = $('input[name="Answer_1"]:checked').val();
if(Answer_1_data){
if(Answer_1_data=="Selection_MQ--")
alert("Correct Anwser");
else
alert("Wrong Answer");
}
});
});
</script>
<td valign="center">
<input type="radio" class="question selection" name="Answer_1" id="Answer_1" value="Selection_MA--" /></td>
<td valign="center"><span class="answer text">No</span></td>
<td valign="center">
<input type="radio" class="question selection" name="Answer_1" id="Answer_1" value="Selection_MQ--" /></td>
<td valign="center"><span class="answer text">Yes</span></td>
<input type="button" id="btn" value="Submit">
Using Javascript
<script type="text/javascript">
function answer()
{
var ans = document.getElementsByName('Answer_1');
for (var i = 0, length = ans.length; i < length; i++) {
if (ans[i].checked) {
if((ans[i].value)=="Selection_MQ--")
alert("Correct Answer");
else
alert("Wrong ANswer");
}
}
}
</script>
<td valign="center">
<input type="radio" class="question selection" name="Answer_1" id="Answer_1" value="Selection_MA--" /></td>
<td valign="center"><span class="answer text">No</span></td>
<td valign="center">
<input type="radio" class="question selection" name="Answer_1" id="Answer_1" value="Selection_MQ--" /></td>
<td valign="center"><span class="answer text">Yes</span></td>
<input type="button" id="btn" value="Submit" onclick="answer()">

If you have radio buttons with the same name, users can only select one, so that part is easy. All you need to do then is show the correct message depending on which one is checked. All just plain javascript.
// Object with correct answers
var answers = {
Answer_1: 'Selection_MQ--'
}
// Function to check if answers are correct
function checkAnswer(){
alert(this.value == answers[this.name]? 'Correct!' : 'Wrong :-(');
}
// Attach listeners to radio buttons
window.onload = function() {
[].forEach.call(document.querySelectorAll('input[name="Answer_1"]'), function (radio){
radio.addEventListener('click',checkAnswer, false);
});
};
<fieldset><legend>Questions</legend>
<label for="Answer_1a"><input type="radio" class="question selection" name="Answer_1" id="Answer_1a" value="Selection_MA--">No</label>
<label for="answer_1b"><input type="radio" class="question selection" name="Answer_1" id="Answer_1b" value="Selection_MQ--">Yes</label>
</fieldset>
This is a good candidate for delegation, where the radios are wrapped in a fieldset and a single listener placed on the fieldset to check answers, rather than putting a listener on every radio button.

// return true if radio button is checked otherwise false
function radioButtonIsChecked( radioButton ) {
if ( radioButton.is( ':checked' ) {
return true;
} else {
return false;
}
}
// get the radio button element value
function getRadioButtonValue( radioButton ) {
if ( radioButtonIsChecked( radioButton ) {
return radioButton.val();
} else {
return null;
}
}
// try the code
for ( var i = 0; i < $( 'input[name="Answer_1"] ').length; i++ ) {
if ( "Selection_MQ--" == getRadioButtonValue( $('#Answer_' + i ) ) {
alert( "Correct Answer" );
} else {
alert( "wrong answer" );
}
}

Related

Div not showing when radio button checked

I have a radio button that will show a div with an input text when it is checked 'NO'. But it is not showing the div, however when I play around the radio button then the div will show. Where am I missing?
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
if (firstCheckbox.checked == true) {
rmk.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmk.style.display = "block";
document.getElementById("rmk").required = true;
}
}
<div>
<label>Have you registered the course?</label>
<table border=0>
<tr>
<td>YES </td>
<td><input type="radio" name="register" value="Y" id="check1" onclick="CheckboxCheck('first')">  </td>
<td>NO </td>
<td><input type="radio" name="register" value="N" checked id="check2" onclick="CheckboxCheck('second')"></td>
</table>
</div>
<div id="rmk" style="display:none">
<label>Reasons</label>
<input type="text" name="remarks" class="form-control">
</div>
There are a few structure and accessibility proposals going on in this suggestion but I think strictly speaking, the easiest solve for you is to invoke the function on page load. Give this example a look:
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
var rmkdiv = document.getElementById("rmk-div");
if (firstCheckbox.checked == true) {
rmkdiv.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmkdiv.style.display = "block";
rmk.required = true;
}
}
CheckboxCheck()
<div>
<p>Have you registered the course?</p>
<label>
YES<input
type="radio"
name="register"
value="Y"
id="check1"
onclick="CheckboxCheck()"
/></label>
<label>NO
<input
type="radio"
name="register"
value="N"
checked
id="check2"
onclick="CheckboxCheck()"
/>
</label>
<div id="rmk-div" style="display: none">
<label>Reasons</label>
<input id="rmk" type="text" name="remarks" class="form-control" />
</div>
</div>
Your input field will only be visible when the function CheckboxCheck is executed. Since "NO" is checked from the beginning, the function will not be executed because it is only called when a change takes place.

how to select multiple checkbox validation in javascript

Here is my Form. I need validation in JavaScript.
At least one checkbox selected in validation.
I hop you all are understand what I need.
please give me solution for that.
If any query then feel free ask.
<form action="#" method="post" name="studentregistration" onsubmit="return(validate());">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" value="Chess" id="hobby">Chess
<input type="checkbox" name="hobby" value="Music" id="hobby">Music<br>
<input type="checkbox" name="hobby" value="Cricket" id="hobby">Cricket
<input type="checkbox" name="hobby" value="Reading" id="hobby">Reading
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
If you're trying to validate that at least one checkbox is checked, then this should work for you using jQuery:
$('input[type="checkbox"]:checked').length > 0
In "pure" js, you could remove the onsubmit attribute and do this instead:
document.querySelector('form[name="studentregistration"]').onsubmit = function(e) {
e.preventDefault();
var cbx = document.querySelectorAll('form[name="studentregistration"] input[name="hobby"]:checked');
if(cbx.length > 0) {
// at least one checked - do something
}
else {
// none checked
}
}
See a live demo!
Complete solution.
In order to submit the form after validation you must use:
document.getElementById("myForm").submit();
document.getElementById("submitform").addEventListener("click",submit_form);
function submit_form(e){
var ob = "";
var chess = document.getElementById("hobby1").checked;
var music = document.getElementById("hobby2").checked;
var cricket = document.getElementById("hobby3").checked;
var reading = document.getElementById("hobby4").checked;
if(chess == true){
ob += "hobby: chess selected!\n";
}
if(music == true){
ob += "hobby: music selected!\n";
}
if(cricket == true){
ob += "hobby: cricket selected!\n";
}
if(reading == true){
ob += "hobby: reading selected!\n";
}
if(ob==""){
alert("No hobbys selected");
}
else{
alert(ob);
//document.getElementById("myForm").submit();
}
//for testing purposes
e.preventDefault();
return false;
}
<form id = "myForm" action="#" method="post" name="studentregistration">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" id="hobby1">Chess
<input type="checkbox" name="hobby" id="hobby2">Music<br>
<input type="checkbox" name="hobby" id="hobby3">Cricket
<input type="checkbox" name="hobby" id="hobby4">Reading
</td>
</tr>
<tr>
<td>
<input type="button" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
if($("#hobby").is(':checked')){
alert("checkbox checked");
}
else{
alert("Please select at least one checkbox");
}
Here is another easy answer
var test = document.getElementsByName("hobby[]");
if(test[0].checked==false && test[1].checked==false && test[2].checked==false && test[3].checked==false)
{
alert("Please Check");
return false;
}

Radio button with search box for HTML table

I have jQuery and table shown below:
console.clear();
function inputSelected(val) {
$("#result").html(function() {
var str = '';
$(":checked").each(function() {
str += $(this).val() + " ";
});
if (val == 1) {
return $('#testSearch').val();
}
str += $('#testSearch').val();
return str;
});
}
$(document).ready(function() {
$("input[type=radio]").click(inputSelected);
$("td.other").click(function() {
$(this).find('input[type=text]').focus();
});
$('#testSearch').on('input propertychange paste', function() {
inputSelected(1);
})
$("td.other input[type=text]").keyup(function(e) {
var value = $(this).val().trim();
if (value.length <= 0) {
value = 'Other';
}
$(this).parent().siblings("input[type=radio]").val(value);
$(this).parent().siblings("label").html(value);
inputSelected();
})
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<table>
<tr>
<td><input name="test" type="radio" value="You enter A" id="1" />A</td>
<td class="other"><input name="test" type="radio" value="" id="2"/>Other:
<div class="text">
<input type="text" id="other" value="">
</div>
</td>
<td><input name="test" type="radio" value="" id="3"/>Search<input id='testSearch' type="search" name="search" placeholder="Search...">
</td>
</tr>
</table>
<div id="result">
</div>
In this table I have 3 radio buttons:
Simple Radio Button
Radio Button with input box
Radio Button with search box
Like first 2 radio buttons 3rd 'search box' button is not working. For example when I click radio button 'a', it display "You enter A" then I click radio button 'other' and enter some text, on result it hide my last selected button display and show me whatever I type. Same if I select 'search' radio button it hide last selected button display and show me whatever I type.
But
After entering something to search when I clicked on any other 2 radio button, it did not hide text that I insert to search.
So, my problem is that when I select any one radio button, it should hide previous selected output like radio button 'A' and 'other' do.
Kindly advise me what changes I have to make in this script for such purpose. Thanks
Catch.
Also I commented some of Your code.
function inputSelected(val) {
$("#result").html(function() {
if (val == 1) {
return $('#testSearch').val();
}
var str = '';
$(":checked").each(function() {
str += $(this).val() + " ";
});
//str += $('#testSearch').val();
return str;
});
}
$(document).ready(function() {
$("input[name=test]").click(inputSelected);
$("td.other").click(function() {
$(this).find('input[type=text]').focus();
});
$('#testSearch').on('input propertychange paste', function() {
$("input[class=testSearch]").val($('input[id=testSearch]').val());
if($("input[class=testSearch]").is(':checked')){
inputSelected(1);
}
})
$("td.other input[type=text]").keyup(function(e) {
var value = $(this).val().trim();
if (value.length <= 0) {
value = 'Other';
}
$(this).parent().siblings("input[type=radio]").val(value);
$(this).parent().siblings("label").html(value);
inputSelected();
})
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<table>
<tr>
<td><input name="test" type="radio" value="You enter A" id="1"/>A</td>
<td class="other"><input name="test" type="radio" value="" id="2"/>Other:
<div class="text">
<input type="text" id="other" value="">
</div>
</td>
<td><input name="test" class="testSearch" type="radio" value="" id="3"/>Search<input id='testSearch' type="search" name="search" placeholder="Search...">
</td>
</tr>
</table>
<div id="result"></div>

Submit Value from price calculator [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have an order form that should filled with identity and price calculated with javascript. But I have no idea how to submit the calculated value to php file.
This is the code :
<html>
<head><title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
</head>
<body>
<table width="1020">
<form action="kirim.php" method="POST" >
<tr>
<td colspan="2"><h2>Form Pemesanan</h2></td>
</tr>
<tr>
<td width="80">Nama</td>
<td><input name="nama" type="text" id="nama" size="30" required="true"></td>
</tr>
<tr>
<td>Nomor HP</td>
<td><input name="nomor" type="text" id="nomor" size="30" required="true"></td>
</tr>
<tr>
<td><p>Email</p> </td>
<td><input name="email" type="text" id="email" size="30" required="true"></td>
</tr>
<tr>
<td></td>
<td><center>Nama Server</center></td><td><center>Masa Aktif</center></td><td><center>Jumlah (Rp.)</center></td><td><center>Diskon (Rp.)</center></td>
<tr>
<td>Server</td>
<td>
<input type="checkbox" name="server1" value="SSH AMERIKA (Nodes Direct)">SSH AMERIKA (Nodes Direct)
</td>
<td width="450">
<input onclick="hitung(this.value)" type="radio" id="a1" name="serverr1" value="10000">1 bulan
<input onclick="hitung(this.value)" type="radio" id="a2" name="serverr1" value="25000">3 bulan
<input onclick="hitung(this.value)" type="radio" id="a3" name="serverr1" value="50000">6 bulan
<input onclick="hitung(this.value)" type="radio" id="a4" name="serverr1" value="75000">9 bulan
<input onclick="hitung(this.value)" type="radio" id="a5" name="serverr1" value="100000">12 bulan</td>
<td width="120" id="amerika"></td>
<td width="100" id="amerika2"></td>
<tr>
</form>
</table>
<script>
var harga=0, harga2=0, harga3=0, harga4=0, hargasementara=0, hargasementara2=0, hargasementara3=0, hargasementara4=0;
//------------------------------------------------------HITUNG RADIO BUTTON 1-----------------------------------------------
function hitung(){
var hargasementara;
if (document.getElementById('a1').checked) {
hargasementara=10000;
harga=document.getElementById('a1').value;
}
else if (document.getElementById('a2').checked){
hargasementara=30000;
harga=document.getElementById('a2').value;
} else if (document.getElementById('a3').checked){
hargasementara=60000;
harga=document.getElementById('a3').value;
}
else if (document.getElementById('a4').checked){
hargasementara=90000;
harga=document.getElementById('a4').value;
}
else if (document.getElementById('a5').checked) {
hargasementara=120000;
harga=document.getElementById('a5').value;
}
else {
hargasementara=0;
}
document.getElementById("amerika").innerHTML = hargasementara;
document.getElementById("amerika2").innerHTML = hargasementara-harga;
akhir();
}
//------------------------------------------------------HITUNG RADIO BUTTON 2-----------------------------------------------
function hitung2(){
var hargasementara2;
if (document.getElementById('i1').checked) {
hargasementara2=15000;
harga2=document.getElementById('i1').value;
}
else if (document.getElementById('i2').checked) {
hargasementara2=45000;
harga2=document.getElementById('i2').value;
} else if (document.getElementById('i3').checked) {
hargasementara2=90000;
harga2=document.getElementById('i3').value;
} else if (document.getElementById('i4').checked) {
hargasementara2=135000;
harga2=document.getElementById('i4').value;
} else if (document.getElementById('i5').checked) {
hargasementara2=180000;
harga2=document.getElementById('i5').value;
} else {
hargasementara2=0;
}
document.getElementById("indonesia").innerHTML = hargasementara2;
document.getElementById("indonesia2").innerHTML = hargasementara2-harga2;
akhir();
}
//------------------------------------------------------HITUNG RADIO BUTTON 3-----------------------------------------------
function hitung3(){
var hargasementara3;
if (document.getElementById('s1').checked) {
hargasementara3=15000;
harga3=document.getElementById('s1').value;
}
else if (document.getElementById('s2').checked) {
hargasementara3=45000;
harga3=document.getElementById('s2').value;
} else if (document.getElementById('s3').checked) {
hargasementara3=90000;
harga3=document.getElementById('s3').value;
} else if (document.getElementById('s4').checked) {
hargasementara3=135000;
harga3=document.getElementById('s4').value;
} else if (document.getElementById('s5').checked) {
hargasementara3=180000;
harga3=document.getElementById('s5').value;
} else {
hargasementara3=0;
}
document.getElementById("singapura").innerHTML = hargasementara3;
document.getElementById("singapura2").innerHTML = hargasementara3-harga3;
akhir();
}
//------------------------------------------------------HITUNG RADIO BUTTON 4-----------------------------------------------
function hitung4(){
var hargasementara4;
if (document.getElementById('ss1').checked) {
hargasementara4=20000;
harga4=document.getElementById('ss1').value;
}
else if (document.getElementById('ss2').checked) {
hargasementara4=60000;
harga4=document.getElementById('ss2').value;
} else if (document.getElementById('ss3').checked) {
hargasementara4=120000;
harga4=document.getElementById('ss3').value;
} else if (document.getElementById('ss4').checked) {
hargasementara4=180000;
harga4=document.getElementById('ss4').value;
} else if (document.getElementById('ss5').checked) {
hargasementara4=240000;
harga4=document.getElementById('ss5').value;
} else {
hargasementara4=0;
}
document.getElementById("singapuraa").innerHTML = hargasementara4;
document.getElementById("singapuraa2").innerHTML = hargasementara4-harga4;
akhir();
}
function akhir(){
hargaakhir=harga*1+harga2*1+harga3*1+harga4*1;
document.getElementById("jumlah").innerHTML = hargaakhir;
}
</script>
<p> Jumlah Total Setelah Diskon:</p>
<p id="jumlah"></p>
</body>
So, I want hargaakhir variable (result of calculation) is submitted with the form to kirim.php
Thanks before,
as well as writing to the html element jumlah create a hidden form input
<input type="hidden" name="sum" value="">
populate it with the js and retrieve after the form was submitted with $_POST['sum']
In your "kirim.php" if you do
echo $_POST['serverr1'];
you'll get the form value since in your radio button you define the element name as "serverr1"

Radio button validation (alert box) confirmation and rejection

I'm working on a HTML document which is an exam submission form. I've completed almost all of the set tasks however, I'm having trouble validating radio buttons. I've searched on stackoverflow however, the answers do not meet the criteria of the question. My completed code is shown below.
I'm having trouble with the bold part of this task:
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Below is the code working, excluding the validation of the radio buttons. Seperatley, I have the code which doesn't work when implemented into the function validateForm().
<html>
<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 (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value.length!== 4) {
msg+="Your Examination Number should be 4 digits.\n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').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></tr>
<tr>
<td id="name">Name</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td id="subject">Subject</td>
<td>
<input type="text" name="subject" />
</td>
</tr>
<tr>
<td id="examinationno">Examination Number</td>
<td>
<input type="text" name="examno" />
</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="GCSE" />GCSE</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="AS" />AS</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="A2" />A2</td>
</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>
Based on the current code, why won't the following validate when added into the function?:
if(document.getElementById('GCSE').checked)
{examtype = "GCSE";
}
if(document.getElementById('AS').checked)
{examtype = "AS";
}
if(document.getElementById('A2').checked)
{examtype = "A2";
}
if(confirm("You have selected"+examtype+.Continue?")){
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
else{
alert("Action cancelled");
return false;
}
// Retrieving the checked radio button value
function getRadioValue (frmName, rbGroupName)
{
var radios = document[frmName].elements[rbGroupName];
for (var i=0; i <radios.length; i++)
{
if (radios[i].checked)
{
return radios[i].value;
}
}
return false;
}
Call the getRadioValue() inside validateForm()
// examtype gets false or GCSE or AS or A2
var examtype = getRadioValue ("ExamEntry", "examtype");
"Continue" is a keyword. So you have to wrap it in apostrophes("). I could not get the structure of if-statements, I made some changes. I hope this is what you are looking for..
if(confirm("You have selected"+examtype+". Continue?")){
if(msg==""){
alert(msg);
return result;
}
else{
alert("Action cancelled");
return false;
}
}

Categories

Resources