on select radio, redirect to a link - javascript

I have three radios and i want onselect of anyone to be redirected to a link. Using javascript or jquery
All <input name="EventRadio" type="radio" value="" checked="checked"/>
Events<input name="EventRadio" type="radio" value="Events" /> Classes<input name="EventRadio" type="radio" value="Classes"/><br /><br />
so since "All" is default checked, i want it to go to mysite.com/search.aspx.
now if user selects Events, I want to redirect user to mysite.com/search?type=Events
or if user selects Classes, I want to redirect the user to mysite.com/search?type=Classes
as response to the onselect of the radios. How do I achieve this?

All <input name="EventRadio" type="radio" value="" checked="checked" onclick ="goToLocation(this.value)"/>
Events <input name="EventRadio" type="radio" value="Events" onclick ="goToLocation(this.value)"/>
Classes <input name="EventRadio" type="radio" value="Classes" onclick ="goToLocation(this.value)"/><br /><br />
function goToLocation(val){
if(val == "Events")
window.location = "go to Events location";
if(val == "Classes")
window.location = "go to Classes location";
window.location = "go to default location";
}

As a demonstration:
var inputs = document.getElementsByTagName('input'),
radios = [],
output = document.getElementById('output'),
url = 'mysite.com/search?type=';
for (var i = 0, len = inputs.length; i<len; i++) {
if (inputs[i].type == 'radio'){
radios.push(inputs[i]);
}
}
for (var r=0, leng = radios.length; r<leng; r++){
radios[r].onchange = function(){
if (this.value){
/* in real life use:
document.location = url + this.value;
*/
output.innerHTML = url + this.value;
}
else {
/* in real life use:
document.location = 'mysite.com/search?type=Events';
*/
output.innerHTML = 'mysite.com/search.aspx';
}
}
}
JS Fiddle demo.
Please note that I've also changed your mark up to use <label> elements, and removed the s and <br />s.

$('input').click(function(){
var val = $(this).val();
if(val !== ''){
window.location = 'http://mysite.com/search?type=' + val;
}else{
window.location = 'http://mysite.com/search.aspx';
}
});

Related

display alert on each selected check box from a group of checkboxes

I have 3 checkboxes and I want them to do certain actions i.e display an alert box when they are checked and when one check box is checked, the others should be unchecked.
I've been able to get the second part to work where only one checkbox can be checked at a time but I can't seem to make the first part of displaying an alert box work.
js that ensures only one box is checked at any time:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
}
html:
<input class="qty" type="checkbox" id="pails" onchange="qtyBox(this)"/>Pails
<input class="qty" type="checkbox" id="liters" onchange="qtyBox(this)"/>Liters
<input class="qty" type="checkbox" id="gallons" onchange="qtyBox(this)"/>Gallons
Now all that's left is when Pails is checked,I want an alert box to display pails. when liters is checked, an alert box to display liters and when gallons is checked, an alert box to display gallons.
You need to get reference to the input. Just add:
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
so it become:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
}
Hope this help.
Use radio buttons with a common name (e.g. units) and a click listener to do the alert. Add a value attribute for the value, an ID seems redundant:
<input class="qty" name="units" type="radio" value="pails" onclick="alert(this.value)">Pails
<input class="qty" name="units" type="radio" value="litres" onclick="alert(this.value)">Litres
<input class="qty" name="units" type="radio" value="gallons" onclick="alert(this.value)">Gallons
Though I'd delegate the listener to an ancestor element.
You should remove the onclick from the html - and just use something like this. However, if you want to use jquery would easier, but here is vanilla javascript solution. ( in a js file or wrapped in script tags )
(function(){
var inputs = document.getElementsByClassName('qty');
for(i=0; i<inputs.length; i++){
var el = inputs[i];
el.addEventListener('click', function(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
this.checked = true
alert(this.id);
});
}
})();

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>

Stop checking checkboxes after a number of checkboxes have been checked in jQuery or JavaScript

I want to stop the user to check another checkbox after a certain number of checkboxes have been checked already. i.e. After 3 checkboxes are checked, the user cannot check anymore and a message says 'You're not allowed to choose more than 3 boxes.'
I'm almost there but the last checkbox is still being checked and I don't want that, I want it to be unchecked with the message appearing.
How do I do that:
var productList = $('.prod-list'),
checkBox = productList.find('input[type="checkbox"]'),
compareList = $('.compare-list ul');
productList.delegate('input[type="checkbox"]', 'click', function () {
var thisElem = $(this),
thisData = thisElem.data('compare'),
thisImg = thisElem.closest('li').find('img'),
thisImgSrc = thisImg.attr('src'),
thisImgAlt = thisImg.attr('alt');
if (thisElem.is(':checked')) {
if ($('input:checked').length < 4) {
compareList.append('<li data-comparing="' + thisData + '"><img src="' + thisImgSrc + '" alt="'+ thisImgAlt +'" /><li>');
} else {
$('input:checked').eq(2).attr('checked', false);
alert('You\'re not allowed to choose more than 3 boxes');
}
} else {
var compareListItem = compareList.find('li');
for (var i = 0, max = compareListItem.length; i < max; i++) {
var thisCompItem = $(compareListItem[i]),
comparingData = thisCompItem.data('comparing');
if (thisData === comparingData) {
thisCompItem.remove();
}
}
}
});
I might have misunderstood the question... see my comment.
Too prevent the selection, you can call event.preventDefault() and define the handler with the event parameter.
$('input[type="checkbox"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});
DEMO
Alternatively, set this.checked to false. This will even prevent the browser from rendering the checkmark.
DEMO
one single jquery function for multiple forms
<form>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg" ><br>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg"><br>
</form>
<br><br><br><br><br>
<form>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1" ><br>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1"><br>
</form>
$('input[type="checkbox"]').click(function(event) {
if ($("input[name= "+ this.name +"]:checked").length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});

Check if all radio buttons checked having particular value

<input type="radio" checked="checked" value="true" name="child">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="child">
<span class="label">Hide</span>
and another radio button on the same page
<input type="radio" checked="checked" value="true" name="baby">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="baby">
<span class="label">Hide</span>
I need to know if all the radio buttons having value="false" are checked using javascript.
Note: The radio button names are different
If you use jQuery, it's very clean:
if ($("input[type='radio'][value='false']").not(':selected').length==0) {
// Do what you want
}
The jQuery expression means all the false radio buttons are selected
boudou beat me by 35 seconds...
However, besides the for you can use a foreach logic:
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
var id = button.getAttribute("id");
var type = button.getAttribute("type");
var value = button.getAttribute("value");
var checked = button.getAttribute("checked");
if (type === "radio" && value === "false" && checked === "checked") {
alert(id);
}
}
The script can be condensed, it's written like this to allow a better understanding.
See a demo here.
You can try this:
function testRadios() {
var r = document.getElementsByTagName("input");
for (var i=0; i < r.length; i++) {
if ( (r[i].type == "radio")
&& (r[i].value == "false")
&& (r[i].checked != "checked")) {
return false;
}
return true;
}
PS: Use <label> instead of <span class="label">.

Undefined value, reading an input

i am geting undefined for ans . why? what is wrong?
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var ansVal = myForm.ans.value;
var qnoVal = myForm.qno.value;
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
<form nam="quiz" id="quiz" >
Yes:
<input type="radio" id="ans" name="ans" value="1" />
<br />No:
<input type="radio" id="ans" name="ans" value="0" />
<input id="qno" type="text" name="qno " value="qqq" />
<input type="button" value="" onClick="submitAnswer(); " />
</form>
Using theForm.inputElement is not standard and can't be guaranteed to work. Instead, you should use document.getElementById, or some other DOM mechanism, to find the input element you want. theForm.elements[name] also works.
You'll also need to fix your element IDs before you can do that - you have two <input type="radio" /> elements with an ID "ans", which is incorrect. IDs must be unique:
<input type="radio" id="ans1" name="ans" value="1" />
<input type="radio" id="ans2" name="ans" value="0" />
<script type="text/javascript">
var ans1 = document.getElementById('ans1');
var ans1value = ans1.value;
</script>
Or, get the radio button group as a single element using elements:
<script type="text/javascript">
var theForm = document.getElementById('quiz');
var ansValue = theForm.elements['ans'].value;
</script>
You have two elements with the same ID, causing a name conflict. They're also the same as the name attribute on the same element, which could cause some confusion down the road.
Try:
var ansVal = myForm.ans.checked;
This will work:
function submitAnswer() {
var myForm = document.getElementById('quiz');
// Set a default value, in case no radio button is selected
var ansVal = 'default value here';
var qnoVal = myForm.qno.value;
// Loop through radio buttons, getting the value of the
// one that is checked (selected).
var radioButtons = myForm.ans;
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
ansVal = radioButtons[i].value;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
this will work too
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var qnoVal = myForm.qno.value;
var ansVal = 'none';
for( i = 0; i < myForm.ans.length; i++ )
{
if( myForm.ans[i].checked == true )
{
ansVal = myForm.ans[i].value;
break;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
This will work
<html>
<form name="form">
Which one is good?<br>
<input type="radio" name="food" value="Spud"
checked="checked"> Spud<br>
<input type="radio" name="food" value="Carrot"> Carrot<br>
<input type="submit" onclick="get_radio_value()">
</form>
<script type="text/javascript>
<!--
function get_radio_value()
{
for (var i=0; i < document.form.food.length; i++)
{
if (document.form.food[i].checked)
{
var rad_val = document.form.food[i].value;
alert(rad_val);
}
}
}
//-->
</script>
</html>

Categories