Onclick event not working with radio button - javascript

I am new to html
I am trying to add a onclick event with radio button but it is not working. I am unable to figure out the reason. Please help.
Example code
<script>
function select(btn)
{
var1=document.getElementById("radio1");
var2=document.getElementById("radio2");
var3=document.getElementById("radio3");
if(var1.checked==true)
{
document.myform.action="A.html";
}
elseif(var2.checked==true)
{
document.myform.action="B.html";
}
else
{
document.myform.action="C.html";
}
}
</script>
function test()
{
alert('Testing')
}
{% block radio_buttons %}
<br><br><br>
<!-- <input type="radio" id="radio1" name="project_type" value=0 checked onclick="alert('yes')"><label>Projects I own</label> -->
<input type="radio" id="radio1" name="project_type" value=0 checked onclick="select('this')"><label>Projects I own</label>
<br>
<input type="radio" id="radio2" name="project_type" value=1 onclick="test()"><label>Projects I manage</label>
<br>
<input type="radio" id="radio3" name="project_type" value=1 onclick="select()"><label>Projects I can edit</label>
<br>
{% endblock %}
This code I have added in templates. I tried adding alerts. Alert get exceuted but not onclick event

The select function contains a syntax error and is therefore never executed.
Write:
else if (var2.checked==true)
instead of
elseif (var2.checked==true)
To avoid these kind of errors open the developer console of your browser and check if syntax errors are shown.
Second the choice of select for the function name is unfortunate, since input elements have a select function which is called instead of your function.
To avoid this rename your function (e.g. radioSelect) and call it accordingly (onclick="radioSelect(this);").
Also your test function is placed outside of a script element which is not a good idea.

You have quite a few syntax errors in your code. And you don't need the (btn) after your select in your function. You have omitted a few semi-colons, not least the one after the testing alert.
This code works
<head>
<script>
function select() {
var1 = document.getElementById("radio1");
var2 = document.getElementById("radio2");
var3 = document.getElementById("radio3");
if (var1.selected === true) {
document.myform.action = "A.html";
}
else if(var2.selected === true) {
document.myform.action = "B.html";
} else {
document.myform.action = "C.html";
}
}
function test() {
alert('Testing');
}
</script>
</head>
<body>
<br>
<br>
<br>
<!-- <input type="radio" id="radio1" name="project_type" value=0 checked onclick="alert('yes')"><label>Projects I own</label> -->
<input type="radio" id="radio1" name="project_type" value=0 checked onclick="select();">
<label>Projects I own</label>
<br>
<input type="radio" id="radio2" name="project_type" value=1 onclick="test();">
<label>Projects I manage</label>
<br>
<input type="radio" id="radio3" name="project_type" value=1 onclick="select();">
<label>Projects I can edit</label>
</body>
Here is a fiddle

Related

addEventListener: click just one element of a bunch of elements

I'm beginner and have trouble with something in JS that might be simple to solve.
I made a quiz based on a NetNinja Udemy course, and I want the submit button to be enabled just when the user clicks on any answer option, and not before, so that he/she can't send a totally empty quiz.
The quiz has 4 questions with 2 options each, and I found this way...
const input_a = document.getElementById("q1a");
const input_b = document.getElementById("q1b");
button.disabled = true;
input_a.addEventListener('click', () => {
button.disabled = false;
});
input_b.addEventListener('click', () => {
button.disabled = false;
});
...to enable the button when the user clicks on any of the two options of the first question (ids: q1a & q1b) Following this logic, there'd also be q2a, q2b, q3a, q3b, q4a & q4b..
As there is a way to include all the answers in one JS element, what should I do in the event function to say "when you click any of this 8 options, enable the button"? Because everything I tried only makes the function work if I click all the buttons, which is obviously impossible in a Quiz .
Thank you! :)
In the solution below, when any of the radio buttons is clicked, the submit button is activated.
let result = [false, false, false, false];
let submitButton = document.getElementById('submitButton');
/* Returns true if all tests have been completed. */
function isValid(){
for(let i = 0 ; i < result.length ; ++i)
if(result[i] != true)
return false;
return true;
}
/* If all tests are completed, the submit button is activated. */
function send(){
result[this.value] = true;
if(isValid()){
submitButton.disabled = false;
console.log("The form can be submitted!");
}
}
/* The send() method is called when the change event of <input> elements whose type is "radio" is fired. */
document.querySelectorAll('input[type="radio"]').forEach((element) => {
element.addEventListener("change", send);
});
<form action="#">
<input type="radio" id="html" name="test1" value="0">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="test1" value="0">
<label for="css">CSS</label><br><br>
<input type="radio" id="js" name="test2" value="1">
<label for="html">JavaScript</label><br>
<input type="radio" id="c#" name="test2" value="1">
<label for="css">C#</label><br><br>
<input type="radio" id="c" name="test3" value="2">
<label for="html">C</label><br>
<input type="radio" id="c++" name="test3" value="2">
<label for="css">C++</label><br><br>
<input type="radio" id="python" name="test4" value="3">
<label for="html">Python</label><br>
<input type="radio" id="ruby" name="test4" value="3">
<label for="css">Ruby</label><br><br>
<button id="submitButton" type="submit" disabled>Submit</button>
</form>

why isn't 2nd IF statement read?

The second if statement is not reached/read.
I switched order of the two if statements; only the first produces a result. I put semicolons various places, but now I understand they are optional. I removed the line space.
function myChoices() {
if (document.getElementById("state").checked)
{document.write("state")}
else if (document.getElementById("county").checked)
{document.write("county")}
else {document.write("country")}
if (document.getElementById("range30").checked)
{document.write("30yrs")}
else if (document.getElementById("range50").checked)
{document.write("50 yrs")}
else {document.write("100yrs")}
}
<input type="radio" name="region" id="state">State <br>
<input type="radio" name="region" id="county">county <br>
<input type="radio" name="region" id="country">country <br>
<br><br>
<input type="radio" name="timerange" id="range30">30 years<br>
<input type="radio" name="timerange" id="range50">50 years<br>
<input type="radio" name="timerange" id="range100">100 years<br>
<button onclick="myChoices()">my selections are made</button>
I select one choice from each set of radio buttons and click the button. Only the result from the first if is returned.
Why?
The problem is document.write. As a rule of thumb, never use document.write.
In your example, when the first if statement calls document.write, it wipes out the HTML document and replaces it by e.g. country.
Then if (document.getElementById("range30").checked) runs, but document.getElementById("range30") doesn't find any element with id range30 because the whole page has been wiped out and replaced by country, so it returns null. Trying to access null.checked throws an exception, which aborts execution of the function.
If you really want to use document.write (which I don't recommend), only call it once, at the end of your function:
function myChoices() {
var text = "";
if (document.getElementById("state").checked) {
text += "state";
} else if (document.getElementById("county").checked) {
text += "county";
} else {
text += "country";
}
if (document.getElementById("range30").checked) {
text += "30yrs";
} else if (document.getElementById("range50").checked) {
text += "50 yrs";
} else {
text += "100yrs";
}
document.write(text);
}
<input type="radio" name="region" id="state">State <br>
<input type="radio" name="region" id="county">county <br>
<input type="radio" name="region" id="country">country <br>
<br><br>
<input type="radio" name="timerange" id="range30">30 years<br>
<input type="radio" name="timerange" id="range50">50 years<br>
<input type="radio" name="timerange" id="range100">100 years<br>
<button onclick="myChoices()">my selections are made</button>
In addition to the above to responses, it is not a good idea to use document.write in callback as it will replace the document content when invoked after the document has loaded. If the document is still open then it will not replace the content.
It is always safer to use .appendChild() to add new DOM elements.
For your use case you can use .textContent to display the results.
function myChoices() {
var resBox = document.getElementById("result");
var selectedRegion = "";
var selectedTimerange = "";
if (document.getElementById("state").checked)
{selectedRegion ="state"}
else if (document.getElementById("county").checked)
{selectedRegion = "county"}
else {selectedRegion ="country"}
if (document.getElementById("range30").checked)
{selectedTimerange ="30yrs"}
else if (document.getElementById("range50").checked)
{selectedTimerange ="50yrs" }
else {selectedTimerange ="100yrs"}
resBox.textContent = `${selectedRegion} ${selectedTimerange}`
}
<input type="radio" name="region" id="state">State <br>
<input type="radio" name="region" id="county">county <br>
<input type="radio" name="region" id="country">country <br>
<br><br>
<input type="radio" name="timerange" id="range30">30 years<br>
<input type="radio" name="timerange" id="range50">50 years<br>
<input type="radio" name="timerange" id="range100">100 years<br>
<button onclick="myChoices()">my selections are made</button>
<p id="result"></p>
When you click on the submit button, you will call the myChoices() function.
When it will first see a document.write, it will replace the whole HTML markup with your text in your input.
You can check the body of the result of your snippet:

How to do toggle two mutually exclusive radio buttons in HTML

I have two radio buttons. When I click on one, the other should become unchecked, and vice versa.
The code I've produced so far is not working:
<input type="radio" id="rbdemail" onclick="chekrbdclick()" checked="checked" />
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick()" />
function chekrbdclick()
{
// How to manage here?
}
Simple, just use a 'name' property with the same value for both elements:
<html>
<body>
<form>
<input type="radio" name="size" value="small" checked> Small
<br>
<input type="radio" name="size" value="large"> Large
</form>
</body>
</html>
hope it helps
<form>
<label>
<input type="radio" name="size" value="small" checked> Small
</label>
<br>
<label>
<input type="radio" name="size" value="large"> Large
</label>
</form>
Give them a name attribute with common value like size, and it will work. For best practice, you can place your input tag inside a label tag, so that, even if your user clicks on the text beside the button (ie on "Small" or "Large"), the respective radio button gets selected.
The perfect answer is above answered ,but I wanna share you how it can work by javascript ,this is javascript work (not standard answer) ....
<input type="radio" id="rbdemail" onclick="chekrbdclick(0)" checked="checked" value="Small" />Small<br>
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick(1)" value="Large" />Large
<script>
function chekrbdclick(n)
{
var small = document.getElementById('rbdemail');
var large = document.getElementById('rbdsitelnk');
if(n === 0){
small.checked = true;
large.checked = false;
}
else {
small.checked = false;
large.checked = true;
}
}
</script>

toggle textbox if checkbox is true for CMS

I try to make something like that work, implementing it in my CMS:
Fixed CMS part:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<input value="yes"></input>
<input value="no"></input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
own JS part someting like:
function EnableTextbox(radioListId,spanId)
{
if(document.getElementById(radioListId).inputValue == "yes")
document.getElementById(textBoxId).visibility = visible;
else
document.getElementById(textBoxId).visibility = hidden;
}
But I am not quite sure how to put it correctly - my understanding of js is not really high enough.
Any helping comments are highly appreciated!
try this
HTML
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" name="showhide"> Show</input>
<input type="radio" value="no" name="showhide"> Hide</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
Script
$(document).ready(function () {
$("#txtBoxId").hide();
$("input[name='showhide']").on("click", function () {
var option = $(this).attr('value');
if (option == "yes") {
$("#txtBoxId").show();
} else {
$("#txtBoxId").hide();
}
});
});
Fiddle Sample
There are a few changes you need to make:
the inputs need to have a type="radio" to indicate that those are radio buttons.
the inputs need to have a common name="whatever" to indicate that both belong to same group and cannot be checked simultaneously.
the inputs need to have a text between the opening/closing tags, this text appears next to the radio button.
you need to call the javascript function when you click/change the buttons, and inside you check which radio was selected.
you pass the radio button reference into the javascript function by writing this as the function variable.
inside the function you retrieve the radio button reference, you can name the variable whatever you want.
you are using visible and hidden as variables, but those are not defined. it supposed to be either a string, or a boolean value. i prefer to use css for that purpose.
here is an Example Fiddle
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" onclick="EnableTextbox(this);" name="Answer">Yes</input>
<input type="radio" value="no" onclick="EnableTextbox(this);" name="Answer">No</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
JS:
function EnableTextbox(radioList) {
if (radioList.value == "yes") document.getElementById("txtBoxId").style.visibility = "visible";
else document.getElementById("txtBoxId").style.visibility = "hidden";
}
Since onclick="" is outdated you should use the element.addEventListener();!
Here is an Example in Fiddle!
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<label><input type="radio" name="answer" id="yes" value="yes" />Yes</label>
<label><input type="radio" name="answer" id="no" value="no"/>No</label>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
JS:
var yes = document.getElementById('yes');
var no_ = document.getElementById('no');
if (yes.addEventListener) {
yes.addEventListener ("RadioStateChange", OnChange, false);
no_.addEventListener ("RadioStateChange", OnChange, false);
}
function OnChange(){
if (yes.checked) {
document.getElementById('txtBoxId').style.display = 'inline';
}
else {
document.getElementById('txtBoxId').style.display = 'none';
}
}
Greetings from Vienna
In jQuery
<span id="spanId">
<input type="radio" name="radiobutton" value="yes" />
<input type="radio" name="radiobutton" value="no" />
</span>
$('#spanId input:radio[name="radiobutton"]').change(function(){
if($(this).val() === 'yes'){
$('#txtBoxId').show();
} else {
$('#txtBoxId').hide();
}
});
Explanation
$('#txtBoxId').show() = display:block;
$('#txtBoxId').hide() = display:none;
If you want visibility instead.
$('#txtBoxId').css('visibility','visible');
$('#txtBoxId').css('visibility','hidden');
Let me know if you have any question.

OnClick of RadioButton not working

I was trying to change the text of a submit button on change of radio button .My code for html part is :
<input type="radio" onclick="check()" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment1" value="Yes"/>
<label for="segment1" id="controls">
<span class="ui-btn-text-controls">Yes</span>
</label>
<input type="radio" onclick="check()" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment2" value="No" checked="checked"/>
<label for="segment2" id="controls">
<span class="ui-btn-text-controls">No</span>
</label>
<input type="submit" value="send" name="sendbutton" id="sendbutton"/>
My javascript code is as follow :
function check(){
var x;
x=document.f1.radio-view;
if(x[0].checked){
document.f1.sendbutton.value="PROCEED";
}
else if(x[1].checked){
document.f1.sendbutton.value="SEND";
}
}
But its not changing the test.What can be the reason for it?
If you decide to address elements directly, use their names properly:
var x = document.f1['radio-view'];
... as you cannot access with the dot syntax the properties which names are not valid identifiers. document.f1.radio-view is treated as document.f1.radio - view, which apparently makes no sense.
But actually, I'd rather skip this part completely: if radio-button is clicked, it's definitely set as checked. So this...
<input type="radio" onclick="check(this)" ... />
...
function check(button) {
document.f1.sendbutton.value = button.value === 'Yes' ? 'PROCEED' : 'SEND';
}
... should be quite enough, as this demo shows.
See Demo here: http://jsfiddle.net/Tngbs/
//HTML
<form>
<fieldset id="SPserviceStatus" data-role="controlgroup" data-type="horizontal" data-mini="true">
<legend>Group<span class="required">*</span></legend>
<input type="radio" name="ss" id="s1" value="Yes">
<label for="serviceStatus1">Yes</label>
<input type="radio" name="ss" id="s2" value="No" checked="checked">
<label for="serviceStatus2">No</label>
</fieldset>
<input type='submit' id='submitBtn' value='SUBMIT' />
</form>
//JS
$("#s1").click(function () {
document.getElementById("submitBtn").value = "Yes Clicked";
return false;
});
$("#s2").click(function () {
document.getElementById("submitBtn").value = "No Clicked";
return false;
});

Categories

Resources