Using radio buttons to change an image - javascript

So i have some radio buttons:
<input type="radio" name="option" value="GDP" id="GDP_option" checked>GDP
<input type="radio" name="option" value="Population" id="Population_option" >Population
<input type="radio" name="option" value="None" id="None_option" > None
I also have a submit button:
<input type="submit" name="submit" id="submit" onsubmit="changeFormula()">
and an image:
<img src="formula_gdp.gif" name="formula" id="formula">
When the submit button is pressed i want to change the image src to something else depending on the radio button that is checked. This is what i've tried:
function changeFormula(){
var radio = document.getElementsByName('option');
var formula = document.getElementsByName('formula')
if (radio[1].checked){
formula.src = "formula_gdp.gif";
}
if (radio[2].checked){
formula.src = "formula_pop.gif";
}
if (radio[3].checked){
formula.src = "formula_none.gif";
}
}

You can Do this by using Jquery as like following ..
<script type='text/javascript'>
$(document).ready(function(){
$("input:radio[name=option]").click(function() {
var value = $(this).val();
var image_name;
if(value == 'GDP'){
image_name = "formula_gdp.gif";
}else{
if(value == 'Population'){
image_name = "formula_pop.gif";
}else{
image_name = "formula_none.gif";
}
}
$('#formula').attr('src', image_name);
});
});
</script>
Only you will have needed those three radio button filed and Image tag .. Not needed Submit button...
<input type="radio" name="option" value="GDP" id="GDP_option" checked>GDP
<input type="radio" name="option" value="Population" id="Population_option" >Population
<input type="radio" name="option" value="None" id="None_option" > None
<img src="formula_gdp.gif" name="formula" id="formula">
Hopefully it will be helpful for you.. If you have needed another things... then you can inform me ....

Try this
$(document).ready(function() {
$("input:radio[name=vf]").change(function() { //name = button group name
if (this.value == "0") {
$("#vf").attr( //image file name
'src', '/images/onestep/lime/vf.jpg' //image path
);
}
else if (this.value == "8") {
$("#vf").attr( //image file name
'src', '/images/onestep/vf.jpg' //image path
);
}
else {
$("#vf").attr( //image file name
'src', '/images/onestep/vf.jpg' //image path
);
}
});

use if(document.getElementById('element_id').checked) for better result.

Two changes require:
1) Change var formula = document.getElementsByName('formula') to var formula = document.getElementById('formula');
2) Index of radio starts with 0 not with 1, so radio[1],radio[2],radio[3] should be radio[0],radio[1],radio[2]
Hope that helps.

Add an event <input type="submit" name="submit" id="submit" onsubmit="changeFormula(e)">
function changeFormula(e){
e.stopPropagation();
var radio = document.getElementsByName('option');
var formula = document.getElementsByName('formula')
if (radio[1].checked){
formula.src = "formula_gdp.gif";
}
if (radio[2].checked){
formula.src = "formula_pop.gif";
}
if (radio[3].checked){
formula.src = "formula_none.gif";
}
}
and if u dont mind using Jquery:
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
if($('#GDP_option').is(':checked')) {
$('#formula').attr('src','formula_gdp.gif')
}
if($('#Population_option').is(':checked')) { $('#formula').attr('src','formula_pop.gif')
}
if($('#None_option').is(':checked')) {
$('#formula').attr('src','formula_none.gif')
}
})
})

<input type="radio" name="option" value="GDP" id="GDP_option" checked>GDP
<input type="radio" name="option" value="Population" id="Population_option">Population
<input type="radio" name="option" value="None" id="None_option">None
<input type="submit" name="submit" id="submit" onclick="changeFormula()">
<img src="formula_gdp.gif" name="formula" id="formula">
<script type="text/javascript">
function changeFormula() {
var radio = document.getElementsByName('option');
var formula = document.getElementById('formula')
if (radio[0].checked) {
formula.src = "formula_gdp.gif";
alert(formula.src);
}
if (radio[1].checked) {
formula.src = "formula_pop.gif";
alert(formula.src);
}
if (radio[2].checked) {
formula.src = "formula_none.gif";
alert(formula.src);
}
}
</script>

Change the 'submit' to a button to stop the page from reloading
<input type="button" value ="Click Me" name="submit" id="submit" onclick="changeFormula()" />
And use this for your function
function changeFormula(){
var formula = document.getElementById('formula')
if(document.getElementById('GDP_option').checked)
formula.src = "formula_gdp.gif";
if(document.getElementById('Population_option').checked)
formula.src = "formula_gdp.gif";
if(document.getElementById('None_option').checked)
formula.src = "formula_none.gif";
}
working fiddle:
http://jsfiddle.net/UB2ka/
There is no image, but you can see the src change in firebug

I think folks love jquery, but I needed something lightweight.
Here it is:
<script>
function changeImage(imgName)
{
image = document.getElementById('theimage');
image.src = imgName;
}
</script>
And here's the radio buttons html (slightly modified for privacy)
<input type="radio" name="reader" value="reader1" onClick="changeImage('image0.jpg');">
<br>
<input type="radio" name="reader" value="reader1" onClick="changeImage('image1.jpg');">
<br>
<input type="radio" name="reader" value="reader1" onClick="changeImage('image2.jpg');">
Here's the image:
<img src="image0.jpg" name="theimage" id="theimage">
This worked for me. Click the radio button, the image changes.

Related

Get the values of column if checkbox/radio box is checked

I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>

Disable button if all checkboxes are unchecked

I have a list of checkboxes, and I need to disable my submit button if none of them are checked, and enable it as soon as at least one gets checked. I see lots of advice for doing this with just a single checkbox, but I'm hung up on getting it to work with multiple checkboxes. I want to use javascript for this project, even though I know there are a bunch of answers for jquery. Here's what I've got - it works for the first checkbox, but not the second.
HTML:
<input type="checkbox" id="checkme"/> Option1<br>
<input type="checkbox" id="checkme"/> Option2<br>
<input type="checkbox" id="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
I'd group your inputs in a container and watch that for events using addEventListener. Then loop through the checkboxes, checking their status. Finally set the button to disabled unless our criteria is met.
var checks = document.getElementsByName('checkme');
var checkBoxList = document.getElementById('checkBoxList');
var sendbtn = document.getElementById('sendNewSms');
function allTrue(nodeList) {
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].checked === false) return false;
}
return true;
}
checkBoxList.addEventListener('click', function(event) {
sendbtn.disabled = true;
if (allTrue(checks)) sendbtn.disabled = false;
});
<div id="checkBoxList">
<input type="checkbox" name="checkme"/> Option1<br>
<input type="checkbox" name="checkme"/> Option2<br>
<input type="checkbox" name="checkme"/> Option3<br>
</div>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
html
<input type="checkbox" class="checkme"/> Option1<br>
<input type="checkbox" class="checkme"/> Option2<br>
<input type="checkbox" class="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
js
var checkerArr = document.getElementsByClassName('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
for (var i = 0; i < checkerArr.length; i++) {
checkerArr[i].onchange = function() {
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
}
I guess this code will help you
window.onload=function(){
var checkboxes = document.getElementsByClassName('checkbox')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkbox"/> Option1<br>
<input type="checkbox" id="check2" class="checkbox"/> Option2<br>
<input type="checkbox" id="check3" class="checkbox"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Few suggestions
1.Always id should be unique. HTML does not show any error, if you give multiple objects with the same id but when you try to get it by document.getelementbyid it always return the first one,because getelementbyid returns a single element
when there is such requirement, you should consider having a classname or searching through the element name because getelementsbyclassname/tag returns an array
Here in the markup i have added an extra class to query using getelementsbyclassname
To avoid adding extra class, you can also consider doing it by document.querySelectorAll
check the following snippet
window.onload=function(){
var checkboxes = document.querySelectorAll('input[type=checkbox]')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check1" /> Option1<br>
<input type="checkbox" id="check2" /> Option2<br>
<input type="checkbox" id="check3" /> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Hope this helps
Something like this would do. I'm sure you can do it with less code, but I am still a JavaScript beginner. :)
HTML
<input type="checkbox" class="checkme" data-id="checkMe1"/> Option1<br>
<input type="checkbox" class="checkme" data-id="checkMe2"/> Option2<br>
<input type="checkbox" class="checkme" data-id="checkMe3"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
JavaScript
//keep the checkbox states, to reduce access to the DOM
var buttonStatus = {
checkMe1: false,
checkMe2: false,
checkMe1: false
};
//get the handles to the elements
var sendbtn = document.getElementById('sendNewSms');
var checkBoxes = document.querySelectorAll('.checkme');
//add event listeners
for(var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('change', function() {
buttonStatus[this.getAttribute('data-id')] = this.checked;
updateSendButton();
});
}
//check if the button needs to be enabled or disabled,
//depending on the state of other checkboxes
function updateSendButton() {
//check through all the keys in the buttonStatus object
for (var key in buttonStatus) {
if (buttonStatus.hasOwnProperty(key)) {
if (buttonStatus[key] === true) {
//if at least one of the checkboxes are checked
//enable the sendbtn
sendbtn.disabled = false;
return;
}
}
}
//disable the sendbtn otherwise
sendbtn.disabled = true;
}
var check_opt = document.getElementsByClassName('checkit');
console.log(check_opt);
var btn = document.getElementById('sendNewSms');
function detect() {
btn.disabled = true;
for (var index = 0; index < check_opt.length; ++index) {
console.log(index);
if (check_opt[index].checked == true) {
console.log(btn);
btn.disabled = false;
}
}
}
window.onload = function() {
for (var i = 0; i < check_opt.length; i++) {
check_opt[i].addEventListener('click', detect)
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkit" />Option1
<br>
<input type="checkbox" id="check2" class="checkit" />Option2
<br>
<input type="checkbox" id="check3" class="checkit" />Option3
<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="true" id="sendNewSms" value=" Send " />

check for empty radio input

I want to check if the user selects a radio button. I have coded this:
HTML
<form action="myServlet" method="post">
<input type="radio" id="rating-input-1-5" name="ratingInput1" value="5">
<input type="radio" id="rating-input-1-4" name="ratingInput1" value="4">
<input type="radio" id="rating-input-1-3" name="ratingInput1" value="4">
//etc
<button type="submit" class="myButton" onclick="sendSuccess()">Submit</button>
</form>
JS
function sendSuccess(){
var len = document.formRate.ratingInput1.length;
var flag;
for(i=0; i<len; i++){
if (document.formRate.ratingInput[i].checked){
flag = true;
}
else{
flag = false;
break;
}
}
if(flag === false){
console.log('noooooo');
return false;
}else{
console.log('yesssss');
}
}
But its not working.
You can do it with jQuery using Attribute Equals Selector [name="value"] to find radio button with same name and :checked to get only checked elements. You can use length to check if you get any checked radio button or not. The length will be zero of none of radio button is checked and will be greater then zero if one or more radio button is checked.
Live Demo
if($('[name=ratingInput1]:checked').length)
console.log('Yes');
else
console.log('No');
Working demo http://jsfiddle.net/cXPYQ/
Hope this fit your needs :)
Code
$("form").submit(function () {
var flag = true;
$(':radio').each(function () {
name = $(this).attr('name');
if (flag && !$(':radio[name="' + name + '"]:checked').length) {
alert(name + ' group not checked');
flag = false;
}
});
return flag;
});
try this
<form name="formRate" action="myServlet" method="post">
<input type="radio" id="rating-input-1-5" name="ratingInput1" value="5">
<input type="radio" id="rating-input-1-4" name="ratingInput1" value="4">
<input type="radio" id="rating-input-1-3" name="ratingInput1" value="4">
<button type="submit" class="myButton" onclick="return sendSuccess();">Submit</button>
</form>
function sendSuccess(){
var flag = false;
var len = $('input:radio[name="ratingInput1"]:checked').size();
if(len == 0){
console.log('noooooo');
flag = false;
}else{
console.log('yesssss');
flag = true;
}
return flag;
}
Its a simple form with radio buttons, so all you need is give the form a name formRate, and no need for jQuery, the following will work
HTML
<form name="formRate" action="myServlet" method="post">
<input type="radio" id="rating-input-1-5" name="ratingInput1" value="5">
<input type="radio" id="rating-input-1-4" name="ratingInput1" value="4">
<input type="radio" id="rating-input-1-3" name="ratingInput1" value="4">
<button type="submit" class="myButton" onclick="return sendSuccess();">Submit</button>
</form>
Javascript
function sendSuccess() {
rating = document.forms["formname"]["ratingInput1"].value;
if(rating > 0){
console.log(rating);
}
else {
console.log('No rating');
}
return false;
}
var flag = $('[name="ratingInput1"]').is(':checked');
will return false if no radio with that name is chosen.

Multiple Radio Buttons that change Submit onclick location.href...possible syntax error

I'm using http://www.somacon.com/p143.php javascript for radio buttons to change the submit onclick location.href depending on which radio button is selected. But I think I may have an issue with my syntax as the button isn't working properly (I don't think it is pulling the value from the radio buttons properly). Thanks in advanced!
Here is the code:
<head>
<script type="text/javascript">
<!--
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
//-->
</script>
</head>
<body>
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p><label for="number0"><input type="radio" value="http://www.google.com" name="number" id="number0"> Zero</label>
<label for="number1"><input type="radio" value="http://www.ebay.com" name="number" id="number1"> One</label>
<label for="number2"><input type="radio" value="http://www.gamestop.com" name="number" id="number2"> Two</label>
<label for="number3"><input type="radio" value="http://www.amazon.com" name="number" id="number3"> Three</label>
<label for="number4"><input type="radio" value="http://www.usatoday.com" name="number" id="number4"> Four</label>
<p>
<input type="button" onclick="location.href='+getCheckedValue(document.forms['radioExampleForm'].elements['number']);" value="Show Checked Value">
ORIGNAL SUBMIT CODE THAT MADE AN ALERT BOX RATHER THAN location.href = <input type="button" onclick="alert('Checked value is: '+getCheckedValue(document.forms['radioExampleForm'].elements['number']));" value="Show Checked Value">
</form>
</body>
It's just a syntax error.
Change it to:
onclick="window.location.href = (getCheckedValue(document.forms['radioExampleForm'].elements['number']));"

Clear contents on click

In the following code:
<INPUT TYPE="radio" name="1" id="1" VALUE="1" <?php echo $checked1 ?>><font size="2">1</font>
<INPUT TYPE="radio" name="2" id="2" VALUE="2" <?php echo $checked2 ?>><font size="2">2</font>
<TEXTAREA name="names" id="names" rows="15" cols="65"><?php echo $names ?></TEXTAREA>
If the radio button 1 selected for the first time then onclick on textarea its contents should be cleared, but if the user clicks for the second time on the same text area the contents should not be cleared for the same radio button1.
The same should hold good for radio button2. How is this done?
This will fullfill your requirement. just place in body tag
<input type="radio" name="G1" id="1" value="1" /> <font size="2">1</font>
<input type="radio" name="G1" id="2" value="2" /> <font size="2">2</font>
<textarea name="names" id="names" rows="15" cols="65" onfocus="handleOnFocus()"></textarea>
<script type="text/javascript">
var isCleardForButton1 = false;
var isCleardForButton2 = false;
function handleOnFocus() {
var objTA = document.getElementById("names");
var objRadio1 = document.getElementById("1");
var objRadio2 = document.getElementById("2");
if (isCleardForButton1 == false && objRadio1.checked == true) {
objTA.value = "";
isCleardForButton1 = true;
}
if (isCleardForButton2 == false && objRadio2.checked == true) {
objTA.value = "";
isCleardForButton2 = true;
}
}
</script>
Demo and here is the code:
<TEXTAREA name="names" id="names" rows="15" cols="65" onclick="doIt(this);">Hello There</textarea>
<script>
var isDone = false;
function doIt(field)
{
if (document.getElementById("1").checked == true && isDone == false)
{
field.value = "";
isDone = true;
}
}
</script>
This would clear contents for the first time and not again for the life time of page.
edit: Looks like I mis-understood your requirements. This only applies to the click of the radio button, not to the textarea.
You need to setup a click event to clear the textarea content, and then unbind itself.
With jQuery the event handler would be something like:
$('#names').val('');
$(this).unbind('click');

Categories