getting selected value of radio button in case of action - javascript

Hi here is the codes bellow, I've tried many things but I couldnt get value of selected radio button.As you can see I need to get that value for diffrent situations.
<div style="display: inline-block">
<div>
Log Out<span> Welcome </span>YS User 1 noName </div>
<br />
<br />
<br />
<br />
<input type="button" onclick="submitCreate();" value="New Survey" /><br />
<input type="button" onclick="submitEdit();" value="Edit Survey" /><br />
<input type="button" onclick="submitDelete();" value="Delete Survey" /><br />
<input type="button" onclick="submitPreview();" value="Preview Survey" />
</div>
<div style="display: inline-block">
<div>
<table class="MyTable"><thead><tr class="columnHead"><th scope="col"></th><th scope="col">CreatedBy</th><th scope="col">Created Date</th><th scope="col">Is Running</th></tr></thead><tbody><tr><td> <input name="selected" id="1"
type="radio" value="1" /></td><td>1</td><td>12/12/2011 3:43:57 PM</td><td>False</td></tr><tr class="altRow"><td> <input name="selected" id="2"
type="radio" value="2" /></td><td>1</td><td>12/13/2011 4:42:37 PM</td><td>False</td></tr><tr><td> <input name="selected" id="3"
type="radio" value="3" /></td><td>1</td><td>12/13/2011 6:27:38 PM</td><td>False</td></tr></tbody></table>
</div>
</div>
</body>
</html>
<script type="text/javascript">
// var value = $$('input[name=selected]:checked')[0].get('value');
// var selectFoo;
// $$('input[name=selected]').each(function (el) {
// if (el.checked == true) {
// selectFoo = el.value;
// }
// });
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 "";
};
function submitCreate() {
var adress = "/User/CreateSurvey/";
document.location = adress;
};
function submitEdit() {
var adress = "/Den/Index/" + getCheckedValue('selected');
document.location = adress;
};
function submitDelete() {
var adress = "/User/DeleteSurvey/" + getCheckedValue('selected');
document.location = adress;
};
function submitPreview() {
var adress = "/User/PreviewSurvey/" + getCheckedValue('selected');
document.location = adress;
};
</script>

You can use document.getElementsByName(<button_name>) or document.getElementsByTagName("input") to get an array of input elements. Loop through those elements to check which is checked.
Here is an example of how to get the value of the checked button from a set of radio buttons with the name "selected":
<html>
<head>
<script type="text/javascript">
function get_radio_value() {
var inputs = document.getElementsByName("selected");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value;
}
}
}
function onSubmit() {
var id = get_radio_value();
alert("selected input is: " + id);
}
</script>
</head>
<body>
<form onsubmit="onSubmit();">
<input name="selected" value="1" type="radio"/>1<br/>
<input name="selected" value="2" type="radio"/>2<br/>
<input name="selected" value="3" type="radio"/>3<br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

I choose let number of code for a required function. The one worked for me is given below from api.jquery.com. Hope this helps others.
HTML
<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>
JavaScript
var selectedOption = $("input:radio[name=option]:checked").val()
The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2

Related

input a button value on corresponding textbox that is on focus

I am trying to create a touchscreen calculator like where the button value will be placed on the textbox after i set it on a focus by clicking but it appears on all the textboxes.I tried to use the code
if ($(impo).is(":focus")) {
but it doesnt work. Please see my snippet
Thanks in advance!
var impo = document.getElementById("imp_text");
var tess = document.getElementById("tess_text");
var FKeyPad = document.Keypad;
var Accumulate = 0;
var FlagNewNum = false;
var PendingOp = "";
document.getElementById('tess').onclick = function() {
document.getElementById('tess_text').focus();
}
document.getElementById('imp').onclick = function() {
document.getElementById('imp_text').focus();
}
function NumPressed(Num) {
if (impo) {
if (FlagNewNum) {
FKeyPad.ReadOut.value = Num;
FlagNewNum = false;
} else {
if (FKeyPad.ReadOut.value == " ")
FKeyPad.ReadOut.value = Num;
else
FKeyPad.ReadOut.value += Num;
}
}
if (tess) {
if (FlagNewNum) {
FKeyPad.readtess.value = Num;
FlagNewNum = false;
} else {
if (FKeyPad.readtess.value == " ")
FKeyPad.readtess.value = Num;
else
FKeyPad.readtess.value += Num;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html lang="en">
<head>
</head>
<body>
<form name="Keypad" action="">
<input type="button" value="Imp" id="imp" /> Importo :
<input name="ReadOut" id="imp_text" type="Text" value=" "> <br>
<input type="button" value="Tes" id="tess" /> Card Tess :
<input name="readtess" id="tess_text" type="Text" value=" ">
<br>
<input type="button" value=" 1" onclick="NumPressed(1)" />
<input type="button" value=" 2" onclick="NumPressed(2)" />
<input type="button" value=" 3" onclick="NumPressed(3)" /> <br>
</form>
</body>
</html>
if (impo) and if (tess) just tests whether the element exists, which they do, so the value gets written to both of them because they both exist. In a desktop environment, you can't do what you're asking - you can give a textbox the focus, but once the user clicks on one of the buttons in order to select that number, the textbox no longer has the focus (because the button has it).
You need a separate way to maintain which textbox is currently selected, something like the snippet below. It will update the currently "selected" element both on the click of the Imp/Tes buttons and whenever either of the textbox gains focus (e.g. by mouse click or touch).
var impo = document.getElementById("imp_text");
var tess = document.getElementById("tess_text");
var current_input = impo;
impo.onfocus = function() {
current_input = impo;
}
tess.onfocus = function() {
current_input = tess;
}
document.getElementById('tess').onclick = function() {
current_input = tess;
tess.focus();
}
document.getElementById('imp').onclick = function() {
current_input = impo;
impo.focus();
}
function NumPressed(Num) {
current_input.value += Num;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html lang="en">
<head>
</head>
<body>
<form name="Keypad" action="">
<input type="button" value="Imp" id="imp" /> Importo :
<input name="ReadOut" id="imp_text" type="Text" value=""> <br>
<input type="button" value="Tes" id="tess" /> Card Tess :
<input name="readtess" id="tess_text" type="Text" value="">
<br>
<br>
<input type="button" value="1" onclick="NumPressed(this.value)" />
<input type="button" value="2" onclick="NumPressed(this.value)" />
<input type="button" value="3" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="4" onclick="NumPressed(this.value)" />
<input type="button" value="5" onclick="NumPressed(this.value)" />
<input type="button" value="6" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="7" onclick="NumPressed(this.value)" />
<input type="button" value="8" onclick="NumPressed(this.value)" />
<input type="button" value="9" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="0" onclick="NumPressed(this.value)" /> <br>
</form>
</body>
</html>

How i can Do dynamic checkboxes for java jsp?

i need to do six checkboxes for one image , and this image need to change if one or more checkboxes is cheked , how i can do it? please help me , i attach my code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<img src="img/fotodiente/1.jpg" width="78" height="107" alt="1" id="diente1" onclick="changeImage1()"/>
<form name="form1" onsubmit="checkBoxValidation()">
<p><input type="checkbox" name="chbdiente1" value="1"/>Vestibular</p>
<p><input type="checkbox" name="chbdiente1" value="2"/>Mesial</p>
<p><input type="checkbox" name="chbdiente1" value="3"/>Oclusal</p>
<p><input type="checkbox" name="chbdiente1" value="4"/>Distal</p>
<p><input type="checkbox" name="chbdiente1" value="5"/>Palatino</p>
<p><input type="checkbox" name="chbdiente1" value="6"/>Lingual</p>
<p><input type="submit" value="submit"/>
</form>
<%String chbdiente1[] = request.getParameterValues("chbdiente1");
if (chbdiente1 != null) {%>
<script>
function changeImage1() {
var image = document.getElementById('diente1');
image.src = "img/fotodiente/1.1.jpg";
}
;
</script>
<ul><%for (int i = 0; i < chbdiente1.length; i++) {%>
<li><%=chbdiente1[i]%></li><%}%>
</ul><%}%>
</body>
</html>
i have this code and send me the value of selected checkboxes , but the image not change. help please. thanks
If you want to change the image after click of checkboxes you need to call changeImage1() into onchange or onclick method of checkbox.
Example:
<script>
$('document').ready(function(){
$('input[type="checkbox"]').click(function(){
changeImage1();
});
});
function changeImage1() {
var image = document.getElementById('diente1');
image.src = "img/fotodiente/1.1.jpg";
}
</script>
function changeImage1() {
var image = document.getElementById('diente1');
var checkboxes = document.getElementById("form1");
var cont = 0;
try {
for (var x = 0; x < checkboxes.length; x++) {
if (checkboxes[x].checked) {
cont = cont + 1;
}
}
} catch (e) {
}
try {
if (cont > 0) {
image.src = "img/fotodiente/1.1.jpg";
d1 = 2;
array.push("Pieza 1");
var chb2 = document.getElementsByName("form1");
} else if (cont === 0) {
image.src = "img/fotodiente/1.jpg";
d1 = 1;
array.splice(1, 1);
}
} catch (e) {
}
}
;
<img src="img/fotodiente/1.jpg" class="item_thumb" width="78" height="107" alt="1" id="diente1" onclick="changeImage1()"/>
<form id="form1" method="post" action="">
<input type="checkbox" id="chbdiente1" value="1" onclick="changeImage1();" /><label>Vestibular</label>
<input type="checkbox" id="chbdiente1" value="2" onclick="changeImage1();" /><label>Mesial</label>
<input type="checkbox" id="chbdiente1" value="3" onclick="changeImage1();" /><label>Oclusal</label>
<input type="checkbox" id="chbdiente1" value="4" onclick="changeImage1();" /><label>Distal</label>
<input type="checkbox" id="chbdiente1" value="5" onclick="changeImage1();" /><label>Palatino</label>
<input type="checkbox" id="chbdiente1" value="6" onclick="changeImage1();" /><label>Lingual</label>
<input type="button" name="Submit" value="Contar" hidden="">
</form>
Well, this changes the image when there are 1 or more checkboxes clicked, if all the checkboxes are unchecked the image returns to the first one.
I hope also I can help others and thanks

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 random checkboxes using JQuery

I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.
I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.
I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.
I am using Jquery.
$(':checkbox:checked').length;
But i want to find the length of all the checkboxes and i want to check 10 random checkbox.
Are you looking for something like this?
http://jsfiddle.net/qXwD9/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
//Creating random numbers from an array
function getRandomArrayElements(arr, count) {
var randoms = [], clone = arr.slice(0);
for (var i = 0, index; i < count; ++i) {
index = Math.floor(Math.random() * clone.length);
randoms.push(clone[index]);
clone[index] = clone.pop();
}
return randoms;
}
//Dummy array
function createArray(c) {
var ar = [];
for (var i = 0; i < c; i++) {
ar.push(i);
}
return ar;
}
//check random checkboxes
function checkRandom(r, nodeList) {
for (var i = 0; i < r.length; i++) {
nodeList.get(r[i]).checked = true;
}
}
//console.log(getRandomArrayElements(a, 10));
$(function() {
var chkCount = 100;
//this can be changed
var numberOfChecked = 10;
//this can be changed
var docFrag = document.createElement("div");
for (var i = 0; i <= chkCount; i++) {
var chk = $("<input type='checkbox' />");
$(docFrag).append(chk);
}
$("#chkContainer").append(docFrag);
$("#btn").click(function(e) {
var chks = $('input[type=checkbox]');
chks.attr("checked", false);
var a = createArray(chkCount);
var r = getRandomArrayElements(a, numberOfChecked);
//console.log(r);
checkRandom(r, chks);
});
});
</script>
</head>
<body>
<div id="chkContainer"></div>
<div>
<input type="button" id="btn" value="click" />
</div>
</body>
How about this:
Working example: http://jsfiddle.net/MxGPR/23/
HTML:
<button>Press me</button>
<br/><br/>
<div class="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
JAVASCRIPT (JQuery required):
$("button").click(function() {
// How many to be checked?
var must_check = 10;
// Count checkboxes
var checkboxes = $(".checkboxes input").size();
// Check random checkboxes until "must_check" limit reached
while ($(".checkboxes input:checked").size() < must_check) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * checkboxes) + 1;
// Check it
$(".checkboxes input:nth-child(" + random_checkbox + ")").prop("checked", true);
}
});

How to check to make sure a radio button is selected

I have a form that I need to figure out the code on how to make sure a radio button is selected
Here is the form
<body>
<div id="content">
<p>Enter the values below and click "Calculate".</p>
<label for="length">Length:</label>
<input type="text" id="length" /><br />
<label for="width">Width:</label>
<input type="text" id="width" /><br />
<label for="answer">Answer:</label>
<input type="text" id="Answer" disabled="disabled" /><br />
<input type="radio" name="Area" value="Area" check="checked"/>Area<br />
<input type="radio" name="Parimeter" value="Parimeter" />Parimeter<br />
<label> </label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</body>
</html>
here is the code
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var length = parseFloat( $("length").value );
var width = parseFloat( $("width").value );
// $("area").value = "";
if (isNaN(length) || length <= 0) {
alert("Length must be a valid number\nand greater than zero.");
} else if(isNaN(width) || width <= 0) {
alert("Width must be a valid number\nand greater than zero.");
}
} else {
var area = width * length;
var perimeter = 2 * width + 2 * length;
$("area").value = area.toFixed(2);
$("perimeter").value = perimeter.toFixed(2);
}
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("length").focus();
}
Here are some links that may help you finish your homework:
http://www.w3schools.com/html/html_forms.asp
http://www.w3schools.com/jquery/default.asp
http://jsfiddle.net

Categories