CheckBox and JavaScript code - javascript

I want to create javascript code that will save all checkbox that user clicked and when user click on button finish, code will show him what he chose.(Text in label )
Honestly I do not have an idea and need help.
Is that possible to achieve on this way :
<html>
<script>
function test()
{
if(document.getElementById("chk").checked)
{
// save in some variable nad print on the end.. That is my problem.. and i have no idea.
}
}
</script>
<body>
<input type="checkbox" id="chk">
<label>someTXT</label>
<input type="button" onclick="test();"></input>
</input>
</body>
</html>

Exmaple to return all checked checkboxes (if you have more than one):
test = function() {
var checkboxesIDs = '';
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if(inputs[i].checked == true) {
checkboxesIDs+= inputs[i].id +", ";
}
}
}
alert(checkboxesIDs);
}
and HTML:
<input type='checkbox' id='c1' />
<input type='checkbox' id='c2' />
<input type='checkbox' id='c3' />
<input type='checkbox' id='c4' />
<input type='button' onclick="test();" value="Test" />
DEMO: http://jsfiddle.net/47EdX/

Here's a short example that figure out how to get this:
JS Function to check through checkboxes:
function checkAll(bx) {
var cbs = document.getElementsByTagName('input');
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}
HTML
<input type="checkbox" onclick="checkAll(this)">
You have to complement with some Array or object that will stores some value to push into the server.
Hope this helps.

$("input[type='button']").click(function(){
$cb = $("input[type='checkbox']").prop("checked");
$cb.each(function(){
alert($(this).attr("id"));
});
});
That's the way to access ALL checkboxes on your page and popup each id. You can also show any other attribute of your checkboxes like value or name.

Related

Get value of checkbox and display it in specific format

I am trying to get the checked value in checkbox and display it in some specific format using javascript but somehow I dont know how to do it
I have tried html and javascript and I dont know ajax or jquery so I am trying javascript only
function Hobby()
{
var checkedValue = null;
var inputElements = document.getElementsByClass('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value
document.getElementById("hobbies_value").innerHTML = inputElements;
break;
}
}
}
Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
<input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports
<input type="button" value="student_submit" onclick="Hobby()"><br/>
If checked values are dancing and painting
then output should be
Hobby:#dancing#painting
and I dont want to display it as alert box instead I want to display it on same page
You need to concatenate the values and display them outside the loop. Something like this:
function Hobby()
{
var checkedValue = "";
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue += "#"+inputElements[i].value
}
}
document.getElementById("hobbies_value").innerHTML = checkedValue;
}
Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
<input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports
<input type="button" value="student_submit" onclick="Hobby()"><br/>
Javascript code is
<div id="hobbies_value"></div>

Block form submit if no one checkbox checked

I need help because confused how to block form submit if no one checkbox checked.
var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');
$form.on('submit', function(e) {
$.each($checkbox, function(index, value) {
if (!$(value).is(':checked')) {
alert('Opps! You not select friends.');
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send-invite-form">
<input type="checkbox" class="invitation-friends" value="875" />
<input type="checkbox" class="invitation-friends" value="394" />
<button type="submit">Send</submit>
</form>
The code check every checkbox. I don't want it. I want if one checkbox checked, the form can submit. If no one checked, bail submit.
Please help.
There is a way to do this that is much simpler than what you are doing. There's no need to loop. Just used the :checked pseudo-class selector to get a set of nodes that are checked and check the .length of the resulting set of nodes. If the .length is 0, no checkboxes have been checked.
$( '#send-invite-form' ).on('submit', function(e) {
if($( 'input[class^="invitation-friends"]:checked' ).length === 0) {
alert( 'Oops! You not select friends.' );
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send-invite-form">
<input type="checkbox" class="invitation-friends" value="875" />
<input type="checkbox" class="invitation-friends" value="394" />
<button type="submit">Send</submit>
</form>
try this, no need to explain i think:
var found = false;
$.each( $checkbox, function(index, value) {
if( $(this).is(':checked') ) {
found = true;
}
});
if(!found){
alert( 'Opps! You not select friends.' );
e.preventDefault();
}
The first problem comes from this line :
if ( !$(value).is(':checked')) {
Should be :
if ( !$(this).is(':checked')) {
Since value contains the value of the selected checkbox not the object, so $(value) will not work.
Then if you want to submit with at least one checkbox you could check the length of checked input's like :
if( $('input.invitation-friends:checked').length == 0 )
{
return false;
}
Hope this helps.
var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');
$form.on('submit', function(e) {
if( $('input.invitation-friends:checked').length == 0 )
{
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send-invite-form">
<input type="checkbox" class="invitation-friends" value="875" />
<input type="checkbox" class="invitation-friends" value="394" />
<button type="submit">Send</submit>
</form>
Since submit button is controlling form submit, I am controlling its enable/disable status based on checkbox click
window.onload = checkBoxEventAndOnSubmitFunctionality();
function checkBoxEventAndOnSubmitFunctionality() {
let checkBoxes = document.getElementsByClassName('invitation-friends');
let checkBoxChecked = 0;
for(i=0;i<checkBoxes.length;i++) {
checkBoxes[i].onclick = function(e) {
if(e.path[0].checked) checkBoxChecked += 1;
else checkBoxChecked -= 1;
}
}
document.getElementById("send-invite-form").onsubmit = function(e) {
if(checkBoxChecked !=0) {
alert("can submit");
document.getElementById("send-invite-form").submit();
}
else {
alert("can NOT submit");
e.preventDefault();
}
}
}
<form id="send-invite-form" onsubmit="checkForCheckBoxes" method="POST">
<input type="checkbox" class="invitation-friends" value="875" />
<input type="checkbox" class="invitation-friends" value="394" />
<button type="submit" id="submitButton">Send</button>
</form>

How to record the select order of a number of checkboxs?

Look at this HTML example:
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
And the resulting output from it:
I hope to send the checked checkbox to the servlet, but i also want to get the order user selected these checkbox.
For example,user A do stuff like : select Cheese,select Butter, select Milk->then Cheese,Butter,Milk will be sent to servlet with this order.
If user B do stuff like : select Cheese,select Butter, deselect Butter, select Milk , select Butter->then Cheese,Milk,Butter will be sent to servlet with this order.
Appreciate.
Check the fiddle for the checkbox order here
I used the following JS Code
checkedOrder = []
inputList = document.getElementsByTagName('input')
for(var i=0;i<inputList.length;i++) {
if(inputList[i].type === 'checkbox') {
inputList[i].onclick = function() {
if (this.checked) {
checkedOrder.push(this.value)
} else {
checkedOrder.splice(checkedOrder.indexOf(this.value),1)
}
console.log(checkedOrder)
}
}
}
​
Make a global variable to track the order:
var selectOrder = 0;
Bind this function to your onclick event in your inputs:
function onClickHandler() {
var senderId = this.id;
selectOrder = selectOrder + 1;
document.getElementById(senderId).setAttribute('data-order', selectOrder);
}
That will set a data-* (custom) attribute on each one with the order they were checked. So, when you submit your form, you can grab all of the checkboxes and get the order with .getAttribute('data-order'); Don't forget to reset your selectOrder = 0 when you submit so it will reorder them on the next time through.
Try this code.This works better
<html>
<head>
<title>My Page</title>
<script type="text/javascript">
var arr=new Array();
function fnc(myid)
{
if(document.getElementById(myid).checked == true)
{
arr.push(document.getElementById(myid).value);
alert(arr);
}
else
{
var item1=document.getElementById(myid).value;
for(i=0;i<2;i++)
{
if(arr[i]=item1)
{
found=i;
arr.splice(found,1);
}
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk" id="Milk" onchange="fnc(this.id)"> Milk<br>
<input type="checkbox" name="option2" value="Butter" id="Butter" onchange="fnc(this.id)"> Butter<br>
<input type="checkbox" name="option3" value="Cheese" id="Cheese" onchange="fnc(this.id)"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
Here, give this a try.
It maintains an array of all of the options' values, along with the order in which they were clicked. It handles the case where items are already checked when the page loads, by arbitrarily assigning them an increasing index for the order they were clicked in.
It handles items being unselected, it also can provide you with a little more info as a happy side-effect of the way I've done it. You can for instance get back values of 2, 3, 4 for selection order. If I load the page, then select Milk then cheese before unselecting then reselecting Butter, I get back the values 2,3,4 2,4,3 - I can straight away tell that the last selection made was Butter, and that it had previously been the first item selected. Likely useless, but an interesting consequence to me all the same.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
#myDiv
{
border: 1px solid black;
display: inline-block;
}
</style>
<script>
window.addEventListener('load', mInit, false);
function mInit()
{
var i, inputList = document.getElementsByTagName('input'), n = inputList.length;
var cbCount = 0;
var curOrder = 0;
for (i=0; i<n; i++)
{
if (inputList[i].type == 'checkbox')
{
cbCount++;
var cur = inputList[i];
cur.addEventListener('change', onCbChange, false);
var mObj = {val:cur.value, selOrder:0};
if (cur.checked)
{
mObj.selOrder = ++curOrder;
}
availOptions.push( mObj );
}
}
}
var availOptions = []; // an array to hold objects - { val, selOrder }
function getItem(value)
{
var i, n = availOptions.length;
for (i=0; i<n; i++)
{
if (availOptions[i].val == value)
return availOptions[i];
}
return null;
}
// just clear it's selOrder member
function mUnselect(value)
{
var Item = getItem(value);
Item.selOrder = 0;
}
// iterate through the list, find the highest value of selOrder, increment it and set this item's selOrder to that
function mSelect(value)
{
var i, n = availOptions.length;
var curMax=0;
for (i=0; i<n; i++)
{
if (availOptions[i].selOrder > curMax)
curMax = availOptions[i].selOrder;
}
curMax++;
getItem(value).selOrder = curMax;
}
function onCbChange()
{
if (this.checked)
mSelect(this.value);
else
mUnselect(this.value);
alert(this.value + ': ' + this.checked);
}
function showCurState()
{
var i, n=availOptions.length;
var mStr = '';
for (i=0; i<n; i++)
mStr += availOptions[i].val + ", selOrder: " + availOptions[i].selOrder + "\n"
alert(mStr);
}
</script>
</head>
<body>
<div id='myDiv' align="left">
<br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
<input type='button' onclick='showCurState();' value='Show state'/>
</div>
</body>
</html>

How to confirm a radio button selection with an alert box

So i have this code:
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n');
}
function formfocus() {
document.getElementById('textbox').focus();
}
window.onload = formfocus;
var option;
</script>
</head>
<body>
Your name:
<input type="text" name="FirstName" id="textbox" <br><br/>
Your Address:
<input type="text" name="address" id="location" <br></br><br></br>
Choose your location:
<form name="Radio" id="destination" action="">
Bristol:
<input type="radio" name="selection" value="bristol" onClick="option=0">
London:
<input type="radio" name="selection" value="london" onClick="option=1">
Birmingham:
<input type="radio" name="selection" value="birmingham" onClick="option=2" />
</form>
<br></br> Click:
<input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br>
</body>
</html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);

nextsibiling doesn't work

this is a sample code of what I am doing. unfortunately the alert(nextElem.value) returns "undefined" when I click the second checkbox to get the href of the link after it. do you have any idea how to fix it?
<HTML>
<HEAD>
<TITLE>Checkbox Inspector</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function validate()
{
for (i = 0; i <(document.f1.checkThis.length) ; i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem.href);
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="f1">
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate()">Check here<BR>
click here
</FORM>
</BODY>
</HTML>
Get the link's href with jQuery
http://jsfiddle.net/mplungjan/H9Raz/ :
$('form input:checkbox').click(function () {
alert($(this).nextAll('a').attr("href"));
});
Because of the BRs we need the nextAll, surprisingly since I was using the next selector with an "a"
See here why it did not work: Cleanest way to get the next sibling in jQuery
Get the link's href with forms access and usage of ID - no jQuery
http://jsfiddle.net/mplungjan/fKE3v/
window.onload=function() {
var chks = document.getElementsByName('checkThis');
for (var i=0;i<chks.length;i++) {
chks[i].onclick=function() {
var id = this.id;
var linkId="link_"+id.split("_")[1]
alert(document.getElementById(linkId).href)
}
}
}
<form>
<div>
<input type="checkbox" name="checkThis" id="chk_1" value="http://www.google.com" />Check here<br/>
click here<br>
<input type="checkbox" name="checkThis" id="chk_2" value="http://www.bing.com" />Check here<br/>
click here
</div>
</form>
Forms access to get the next checkbox
<INPUT TYPE="checkbox" NAME="checkThis" value="http://www.google.com" onClick="validate(this.form)">Check here<BR>
<INPUT TYPE="checkbox" NAME="checkThis" onClick="validate(this.form)">Check here2<BR>
function validate(theForm) {
var chk = theForm.checkThis
for (i = 0; i <chk.length) ; i++) {
if (chk[i].checked) {
var nextElem = chk[i+1];
if (nextElem) alert(nextElem.value);
}
}
}
Your problem is that nextElem is the text node immediately after your checkbox, not the next checkbox; text nodes don't have value attributes. For example, try this:
function validate() {
for (i = 0; i < (document.f1.checkThis.length); i++) {
if (document.f1.checkThis[i].checked) {
var elem = document.f1.checkThis[i];
var nextElem = elem.nextSibling;
alert(nextElem);
alert(nextElem.value);
}
}
}
Or, for your convenience:
http://jsfiddle.net/ambiguous/sUzBL/1/

Categories