Javascript: Image not matching value of radio button - javascript

I am working with radio buttons and displaying an image depending on the radio button chosen. But somehow I am receiving an error with the image array. I only get two pictures displayed and does not match the proper value. Is the error in my array or the html? EXAMPLE
Reference of bikes:
Bike1.jpg
Bike2.jpg
Bike3.jpg
JS
<script>
function check_value(val) {
var imgs = ['images/bike1.jpg', 'images/bike2.jpg', 'images/bike3.jpg'];
var img = imgs[val];
var el = document.getElementById("imgBox");
if (img) {
el.src = img;
el.style.display = "";
}
}
</script>
HTML
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(1)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(2)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(3)'/> Aprilia RSV4<br />
</form>
<img id="imgBox" src="#" style="display:none">

Arrays are zero-indexed. You should call:
check_value(0)
to get the first item, and 1 for the second, 2 for the third.
Note how choosing your first item loads the second image, and the second item the third.

Arrays start at index 0, so you have the following alternatives:
use imgs[val-1]
change your array to [null, "img1", "img2 ...]
start your images at img0
However, a much better approach is:
function check_value(val) {
var el = document.getElementById("imgBox");
if (val>0 && val<4) { //will trigger when [1,2,3], modify it according to your needs
el.src = "images/bike" + val + ".jpg";
el.style.display = "";
}
}

Javascript arrays are indexed starting from 0 and going up. So
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(1)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(2)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(3)'/> Aprilia RSV4<br />
</form>
Should be
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(0)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(2)'/> Aprilia RSV4<br />
</form>

Related

Changing URL on radio button selection

I'm trying to change the URL when I select radio button.
I have found an answer that works for 'select' form elements, but if I apply it to my radio buttons it lists out all the options instead of the one that is selected
My JS
$('.unitfiltercontrol').change(function(){
var params =[];
$('.unitfiltercontrol').each(function(){
$this=$(this);
if(!$this.val()=='') params.push($this.data('param')+'='+encodeURIComponent( $this.val() ));
});
$('#urlDisplay').text(window.location.href+('?'+params.join('&'))); //print to div for testing
});
My HTML:
<form>
<input id="radio1" type="radio" value="1" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio2" type="radio" value="2" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio3" type="radio" value="1" name="bar" data-param="bar" class="unitfiltercontrol">
<input id="radio4" type="radio" value="2" name="bar" data-param="bar" class="unitfiltercontrol">
</form>
<div id="urlDisplay"></div>
So if I select radio1, instead of the URL being displayed as:
/?foo=1
I get:
/?foo=1&foo=2&bar=1&bar=2
How would I modify this to work with radio buttons?
Hi friend you can use if condition when pushing parameters to like below
$('.unitfiltercontrol').change(function(){
var params =[];
$('.unitfiltercontrol').each(function(){
$this=$(this);
if ($(this).prop("checked")) { //get the values of only checked radio buttons
if(!$this.val()=='') params.push($this.data('param')+'='+encodeURIComponent( $this.val() ));
}
});
$('#urlDisplay').text(window.location.href+('?'+params.join('&'))); //print to div for testing
});
Radio button in your case make single selection , so no need to loop each radio , just get in the change the value and data for current clicked , then create object using data-param as key , after that loop thorough keys and create and array of key + values as below ; snippet :
let values = {};
$('.unitfiltercontrol').change(function(e){
let data = $(this).data('param');
let value = this.value;
values[data] = value;
let params = [];
let keys = Object.keys(values);
for(inc = 0; inc < keys.length ; inc ++) {
let key = keys[inc];
params.push(key+'='+encodeURIComponent(values[key]))
}
$('#urlDisplay').text(window.location.href+('?'+params.join('&')));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
My HTML:
<form>
<input id="radio1" type="radio" value="1" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio2" type="radio" value="2" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio3" type="radio" value="1" name="bar" data-param="bar" class="unitfiltercontrol">
<input id="radio4" type="radio" value="2" name="bar" data-param="bar" class="unitfiltercontrol">
</form>
<div id="urlDisplay"></div>
<div id="urlDisplay">
</div>

it needs to count the values but its doesnt work javascript

i have made a small code but he needs to count the value + a other value but its not work but he only places everything side by side. its a realy stupid question i know. I just do not see how it should be done.
You are trying to add two strings.
When you get value, notice your value is in quotes making it a string. You can parse int from string. You want to add something to handle when only 1 number is selected.
<!DOCTYPE html>
<html>
<body>
<form id="first" name="first">
<input type="radio" name="rads" value="1" />1
<input type="radio" name="rads" value="2" />2
<input type="radio" name="rads" value="3" />3
<input type="radio" name="rads" value="4" />4
</form>
<form id="second" name="second">
<input type="radio" name="rads" value="1" />1
<input type="radio" name="rads" value="2" />2
<input type="radio" name="rads" value="3" />3
<input type="radio" name="rads" value="4" />4
</form>
<span id="result"></span>
<script>
document.onclick = function hoi(){
var first = document.first.rads.value;
var second = document.second.rads.value;
var all = parseInt(first) + parseInt(second);
result.innerHTML = all;
}
</script>
</body>
</html>
The value property on a input is string, so there is string concatenation going on, convert both inputs to a number then add:
result.innerHTML = Number(first) + Number(second)
First of all, welcome to StackOverflow!
The solution to your problem is very simple: The value property returns a string, and using + on strings concatenates them. You first have to convert it to a number using parseInt(), and then add them together which would look like so:
var all = parseInt(first) + parseInt(second);

Accessing the radio button value

Html Code: -
<input type="radio" name="radio" id="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate()"> For Users</input>
</p>
And JavaScript Code : -
function validate()
{
var btn_value=document.getElementById("radio").value;
if(btn_value==true)
{
alert(btn_value);
}
}
Now, whenever I am trying to print the value of radio button. It is always printing value as 1.
So, Now I don't understand what exactly am I missing here...
Thanx in advance for your help.
Elements ID should be unique. I modified your HTML and JS part and check below
Try this
HTML
<p>
<input type="radio" name="radio" id="radio1" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio2" value="2" onclick="validate(this)"> For Users</input>
</p>
JavaScrpit
function validate(obj)
{
var btn_value=obj.value;
if(btn_value==true)
{
alert(btn_value);
}
}
first of all never use a DOMID twice in your html!
remove them.... only use dublicated names!
<input type="radio" name="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" value="2" onclick="validate()"> For Users</input>
</p>
with the js check every element with the name attribute!
function validate() {
var elements = document.getElementsByName("radio");
for(var n = 0; n < elements.length; n++) {
if(elements[n].checked === true) {
alert(elements[n].value);
}
}
}
if you use your validate method ONLY in the onclick you can pass the domelement in the validate methode like this:
<input type="radio" name="radio" value="1" onclick="validate(this)"> For Yourself</input> </p>
and your js:
function validate(domElement) {
if(domElement.checked === true) {
alert(elements[n].value);
}
}
try this
<input type="radio" name="radio" id="radio" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate(this)"> For Users</input>
</p>​
function validate(ele)
{
alert(ele.value);
}​
IDs MUST be unique, it's a mistake to give it the same id.
You can give the IDs a running number (- radio1,radio2 etc) and loop through them to check which one was selected.

JavaScript for loop "document.getElementById"

Hi I am trying to go throw radio buttons using a for loop , with ID of "Group" and get the value of it show out here is my code but it doesnt alert the value of them on submit,
http://jsfiddle.net/JAwZg/
HTML:
<input type="radio" id="group1" name="group" value="1" />
No Changes<br/>
<input type="radio" id="group2" name="group" value="2" />
Gray Scale <br/>
<input type="radio" id="group3" name="group" value="3" />
Old Style<br/>
<input type="radio" id="group4" name="group" value="4" />
Sharpening<br/>
Script:
var ims = document.getElementsByName("group");
for(var i = 0; i < ims.length; i++){
ims[i].onclick = function(){alert("hi");}
}
​http://jsfiddle.net/JAwZg/4/
you can also do that like this.instead of ID give it a class
var yourString;
$.each($('.className'), function(i, k){
yourString += $(k).val()+',';
});
yourString = $.trim(yourString);
yourString = yourString.substring(0, yourString.length - 1);

How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group.
One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.
In my case, I have many checkbox groups on the same page, so I want it to work like this example.
An asp.net codebehind example is here, but I want to do it in client side code.
How can I do this in JavaScript?
i have decided to use the ajax mutually exclusive checkbox extender.
The solutions given so far are basically based on radio buttons.
This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender
Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows
HTML
<div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>
<div>
Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>
Jquery
$('div .checkbox').click(function () {
checkedState = $(this).attr('checked');
$(this).parent('div').children('.checkbox:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
And here is fiddle
Like I said in my comment, you should really use <radio> elements for this. Give them the same name and they work almost the same way:
<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>
The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again).
If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element.
I hope this one will work
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
JavaScript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well.
Update
Looking at my answer, I realized it's redundant to refer to the css class twice. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference
Get all checkboxes whose check is mutually excluded
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Group all mutually excluded checkboxes in a containing element
JavaScript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Enjoy :-)
Try this:
HTML
<div>
Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>
<span>
Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">
Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>
​JavaScript/jQuery
$(':checkbox.radiocheckbox').click(function() {
this.checked
&& $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
.prop('checked', false);
});​
Mutually exclusive checkboxes are grouped by container+name+classname.
You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name.
JavaScript code is highly optimized. You can see a working example.
No matter where the check box is located on your page, you just need to specify the group and here you go!
<input type='checkbox' data-group='orderState'> pending
<input type='checkbox' data-group='orderState'> solved
<input type='checkbox' data-group='orderState'> timed out
<input type='checkbox' data-group='sex'> male
<input type='checkbox' data-group='sex'> female
<input type='checkbox'> Isolated
<script>
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var state = $(this)[0].checked,
g = $(this).data('group');
$(this).siblings()
.each(function () {
$(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
});
});
})</script>
I guess this is what you want.
Consider the HTML below:
<form action="">
My favourite colors are:<br />
<br />
<input type="checkbox" value="red" name="color" /> Red<br />
<input type="checkbox" value="yellow" name="color" /> Yellow<br />
<input type="checkbox" value="blue" name="color" /> Blue<br />
<input type="checkbox" value="orange" name="color1" /> Orange<br />
<input type="checkbox" value="green" name="color1" /> Green<br />
<input type="checkbox" value="purple" name="color1" /> Purple
</form>
Note that there's two names for color groups: red, yellow, blue and orage, green, purple
And this JavaScript noted below will work generically to all checkbox on the page.
jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
var checkbox = jQuery(value);
checkbox.bind("click", function () {
var check = checkbox.attr("checked");
jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
checkbox.attr("checked", check);
});
});
Take a look at this LIVE example

Categories

Resources