Click event on radio buttons jquery - javascript

I have looked for few other answers and tutorials but havent been able to find what I want. For example, I found this which uses change function, however, I need to use a click event and detect when a radio button is clicked. When a radio button is click I will be showing message to show like "you have selected radio button 1".
For example, below are my 3 radio buttons and I want to assign click event to them
<input type="radio" name="one" value="first" id="radio1" checked> first
<input type="radio" name="two" value="second" id="radio2" checked> second
<input type="radio" name="three" value="third" id="radio3" checked> third
I have tried
1
var inputs = document.querySelectorAll('input');
for (var i = 0; i <= inputs.length; i++) {
$("input[id='radio'+i]").click(function(){
if(inputs == 'radio1') {
//dosomething
} else if (inputs == 'radio2') {
//dosomething
}else if (inputs == 'radio3') {
//dosomething
}
});
}
2
var inputs = document.querySelectorAll('input');
for (var i = 0; i <= inputs.length; i++) {
$("#radio"+i).click(function(){
if(inputs == 'radio1') {
//dosomething
} else if (inputs == 'radio2') {
//dosomething
}else if (inputs == 'radio3') {
//dosomething
}
});
}
Please can someone help me on this as I have searched but havent been able to find anything of help.

you do not have radio buttons group of different names. You are likely to have something like this
<form id="myForm">
<input type="radio" name="radio" value="first" checked> first
<input type="radio" name="radio" value="second"> second
<input type="radio" name="radio" value="third"> third
</form>
$('#myForm input').on("change", function() {
console.log($(this).attr('value')); // based on the value do something.
});
thanks

Related

Grabbing freetext and radio button values in pure javascript

I have several radio buttons, and the last radio button has a freetext option next to it. I had success getting the values of the radio button OR the freetext, but never both in the same function.
If I had 3 choices, and the 4th choice was another, I would want the function to grab the value without creating a separate Javascript function.
Here was my attempt:
<input type="radio" id = "choice1" name="snooze" value="samplechoice0" onClick='valuechanged();'/> samplechoice0<br>
<input type="radio" id = "choice2" name="snooze" value="samplechoice1" onClick='valuechanged();'/> samplechoice1<br>
<input type="radio" id = "choice3" name="snooze" value="samplechoice2" onClick='valuechanged();'/> samplechoice2 <br>
<input type="radio" id = "choice10" name="snooze" value="Normal Radio" onClick='valuechanged();'/>
<input type="text" id = "choice11" class="tb" name="tb1" placeholder="Enter Other Reason Here" onkeypress='valuechanged();' > <br>
function Submit() {
var items=document.getElementsByClassName('radio');
var selectedItems=" ";
for(var i=0; i<items.length; i++) {
if(items[i].type=='radio' && items[i].checked==true && document.getElementById('choice10').checked==false) {
selectedItems+=items[i].value+"; ";
}
}
if(document.getElementById("choice10").checked == true) {
selectedItems = document.getElementById('choice11').value;
}
alert(selectedItems);
}
Assuming I'm understanding your question, I would pair the two together using a name that matches the radio input's value. For example, if you have a radio input with value="other", just create a textbox with name="otherText"
Then, using an object like { snooze, snoozeText }, allow both values to potentially be undefined, empty string, or whatever else works in your situation. For example:
document.querySelector('.js-snooze-form').addEventListener('submit', e => {
e.preventDefault()
const formElements = e.currentTarget.elements
// Get the snooze value
const snoozeEl = Array.from(formElements.snooze).filter(el => el.checked)[0]
const snooze = snoozeEl && snoozeEl.value
// Get the paired text, if any
const snoozeTextEl = formElements[`${snooze}Text`]
const snoozeText = snoozeTextEl && snoozeTextEl.value
// "Return" the checked snooze value paired with the reason text
console.log({ snooze, snoozeText })
})
form {
display: grid;
gap: 1em;
justify-items: start;
}
<form class="js-snooze-form">
<label><input type="radio" name="snooze" value="0" />Choice 0</label>
<label><input type="radio" name="snooze" value="1" />Choice 1</label>
<label><input type="radio" name="snooze" value="2" />Choice 2</label>
<!-- Define a pairing between other & otherText -->
<div>
<label><input type="radio" name="snooze" value="other" />Other:</label>
<input name="otherText" placeholder="Enter Other Reason Here" />
</div>
<button>Submit</button>
</form>
You can change the ID of the last radio button with free text dynamically by making it equal to the text which is given in by the user.
I also added in following code that when the user gives text input next to the last radio button, the last radio button is automatically checked.
You can then grab the ID of the radio button which is checked.
<form id="radiobuttonForm" name="radiobuttonForm">
<input type="radio" name="choice" id="choice1"> samplechoice0
<br>
<input type="radio" name="choice" id="choice2"> samplechoice1
<br>
<input type="radio" name="choice" id="choice3"> samplechoice2
<br>
<input type="radio" name="choice" id="other" class="other_reason_radio"> samplechoice3
input type="text" id="other_reason_text_input"/>
</form>
var choice;
function getChoice(){
var radios = document.forms["radiobuttonForm"].elements["choice"];
for(var i = 0, max = radios.length-1; i < max; i++) {
radios[i].onclick = function() {
choice=this.id;
console.log('choice: ', choice);
}
}
radios[radios.length-1].onclick = function() {
document.getElementsByClassName("other_reason_radio")[0].id=document.getElementById("other_reason_text_input").value;
choice=this.id;
console.log('choice: ', choice);
}
}
document.getElementById("radiobuttonForm").addEventListener("click", getChoice());
document.getElementById('other_reason_text_input').addEventListener('input', function() {
document.getElementsByClassName("other_reason_radio")[0].checked = true;
document.getElementsByClassName("other_reason_radio")[0].id=document.getElementById("other_reason_text_input").value;
choice=document.getElementById("other_reason_text_input").value;
console.log('choice: ', choice);
});

How to do radio button validation in jquery

In my application i have two radio buttons,one text box and one button
<input type="radio" name="myRadio" value="red" id="myRadio" checked>Red color
<input type="radio" name="myRadio" value="Blue" id="myRadio">Blue color
<input type="text" id="txtShareCount" name="txtColor"/>
<input type="submit" name="btnsubmit" value="Blue" id="btnsubmit">submit
Here when i check Blue color radio button text box will appear
what i want is, I need to do validation for text box in jquery when i check Blue color radio button if text box is empty then click submit button it display alert message how can i do this in jquery
I did this in javascript it works fine but I need in jquery how can i do this in jquery
To get the value of your radio use:
$('input[name=myRadio]:checked', '#myForm').val()
Or if you're not using a form
$('input[name=myRadio]:checked').val()
For radiobutton you can use :checked selector - $('#myRadio:checked')
As per the traditions and the documentations. Your js gets messed up if you have more than 1 element with same id. So instead of using getElementById() use getElementsByName()
So something like this
function validateRadio() {
var radios = document.getElementsByName("myRadio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
alert("Must check some option!");
return formValid;
}​
Note :
1-don't have multiple elements with the same Id
2-when use getElementById , you must enter id attribute
Try this
function myFunction() {
if (document.getElementById('myRadioRed').checked == true || document.getElementById('myRadioBlue').checked == true) {
if (document.getElementById('txtShareCount').value == "") {
alert("Please Enter Color");
document.getElementById("txtShareCount").focus();
return false;
}
return false;
}
else { return true; }
}
<input type="radio" name="myRadio" value="red" id="myRadioRed" checked>Red color
<input type="radio" name="myRadio" value="Blue" id="myRadioBlue">Blue color
<input type="text" id="txtShareCount" name="txtColor" />
<input type="button" name="btnsubmit" value="Blue" id="btnsubmit" onclick="myFunction()"/>

disabling and enabling the radio buttons

i have one checkbox and two radio buttons. when i check the checkbox.i want both the radio buttons to enable and when i uncheck the checkbox i want both the radio button to get disable
below is the code which i have tried
<script>
function myfunction()
{
var radio=document.getElementsByName("disableme");
var len=radio.length;
for(var i=0;i<len;i++)
{
radio[i].disabled=true;
}
}
</script>
Notification
<input type="checkbox" onclick=myfunction() checked>
<input type="radio" name="disableme" id="1"> open
<input type="radio" name="disableme" id="2">close
You should check if checkbox is checked - in order to do that you can pass the element when your calling the function.
see example below
<script>
function myfunction(el) {
var radio=document.getElementsByName("disableme");
var len=radio.length;
for(var i=0;i<len;i++) {
radio[i].disabled=!el.checked;
}
}
</script>
Notification
<input type="checkbox" onclick=myfunction(this) checked>
<input type="radio" name="disableme" id="1">open
<input type="radio" name="disableme" id="2">close

Multiple quiz with checkboxes - multiple options

I have the following HTML:
<fieldset id="question1">
<legend>Which are fruit?</legend>
<label><INPUT TYPE="checkbox" NAME="q1" VALUE="wrong">tomatoes<BR></label>
<label><INPUT TYPE="checkbox" NAME="q2" VALUE="wrong">cucumber<BR></label>
<label><INPUT TYPE="checkbox" NAME="q3" VALUE="right">apples<BR></label>
<label><INPUT TYPE="checkbox" NAME="q4" VALUE="wrong">onion<BR></label>
<label><INPUT TYPE="checkbox" NAME="q5" VALUE="right">bananas<BR></label>
</fieldset>
<input type="button" id="answer">
and JavaScript:
document.getElementById("answer").onclick = validate;
function validate() {
var checkbox;
var i;
var right;
checkboxes = document.getElementById("question1").getElementsByTagName("input");
right = false;
for(i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].value == "right" && checkboxes[i].checked == true) {
right = true;
}
}
if(right) {
alert("You answered correctly");
} else {
alert("Wrong answer");
}
}
My Quiz is almost working but I only want it to be correct when all the right options are checked. At the moment when one correct option is selected it still returs as correct regardless of whether other incorrect ones were also selected.
Here is the live sample: http://jsfiddle.net/nzLmxfx7/
Thanks!
Try this, which works on my computer.
HTML:
<fieldset id="question1">
<legend>Which are fruit?</legend>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="wrong">tomatoes<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="wrong">cucumber<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="right">apples<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="wrong">onion<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="right">bananas<BR></label>
</fieldset>
<input type="button" id="answer" value="Submit">
JavaScript:
document.getElementById("answer").onclick = validate;
function validate() {
var checkboxes = document.getElementsByName("input");
var checkboxChecked = [];
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked && (checkboxes[i].value === "right")) {
checkboxChecked.push(checkboxes[i]);
}
}
if(checkboxChecked.length === 2) {
alert("You answered correctly");
}
else {
alert("Wrong answer");
}
}
Do it other way. Set right to true by default and set it to false if either correct checkbox is not checked or wrong checkbox is checked.
You are only setting the value of flag (right) to true if user has selected a checkbox whose value is true.
You also need to set flag to false if user has selected a checkbox whose value is false.
For Ex:
If user checked apples and onions. Then your code will check apples checkbox and set the flag to true. There would be no code executing for the Onions.
I think you got my point
Add:
if(checkboxes[i].value == "wrong" && checkboxes[i].checked == true) {
right = false;
}

How can I change the background color when I click on a radio button

JavaScript
<script>
function changeColor() {
var element = user.elements["group1"];
for (var i = 0; i < element.length; i++) {
if (element[i].checked == true) {
var newColor = element[i].value;
alert("hai");
document.getElementById("changeColor").style.background = newColor;
}
}
}​
</script>
HTML
<div id="color">
<input type="radio" name="group1" id="color1" value="#990000" /><label for="color1">Red</label>
<input type="radio" name="group1" id="color2" value="#009900" /><label for="color2">Green</label>
<input type="radio" name="group1" id="color3" value="#FFFF00" /><label for="color3">Yellow</label><br><br><br>
<button onclick="changeColor()">Change</button>
The above HTML and JavaScript code is fine when I click on the radio button the background color is changed. It is working properly. However, my problem is that after the color change the browser will automatically refresh, which I do not want.
After click on submit button the onclick event will call. So if you send boolean value return false then the page is not submit here is code i am using return false;
<script>
function changeColor() {
var element = user.elements["group1"];
for (var i = 0; i < element.length; i++) {
if (element[i].checked == true) {
var newColor = element[i].value;
document.getElementById("changeColor").style.backGround = newColor;
return false;
}
}
}
</script>
Change the onlick event add return before your changeColor() function
<button onclick="return changeColor();">Change</button>
I highly suggest you use jQuery:
HTML
<button id="btnColor">Change</button>
jQuery:
$('#btnColor').live('click', function(e) {
e.preventDefault();
$('#changeColor').css('background-color', $('input:radio[name=group1]:checked').val());
});
You could wrap the radio-buttons with a form, like this, leaving the button outside:
<form name="form_radiobuttons">
<input type="radio" name="group1" id="color1" value="#990000" /><label for="color1">Red</label>
<input type="radio" name="group1" id="color2" value="#009900" /><label for="color2">Green</label>
<input type="radio" name="group1" id="color3" value="#FFFF00" /><label for="color3">Yellow</label><br><br><br>
</form>
<input type="button" onclick="changeColor()">Change</button>
This way the form won't be submitted when you click the button.
Its looks like your button is the only button in the form so the browser is thinking its the submit button for the form.
As pointy says you can add a type to the button, add you onclick function to a different element such as a link (with an anchor not an actual link of course otherwise you will get the same problem) or move the button outside of the form.

Categories