How do you change the appearance of a button in javascript? - javascript

I'm very new to web development, so bear with me. I know how to do this when the submit button is created in the HTML page, with the help of CSS. But can you apply CSS to the javascript block? The reason I want to declare the Submit button in javascript is because eventually I want the submit button to send the choice into an SQL database, and I figure it would be much easier to do that in javascript as opposed to HTML. Please tell me if I'm completely on the wrong track.
function myFunction() {
var x = document.getElementById("myRadio");
x.checked = true;
}
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>webpage</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
Radio Button:
<input type="radio" id="myRadio">
<input type="radio" id="myRadio2">
<input type="radio" id="myRadio3">
<button onclick="myFunction()">Submit</button>
</body>
</html>

Here's the basic idea of an HTML form, which will post the values of your selected radio buttons. You can review the POST by looking at a dev tool like Firebug.
<body>
<form method="POST" action="mypostpage.php">
<input name="myRadio" type="radio" value="1"> Choice 1
<input name="myRadio" type="radio" value="2"> Choice 2
<input name="myRadio" type="radio" value="3"> Choice 3
<input type="submit" value="Submit">
</form>
</body>
If you want to generate the radio buttons in JavaScript/JQuery, here's a general pattern:
JSFiddle
JQuery:
//see what value is selected
$('#myForm').on('change', function() {
var selectedRadio =$('input[name="myRadio"]:checked', '#myForm').val()
console.log(selectedRadio);
});
//add more radios
$('#addRadio').on('click', function() {
var lastRadioVal = parseInt($('input[name="myRadio"]:last', '#myForm').val());
for (i = lastRadioVal + 1; i <= lastRadioVal + 5; i++) {
$('#myForm').append('<input type="radio" name="myRadio" value="' + i + '"> Choice ' + i );
}
});
HTML:
<form id="myForm" method="POST" action="mypostpage.php">
<input name="myRadio" type="radio" value="1"> Choice 1
<input name="myRadio" type="radio" value="2"> Choice 2
<input name="myRadio" type="radio" value="3"> Choice 3
<input type="submit" value="Submit">
</form>
<input type="button" id="addRadio" value="Add Radio">
UPDATED
(JSFiddle link remains the same as above)
HTML
<form id="myForm" method="POST" action="mypostpage.php">
<input name="myRadio" type="radio" value="1"> Choice 1
<input name="myRadio" type="radio" value="2"> Choice 2
<input name="myRadio" type="radio" value="3"> Choice 3
<input id="myButton" type="button" value="Submit">
JQuery
//see what value is selected
$('#myForm').on('change', function() {
var selectedRadio =$('input[name="myRadio"]:checked', '#myForm').val()
console.log(selectedRadio);
});
//add more radios
$('#addRadio').on('click', function() {
var lastRadioVal = parseInt($('input[name="myRadio"]:last', '#myForm').val());
for (i = lastRadioVal + 1; i <= lastRadioVal + 5; i++) {
$('#myForm').append('<input type="radio" name="myRadio" value="' + i + '"> Choice ' + i );
}
//change button style
if($(this).hasClass("warning")) {
$(this).removeClass("warning");
$(this).addClass("error");
$(this).val("Error!");
} else {
$(this).addClass("warning");
$(this).val("Warning!");
}
});
//change the button styling
$('#myButton').on('click', function() {
$(this).addClass("validated");
//you'll need to submit the form since the button is just a button and not a submit button. i've commented it out below because this is just an example
//$('#myForm').submit();
});
CSS
.validated {
background: green;
}
.warning {
background: yellow;
}
.error {
background: red;
}

Related

Why isn't my javascript/jquery code working as expected for checkboxes

I have a code where I expect my checkboxes to be selected and disabled. When I click Zero, all checkboxes should be highlighted, all checkboxes except zeroth checkbox should be disabled. Similarly for one, two and three radio buttons. This does not seem to happen consistently. I am trying it on chrome browser version 48.0.2564.116. Also, the behavior is horrible on Firefox. Can someone please let me know what I am doing wrong?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input[name=radio_group]").prop("checked", false);
$("input[type=radio]").click( function( e ){
var whats_selected = $("input[name=radio_group]:checked").val()
$("input[type=checkbox]").attr('checked',false );
//disable all other checkboxes
for(i=0; i < 4; i++ ){
var elem = $("input[type=checkbox][name*=checkbox"+i+"]");
elem.click();
if( i != whats_selected ){
elem.prop("disabled", true);
}else{
elem.removeAttr("disabled");
}
}
});
});
</script>
</head>
<body>
<h1>Checkbox play</h1>
<h3>My 4 Radio Buttons</h3>
<input type="radio" name='radio_group' value=0>Zero<br>
<input type="radio" name='radio_group' value=1>One<br>
<input type="radio" name='radio_group' value=2>Two<br>
<input type="radio" name='radio_group' value=3>Three<br>
<p>And here are my checkboxes</p>
<input type='checkbox' id="chkbox0" name="checkbox0" value="checkbox0">Checkbox Zero<br>
<input type='checkbox' id="chkbox1" name="checkbox1" value="checkbox1">Checkbox One<br>
<input type='checkbox' id="chkbox2" name="checkbox2" value="checkbox2">Checkbox Two<br>
<input type='checkbox' id="chkbox3" name="checkbox3" value="checkbox3">Checkbox Three<br>
</body>
</html>
I think this should do the trick (if I get your question correctly)
$("input[type=radio]").click(function(e) {
var whats_selected = $(this).val();
// check an disable all checboxes
$("input[type=checkbox]")
.attr('checked', true)
.prop('disabled', true);
// enable the targetted checkbox
$('#chkbox' + whats_selected)
.prop('disabled', false);
});
Have a look at the demo: https://jsfiddle.net/a5og0soL/
Here is another way to do it, matching the index of the radio/checkbox pair:
jsFiddle Demo
var ndx;
$(document).ready(function() {
$("input[type=radio]").click(function() {
ndx = $("input[type=radio]").index(this);
$("input[type=checkbox]").attr('checked', true).prop('disabled', true);
$("input[type=checkbox]").eq(ndx).prop('disabled',false);
});
}); //END document.ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>My 4 Radio Buttons</h3>
<input type="radio" name='radio_group' value=0>Zero
<br>
<input type="radio" name='radio_group' value=1>One
<br>
<input type="radio" name='radio_group' value=2>Two
<br>
<input type="radio" name='radio_group' value=3>Three
<br>
<p>And here are my checkboxes</p>
<input type='checkbox' id="chkbox0" name="checkbox0" value="checkbox0">Checkbox Zero
<br>
<input type='checkbox' id="chkbox1" name="checkbox1" value="checkbox1">Checkbox One
<br>
<input type='checkbox' id="chkbox2" name="checkbox2" value="checkbox2">Checkbox Two
<br>
<input type='checkbox' id="chkbox3" name="checkbox3" value="checkbox3">Checkbox Three
<br>

How to grey out other radio buttons after one is selected until refresh

Hopefully somebody can prompt me into the right direction,
I want a simple 3 radio button form, lets say 1,2,3
once 1 has been selected i want to disable options 2 and 3 until page has been refreshed
so maybe those option would grey out and not be selectable
any help appreciated cant find a thing on google
We will group radio buttons in a div:
<div class="readioBtnDiv">
<input type="radio" name="group1" value="1" />1
</div>
<div class="readioBtnDiv">
<input type="radio" name="group2" value="1" />2
</div>
<div class="readioBtnDiv">
<input type="radio" name="group3" value="1" />3
</div>
Now we will disable another radio button when one is selected:
$("input:radio").click(function() {
var $this = $(this);
var value = $this.val();
$this.closest('.readioBtnDiv')
.siblings('.readioBtnDiv')
.find('input:radio[value="' + value + '"]')
.attr("disabled","disabled");
});
Here we go, jQuery way:
HTML:
<form>
<input type="radio" value="1"> 1
<input type="radio" value="2"> 2
<input type="radio" value="3"> 3
</form>
JS:
<script>
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
})
</script>
To add jQuery to your project - simply insert
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
inside your <head> </head> tag.
UPDATE:
To keep it after page refreshes you should modify your code to this:
<form>
<input type="radio" value="1" id="radio1"> 1
<input type="radio" value="2" id="radio2"> 2
<input type="radio" value="3" id="radio3"> 3
</form>
<script>
$('#'+localStorage.selected).trigger('click');
$('#'+localStorage.selected).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
localStorage.setItem('selected', $(this).attr('id'));
})
</script>
I think all the answers are right and accurate to your question above but according to me you would find this answer more useful and understandable if you are newbie
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function myFunction1() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction2() {
document.getElementById("radio1").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction3() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio1").disabled = true;
}
</script>
</head>
<body>
<div class="block">
<input onclick="myFunction1();" type="radio" id="radio1" value="Radio1" /><label>Radio1</label>
<input onclick="myFunction2();" type="radio" id="radio2" value="Radio2" /><label>Radio2</label>
<input onclick="myFunction3();" type="radio" id="radio3" value="radio3" /><label>radio3</label>
</div>
</body>
</html>
It's a working example according to your need. Cheers :)

display the value of all selected radio buttons on a form

I have multiple radio buttons generated in a php loop which looks something like this
while(){
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team1'].' " onclick="return disp()""><span>'.$team1.'</span>
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team2'].' "onclick="return disp()""><span>'.$team2.'</span>
<input type="radio" name="picks'.$x.'" value="draw" onclick="return disp()">
}
What I want to do
Display all selected radio buttons in a div on the bottom of page
My Code
var elmnts = document.getElementById("makePicksForm").elements
var lngth = document.getElementById("makePicksForm").length;
var div = document.getElementById("dispPicks");
for (var x = 0; x < lngth; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML = elmnts[x].value;
}
}
My Problem
Only the value of first selected radio button is displayed in div, other radio buttons are ignored
My Question
Any idea how I can modify my javascript to display the values of ALL selected radio buttons?
Since you've tagged your question with jQuery, here is a jQuery solution. Run the snippet to see it work:
$(document).ready(function () {
$(':radio').change(function (e) {
//clear the div
$('#dispPicks').html('');
//update the div
$(':radio:checked').each(function (ind, ele) {
$('#dispPicks').append($(ele).val() + '<br/>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="foo" value="foo1" />
<input type="radio" name="foo" value="foo2" />
<input type="radio" name="foo" value="foo3" />
<br/>
<input type="radio" name="bar" value="bar1" />
<input type="radio" name="bar" value="bar2" />
<input type="radio" name="bar" value="bar3" />
<br/>
<input type="radio" name="wow" value="wow1" />
<input type="radio" name="wow" value="wow2" />
<input type="radio" name="wow" value="wow3" />
<div id="dispPicks"></div>
You're using lngth in your for loop, but that's defined by getting an element by ID which should only be 1 element. Your loop will only run once that way...
Assuming the element with ID makePicksForm contains all your radio buttons, you need to get the length of the elements:
var elmnts = document.getElementById("makePicksForm").elements;
var div = document.getElementById("dispPicks");
for (var x = 0; x < elmnts.length; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML += elmnts[x].value;
}
}
Also, you need to add the value to the innerHTML property, using +=
as a side note: your PHP loop is creating duplicate ID's, which will result in failures in your javascript code if you need to reference the elements...
Another jQuery-Fiddle
<input type="radio" id="bob" name="boys" value="Bob"><label for="bob">Bob</label><br>
<input type="radio" id="jim" name="boys" value="Jim"><label for="jim">Jim</label><br>
<input type="radio" id="pete" name="boys" value="Pete"><label for="pete">Pete</label><br>
<input type="radio" id="mary" name="girls" value="Mary"><label for="mary">Mary</label><br>
<input type="radio" id="jane" name="girls" value="Jane"><label for="jane">Jane</label><br>
<input type="radio" id="susan" name="girls" value="Susan"><label for="susan">Susan</label>
<h3><span id="boy">?</span> and <span id="girl">?</span></h3>
$("input[name=boys]").click(function () {
$("#boy").text($(this).val());
});
$("input[name=girls]").click(function () {
$("#girl").text($(this).val());
});

textbox.value not working in javascript

The following is a simple javascript code to set a value into a textbox. But, it doesn't seem to work. I am not able to find the flaw. Also, the javascript is working only in IE and not in Chrome/Firefox. How do I get out of this trouble?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function reportValue()
{
var form = document.getElementById("billgen");
var radioArray = form["time"];
var months;
for(var i=0;i<radioArray.length;i++)
{
if(radioArray[i].checked)
{
months = radioArray[i].value;
break;
}
}
if(months == "1")
{
e=31*100;
form["total"].value = e;
//document.getElementById("total").value = e; => not working as well
return true;
}
else{
alert("Are you sure the instructor is " + months + "?\nYou may be underestimating the instructor!");
return false;
}
}
</script>
</head>
<body bgcolor="white">
<fieldset>
<legend>Bill Generation</legend>
<form id="billgen" method="post">
<label><input type="radio" name="time" value="1" checked /> 1 Month </label>
<label><input type="radio" name="time" value="3" /> 3 Month </label>
<label><input type="radio" name="time" value="6" /> 6 Month </label>
<label><input type="radio" name="time" value="12" /> 1 Year </label>
<input type="submit" value="submit" onclick="reportValue();" />
<p>
<input type="text" id="total" name="total" />
</p>
</form>
</fieldset>
</body>
</html>
Clicing on a <input type="submit"/> causes the page to reload, so instead of "submit", either use the <button> element or use an <input type="button"/>.
Here is your code with getElementById( instead of getElementById[: JSFiddle and it works.
Just move your code to the end of your html, just before the </body> and it should work, I think the problem is that you are asigning the form to a variable before the form even exists.

Print values of selected radio buttons and check-boxes and exclude the submit button

In the script below, how do I get the values of only radio buttons and checkboxes that have been selected and not all (provided a radio button and checkbox were selected).
Right now it gives me the values of all, whether selected or not, and also the submit button (which i dont need).
How do i do this? There'll be more checkboxes and radio buttons, i've used only 2 sets for this question.
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
str += elem[i].value+"<br>";
}
document.getElementById('lblValues').innerHTML = str;
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Add the following test:
if(elem[i].checked)
str += elem[i].value+"<br>";
Also, if you use jQuery, the whole script is even simpler:
function DisplayFormValues(){
$("input:checkbox:checked").add("input:radio:checked")
.each(function(){
$("div#lblValues").append(this.value + "<br>");
});
}

Categories