how to make the radio buttons work in javascript? - javascript

I am learning the basics of JavaScript and still get some of the basics wrong and I tried to make it work, but failed. I am trying to make the message change font weight when one of the radio button is checked. JSfiddle: http://jsfiddle.net/Eg87P/
HTML/JavaScript Code:
<div id="prob2">
<h1>Radio Buttons</h1>
<p id="msg">Message</p>
<input type="radio" value="bold" name="rdFontStyle" id="bold"/>Bold<br/>
<input type="radio" value="italic" name="rdFontStyle" id="italic"/>Italic<br/>
<input type="radio" value="underline" name="rdFontStyle" id="underline"/>Underline<br/>
<input type="radio" value="regular" name="rdFontStyle" id="regular"/>Regular<br/>
<script type="text/javascript">
function msg1
{
var msg = document.getElementById("msg");
if(document.getElementById("bold").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "bold";
}
else if(document.getElementById("italic").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "italic";
}
else if(document.getElementById("underline").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "underline";
}
else if(document.getElementById("regular").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "normal";
}
}
msg1();
</script>
</div>

Open your JavaScript console and read the error message:
Uncaught SyntaxError: Unexpected token {
function msg1 should be function msg1()
when one of the radio button is checked
If you want to react to a radio button being checked then you need to listen for an event before running your function. At the moment you are running it immediately.
document.getElementById('prob2').addEventListener('change', msg1);
msg.style.fontWeight = "italic";
Italic isn't a font-weight. It is a font-style.
msg.style.fontStyle = "italic";
msg.style.fontWeight = "underline";
Underline isn't a font-weight. It is a type of text-decoration.
msg.style.textDecoration = "underline";
msg.style.fontWeight = "normal";
Normal is a font-weight, but it makes little sense to set it explicitly here since it is the default and you've just removed the other styles.

You're not running the msg1() function when the user clicks on the radio button, only once at script loading.Add a onClick on each radio button which calls msg1();And your function definition as previously commented.

var msg = document.getElementById("msg");
document.getElementById("bold").addEventListener("change", function() {
if (msg.hasAttribute("style")) {
msg.removeAttribute("style");
}
msg.style.fontWeight = "bold";
})

You never call the javascript function on the change of the radio buttons. I suggest adding the following:
<input type="radio" value="bold" name="rdFontStyle" id="bold" onchange="msg1()"/>Bold<br/>
<input type="radio" value="italic" name="rdFontStyle" id="italic" onchange="msg1()"/>Italic<br/>
<input type="radio" value="underline" name="rdFontStyle" id="underline" onchange="msg1()"/>Underline<br/>
<input type="radio" value="regular" name="rdFontStyle" id="regular" onchange="msg1()"/>Regular<br/>
Give that a try and see what happens =)
EDIT: You also need to add () after your declaration of the function:
function msg1()
{
...
}
Furthermore, you should use the correct style properties. The following works:
<script type="text/javascript">
function msg1()
{
var msg = document.getElementById("msg");
if(document.getElementById("bold").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "bold";
}
else if(document.getElementById("italic").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontStyle = "italic";
}
else if(document.getElementById("underline").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.textDecoration = "underline";
}
else if(document.getElementById("regular").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontStyle = "normal";
}
}
</script>

Related

Validate form: if radio button is not checked show error message Javascript

I am trying to show an error message if the checkboxes are unchecked.
My solution doesn't work. Please see below. Not sure how to check this.
<input type="radio" name="comm">Yes
<input type="radio" name="comm">No
<div id="error_message"></div>
<button id="btn">Submit</button>
document.getElementById("btn").addEventListener("click", function(event){
event.preventDefault();
myFunction();
});
function myFunction() {
var errortxt = "";
var radios = document.getElementsByName('comm');
for(var i = 0; i < radios.length; i++) {
if (radios[i].checked = false) {
errortxt = "Error text";
} else {
errortxt = "";
}
}
document.getElementById("error_message").innerHTML = "<p>" + errortxt + "</p>";
}
You made a mistake but you were on the good way of thinking, i did update your snippet with the correct synthax.
= is for assigning a value to a variable in javascript.
There are two operators for comparing values in JavaScript: strict equality === and “normal” (or lenient) equality == .
see http://2ality.com/2011/06/javascript-equality.html
for(const radio of radios){
if(!radio.checked){
errortxt = "Error text";
break; // this will break the loop when a radio is not checked (will save precious time !)
}
}
document.getElementById("btn").addEventListener("click", function(event){
event.preventDefault();
myFunction();
});
function myFunction() {
var errortxt = "";
var radios = document.getElementsByName('comm');
for(const radio of radios){
if(!radio.checked){
errortxt = "Error text";
break;
}
}
document.getElementById("error_message").innerHTML = "<p>" + errortxt + "</p>";
}
<input type="radio" name="comm">Yes
<input type="radio" name="comm">No
<div id="error_message"></div>
<button id="btn">Submit</button>
simply using required in HTML can fix this issue
like this :
<input type="radio" name="comm" required>

Change input from hidden to file

I have a problem with changing type of input in javascript.
When I change from hidden to text is ok and is proper displayed but when I change to file input isn't showing.
<script type="text/javascript">
function show(x,y) {
if (document.getElementById(y).checked) {
document.getElementById(x).setAttribute('type', 'file');
} else {
document.getElementById(x).setAttribute('type', 'hidden');
}
}
</script>
/*JQUERY
function show(x,y){
$(y).change(function() {
$("#txtAge").text(this.checked);
if(this.checked) $(x).attr('type','text')
else $(x).attr('type','file');
});
}
show('#a','#isAgeSelected');*/
//JAVASCRIPT
function show(x,y,z){
var typedefault=document.getElementById(x).type;
document.getElementById(y).onchange=function(){
document.getElementById('txtAge').innerText=this.checked;
if(this.checked){
document.getElementById(x).type = z;
} else {
document.getElementById(x).setAttribute('type',typedefault);
}
};
}
show('a','isAgeSelecteda','text');
show('b','isAgeSelectedb','text');
show('c','isAgeSelectedc','file');
/*
function supportsFileInput() {
var dummy = document.createElement("input");
dummy.setAttribute("type", "file");
return dummy.disabled === false;
}
alert(supportsFileInput());
*/
<input id="isAgeSelecteda" type="checkbox">
<input id="isAgeSelectedb" type="checkbox">
<input id="isAgeSelectedc" type="checkbox">
<p id="txtAge"></p>
<input type="hidden" id="a">
<input type="file" id="b">
<input type="hidden" id="c">
Try this:
function show(x, y) {
if (document.getElementById(y).checked) {
document.getElementById(x).type = 'text';
} else {
document.getElementById(x).type = 'file';
}
}
Fiddle1
function show(x, y) {
if (document.getElementById(y).checked) {
document.getElementById(x).type = 'text';
} else {
document.getElementById(x).type = 'hidden';
}
}
Fiddle2
Fiddle3
Below code should work.
Javascript code
document.getElementById(selector).setAttribute("type","file");
jQuery Code
$(selector).attr('type', 'file');
Sample code
HTML
<input type="checkbox" id="chkTest" onclick="myFunction()">
<input type="hidden" id="hdnFld" />
Java script
function myFunction() {
if(document.getElementById("chkTest").checked) {
document.getElementById("hdnFld").setAttribute("type","text");
} else{
document.getElementById("hdnFld").setAttribute("type","file");
}
}

unselecting radio input selection

In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>

If input name is value

This is my setup:
HTML
1. How are you?
<input class="calc" type="radio" name="1" value="2">Good
<input class="calc" type="radio" name="1" value="1">Okey
<input class="calc" type="radio" name="1" value="0">Bad
Javascript
if ( name 1 has value 2)
{ do something }
else if ( name 1 has value 1)
{ do something }
else if ( name 1 has value 0)
{ do something }
else
{ }
How do I make a if else statement out of name and value?
var names = document.getElementsByName("1");
if (names[0].checked)
{ do something }
else if (names[1].checked)
{ do something }
else if (names[2].checked)
{ do something }
else
{ }
Though it would seem simpler to just grab the checked one, and put its value in a switch() statement.
var chkd = document.querySelector(".calc:checked");
switch( chkd.value) {
case 2: // ...
break;
case 1: //
break;
default: // ...
}
However the :checked requires a modern browser, like IE9 or greater.
The general premise behind an if statement is:
if ('statement to evaluate') {
// Code to execute if above statement is true
} else if ('another statement')
// Code executes if first statement was false, but second one is true
} else {
// If both above statements are false, execute this code
}
Read more about if statments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
More about what evaluates to true: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
Here's a complete example. The best part is - you don't need conditions at all. You can use the value itself to determine what callback to use. This method is called "property lookup".
Live demo (click).
Sample Markup:
<form id="myForm">
<h3>1. How are you?</h3>
<input name="1" type="radio" value="2">
<label>Good</label>
<input name="1" type="radio" value="1">
<label>Okay</label>
<input name="1" type="radio" value="0">
<label>Bad</label>
<button disabled>Click me.</button>
</form>
JavaScript:
var inputs = document.querySelectorAll('#myForm input');
var submit = document.querySelector('#myForm button');
for (var i=0; i<inputs.length; ++i) {
inputs[i].addEventListener('click', function() {
submit.removeAttribute('disabled');
});
}
var responses = [
function() { //this is "responses[0]
console.log('this handles value 1!');
},
function() { //this is "responses[1]
console.log('this handles value 2!');
},
function() { //this is "responses[2]
console.log('this handles value 3!');
}
];
submit.addEventListener('click', function(e) {
var checked = document.querySelector("#myForm input:checked");
var x = checked.value;
responses[x](); //call the response function for this value
e.preventDefault(); //prevent the form from submitting
});

how to check if a check box is already checked before i click on it

I am modifying a functionality in which save button should only get enabled if any pre selected value get changed . For radio button i wrote a blunder code
HTML:
<input type="radio" id="allIB"style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this.id)">
<input type="radio" id="allOB" style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this.id)">
Javascript:
function enableSave1(id)
{
abc=id;
if(document.getElementById('abc').checked)
{
btnCommit.src='images\\Button\\Normal\\Save.gif';
btnCommit.disabled=false;
}
}
This is not working is there any way by which i can check if a radio button is already selected then clicking on it doesn't cause save button doesn't to get enable
use the else part of the if condition to disable the button and also remove the '' around abc:
else{
btnCommit.disabled=true;
}
change your function as
function enableSave1(id) {
if (document.getElementById(id).checked) {
btnCommit.src = 'images\\Button\\Normal\\Save.gif';
btnCommit.disabled = false;
} else {
btnCommit.disabled = true;
}
}
or your code as
HTML
<input type="radio" id="allIB" style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this)">
<input type="radio" id="allOB" style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this)">
JavaScript
function enableSave1(radio) {
if (radio.checked) {
btnCommit.src = 'images\\Button\\Normal\\Save.gif';
btnCommit.disabled = false;
} else {
btnCommit.disabled = true;
}
}

Categories