I'm trying to populate the multiple selected choice from checklist into PHP. However, only the "Reading" choice is populating in the new window and not the other choices that I have selected. For example, I have selected "Painting & Travelling" but after I clicked submit, the value that showing is "Reading".Kindly advise how to fix this. Thanks in advance. I'm new to web development.
Javascript
function validate(){
var x3=document.getElementById("hobbies");
if (x3.value == "")
{
alert("No blank values allowed")
return false;
}
else
{
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+x3.value+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
}
Form
<form onsubmit="return validate()" method= "get">
<label>Hobbies : </label><br><br>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Reading"/>Reading<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Painting"/>Painting<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling"/>Traveling<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Baking"/>Baking<br/><br/>
</div>
</form>
Please try the following:
<form onsubmit="return validate()" method= "get">
<label>Hobbies : </label><br><br>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Reading" />Reading<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Painting" />Painting<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling" />Traveling<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Baking" />Baking<br/><br/>
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function validate() {
var x3 = document.getElementsByName("hobbies[]");
var selectedVals = "";
for(var i = 0; i < x3.length; i++) {
if((x3[i].checked) && (x3[i].value != '')) {
selectedVals += (selectedVals == '')?x3[i].value:','+x3[i].value;
}
}
if(selectedVals == "") {
alert("No blank values allowed")
return false;
}
else {
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+selectedVals+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
}
}
</script>
Hope this may help.
You need to fetch the values of checkbox one by one in loop:
<form onsubmit="return validate()" method= "get" name="demoForm">
<label>Hobbies : </label><br><br>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Reading"/>Reading<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Painting"/>Painting<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling"/>Traveling<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Baking"/>Baking<br/><br/>
<button type="submit">click</button>
</form>
<script type="text/javascript">
function validate(){
var hobby = document.forms['demoForm'].elements[ 'hobbies[]' ];
var len = hobby.length;
var values="";
for (var i=0;i<len;i++)
{
if (hobby[i].checked)
{
values += hobby[i].value+",";
}
}
values = values.replace(/,\s*$/, "");
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+values+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0 ');
}
</script>
You can also fetch the values using $_GET['hobbies']
You set all elements with the same id
id is unique attribute so whatever you select the javascript will always return the first element value on x3 you can do this if you only want to submit selected checkboxes
<script type="text/javascript">
function validate() {
var x3 = document.getElementsByName("hobbies[]");
var values= "";
for(var i = 0; i < x3.length; i++) {
if(x3[i].checked) {
if(x3[i].value==''){
alert('No blank values allowed');
return false;
}
else{
values+= x3[i].value+',';
}
}
}
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+values+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
}
}
Related
Example code:
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
On form submission the URL should look like:
http://some-website.tld/action?anythingOne=one,three&otherThingTwo=Fifty
What I am observing now is,
http://some-website.tld/action?anythingOne=one&anythingOne=three&otherThingTwo=Fifty
The serialize() or serializeArray() is not working in this case. Any ideas?
You could grab the result of .serializeArray and transform it into the desired format:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serializeArray();
var dataByKey = data
.reduce((result, entry) => {
var name = entry.name.replace(/\[\]$/, '');
(result[name] || (result[name] = [])).push(entry.value);
return result;
}, {});
Object.keys(dataByKey)
.forEach((key, _) => dataByKey[key] = dataByKey[key].join(','));
console.log(dataByKey);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<fieldset>
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
</fieldset>
<fieldset>
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
</fieldset>
<input type="submit" />
</form>
If you want, you can also use pure javascript without jQuery to get all the checked checkboxes' value, http://jsfiddle.net/jx76dpkh/1/
<form id="myForm" method="get">
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
<input type="submit" />
</form>
JS:
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
let checkboxes = Array.from(myForm.querySelectorAll('input[type="checkbox"]:checked');// build the array like element list to an array
let anythingOne = checkboxes.filter( box => box.name === 'anythingOne[]').map(item => item.value);
let otherThingTwo = checkboxes.filter( box => box.name === 'otherThingTwo[]').map(item => item.value);
});
In case, you are allowed to change html, here is a solution using hidden fields.
function updateChecks() {
$.each(['anythingOne', 'otherThingTwo'], function(i, field) {
var values = $('input[type=checkbox][data-for=' + field + ']:checked').map(function() {
return this.value;
}).get().join(',');
$('input[type=hidden][name=' + field + ']').val(values);
});
}
$(function() {
$('form').on('submit', function(e) {
updateChecks();
});
updateChecks();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="hidden" name="anythingOne" value='' />
<input type="hidden" name="otherThingTwo" value='' />
<input type="checkbox" data-for="anythingOne" value='one' checked='' />
<input type="checkbox" data-for="anythingOne" value='two' />
<input type="checkbox" data-for="anythingOne" value='three' checked='' />
<input type="checkbox" data-for="otherThingTwo" value='Forty' />
<input type="checkbox" data-for="otherThingTwo" value='Fifty' checked='' />
</form>
You could get query string parameters using by serializeArray() method. Then use reduce() to group parameter values by name, and map() to get array of key-value pairs. Then it is possible to concatenate the pairs separated by & using join() method. For example the following snippet creates a target URL using actual value of the form action (current URL by default) and values of checked checkboxes:
$('form').submit(function() {
var queryString = $(this).serializeArray()
.reduce(function(transformed, current) {
var existing = transformed.find(function(param) {
return param.name === current.name;
});
if (existing)
existing.value += (',' + current.value);
else
transformed.push(current);
return transformed;
}, [])
.map(function(param) {
return param.name + '=' + param.value;
})
.join('&');
var action = $(this).prop('action');
var delimiter = (~action.indexOf('?')) ? '&' : '?';
$(this).prop('action', action + delimiter + queryString);
// Only for display result. Remove on real page.
var url = $(this).prop('action');
console.log(url);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="GET">
<input type="checkbox" name="anythingOne" value='one'>
<input type="checkbox" name="anythingOne" value='two'>
<input type="checkbox" name="anythingOne" value='three'>
<input type="checkbox" name="otherThingTwo" value='Forty'>
<input type="checkbox" name="otherThingTwo" value='Fifty'>
<button type="submit">Show target URL</button>
</form>
The latest 3 lines are used only to prevent the form sending and display resulted URL.
Also it is possible to solve the question using only serialize() mathod and regular expressions, but it requires lookbehind assertion support in browsers.
You can collect all the checked boxer and join the different parts of the strings.This may not be the most neat or efficient solution, but it works. I used a button to trigger the concatenation. See my comments within the code.
$(document).ready(function(){
$("button").click(function(){
/* concatenate anythingOne form*/
//collect anythingOne input
var joined_serialized = []
var anythingOne = [];
$.each($("input[name='anythingOne[]']:checked"), function(){
anythingOne.push($(this).val());
});
//join otherThingTwo input
var anythingOne_serialized = "";
if(anythingOne.length > 0){ //only collect if checked
anythingOne_serialized = "anythingOne=" + anythingOne.join(",");
joined_serialized.push(anythingOne_serialized)
}
/* concatenate otherThingTwo form*/
//collect otherThingTwo input
var otherThingTwo = []
$.each($("input[name='otherThingTwo[]']:checked"), function(){
otherThingTwo.push($(this).val());
});
//join otherThingTwo input
var otherThingTwo_serialized = "";
if(otherThingTwo.length > 0){ //only collect if checked
otherThingTwo_serialized = "otherThingTwo=" + otherThingTwo.join(",");
joined_serialized.push(otherThingTwo_serialized)
}
/*join different form names*/
var joined_serialized = joined_serialized.join("&")
if(joined_serialized.length == 1){ //remove last & if only one form is checked
joined_serialized = joined_serialized.slice(0, -1)
}
/*concatenated forms with website*/
var result = "http://some-website.tld/action?"+joined_serialized
console.log(result) //E.g. when Two, Three and Forty are checked: http://some-website.tld/action?anythingOne=two,three&otherThingTwo=Forty
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
<button>submit<button/>
my code is :
<input type="checkbox" name="area" id="area" value="0">Some Text1</input>
<input type="checkbox" name="area" id="area" value="80">Some Text2</input>
and javascript code is
function calc(){var textValue1 = document.getElementById('quantity').value;
var textValue2 = document.getElementById('area').value;
document.getElementById('cost').value = textValue1 * textValue2 ; }
but it isn't working.
Try this:
valueChange = function(item){
alert(item.value);
}
<form name="form1" method="post" action=" insert_data.php">
Delivery Location
<input onChange="valueChange(this)" type="checkbox" name="area" id="area" value="0">Inside city </input>
<input onChange="valueChange(this)" type="checkbox" name="area" id="area" value="80">Outside city </input>
</form>
Sample example by using JQuery...
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$( "#target" ).submit(function( event ) {
$('input[name="vehicle"]:checked').each(function() {
console.log(this.value);
});
return false;
});
});
</script>
</head>
<body>
<form id='target' action="/action_page.php">
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The problem is that id attributes should be unique. In your case you have 2 elements with id="area" which confuses the document.getElementById() method. You can use a selector query to achieve what you want. There's not need for additional libraries such as jQuery.
Here's a working example:
function calculate () {
var selected = document.querySelector('[name="area"]:checked')
if (!selected) {
alert('Please select a value')
return
}
var quantity = 5 // you can get this from a different place
alert('Final value: ' + selected.value * quantity)
}
document.getElementById('submit').addEventListener('click', calculate)
<form name="form1" method="post" action=" insert_data.php">
Delivery Location
<input type="checkbox" name="area" id="inside" value="0">Inside city </input>
<input type="checkbox" name="area" id="outside" value="80">Outside city </input>
<button id="submit">Calculate</button>
</form>
try the below JS code in console. you can use it as per the events u want
var checkedValue = null;
var inputElements = document.getElementsByName('area');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.
I have placed an onsubmit function onto a form which checks to see if certain checkboxes are checked.
The problem I am having is that I only require one checkbox from each column to be checked, there are 3 columns in total with around 6 different checkboxes in each column - every checkbox in a column shares the same ID (this is what makes it hard for me).
The below script works, but it requires all of the boxes in each column to be checked, how can I modify it to still submit only if one checkbox in each column is checked.
<script type="text/javascript">
window.onload = function() {
var form = document.getElementById('uwpqsffrom_731');
form.onsubmit = function() {
var no1 = 0, no2 = 0, no3 = 0;
var list;
list = document.getElementsByName('taxo[0][term][]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no1++;
}
}
list = document.getElementsByName('taxo[1][term][]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no2++;
}
}
list = document.getElementsByName('taxo[2][call]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no3++;
}
}
list = document.getElementsByName('taxo[2][term][]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no3++;
}
}
if ( no1 == 0 || no2 == 0 || no3 == 0 )
{
alert("Please select at least one option from each section");
return false;
}
}
}
</script>
HTML:
You can see that there are everal checkboxes with the same ID - I only require 1 of them to be checked for the form to submit.
<form id="uwpqsffrom_731" method="get" action="http://test.com/">
<div class="uform_title">Find Your Perfect Venue</div><input type="hidden" name="unonce" value="a92b348757"><input type="hidden" name="uformid" value="731"><input type="hidden" name="s" value="uwpsfsearchtrg">
<div class="uwpqsf_class tax-check-0 togglecheck">
<span class="taxolabel-0">Guests</span>
<input type="hidden" name="taxo[0][name]" value="number-of-guests">
<input type="hidden" name="taxo[0][opt]" value="1">
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="150-180">150-180</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="180-200">180-200</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="20-50">20-50</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="200-350">200-350</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="200-380">200-380</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="350-500">350-500</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="50-65">50-65</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="500-1000">500-1000</label>
<label><input type="checkbox" id="tchkb-0" name="taxo[0][term][]" value="65-150">65-150</label>
</div>
<div class="uwpqsf_class tax-check-1 togglecheck">
<span class="taxolabel-1">Event Type</span>
<input type="hidden" name="taxo[1][name]" value="event-type">
<input type="hidden" name="taxo[1][opt]" value="1">
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="awards-dinner">Awards Dinner</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="awards-dinner-dance">Awards Dinner Dance</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="barbat-mitzvah">Bar/Bat Mitzvah</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="cocktail-party">Cocktail Party</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="dinner">Dinner</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="dinner-dance">Dinner Dance</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="networking-event">Networking Event</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="party">Party</label>
<label><input type="checkbox" id="tchkb-1" name="taxo[1][term][]" value="vip-experience">VIP Experience</label>
</div>
<div class="uwpqsf_class tax-check-2 togglecheck">
<span class="taxolabel-2">Venue Preference</span>
<input type="hidden" name="taxo[2][name]" value="venue-locations">
<input type="hidden" name="taxo[2][opt]" value="">
<label><input type="checkbox" id="tchkb-2" name="taxo[2][call]" class="chktaxoall">All Venues</label>
<label><input type="checkbox" id="tchkb-2" name="taxo[2][term][]" value="london-dungeon">London</label>
<label><input type="checkbox" id="tchkb-2" name="taxo[2][term][]" value="madame-tussauds">New York</label>
<label><input type="checkbox" id="tchkb-2" name="taxo[2][term][]" value="sea-life">Russia</label>
<label><input type="checkbox" id="tchkb-2" name="taxo[2][term][]" value="stardome-4d">Spain</label>
</div>
<div class="uwpqsf_class uwpqsf_submit">
<input type="submit" id="uwpqsf_id_btn" value="Search" alt="[Submit]" class="usfbtn ">
</div>
</form>
Made some changes to your original javascript, but you should be able to just copy - paste my code over yours easily.
function test() {
var no1 = 0, no2 = 0, no3 = 0;
var list;
list = document.getElementsByName('taxo[0][term][]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no1++;
}
}
list = document.getElementsByName('taxo[1][term][]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no2++;
}
}
list = document.getElementsByName('taxo[2][call]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no3++;
}
}
list = document.getElementsByName('taxo[2][term][]');
for(i=0; i<list.length; i++)
{
if (list[i].checked)
{
no3++;
}
}
if ( no1 == 0 || no2 == 0 || no3 == 0 )
{
alert("Please select at least one option from each section");
return false;
}
}
Sorry it's a little sloppy, I don't really handle javascript well without jQuery, and there were some limitations due to your markup (didn't change that at all as you said it was all generated by a pluging.
Anyway, here is a jsfiddle of it as well
(note: had to do the for twice for the last column as the names we're different ...)
(note2: if you can also use jQuery, I can clean it up really nicely)
If you require only one of the checkboxes from each column to be selected I would recomend using radio-buttons. If you can't, just change it to if ( no1 !=1 && no2 != 1 && no3 != 1 )
how can I modify it to still submit only if one checkbox in each column is checked.
You should make all your checkbox to have common name. Then iterate the checkbox with name, use document.getElementsByName('name')
Your html should look something like this:
150-180
180-200
var chkBox = document.getElementsByName('taxo');
for (var i = 0; i < chkBox.length; i++){
if (chkBox.checked == true){
submitForm();
break;
}
}
function submitForm(){
//submit form
}
I have many server input checkboxes. I have given the first checkbox the id all. By default it will be checked. When the user checks other checkboxes, then checkbox with id all will be unchecked. And if all is checked other checkboxes will be unchecked. For this to happen i made the code but nothing is happening.
Here is what i have tried.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check()" checked/>ALL <br/>
<input type="checkbox" id="servers" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" id="servers" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" id="servers" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" id="servers" value="amp" name="server[]" onChange="check()" />AMP <br/>
</form>
function check(){
var all = document.getElementById("all"),
group = document.getElementById("servers");
if(all.checked == true){
group.checked == false;
}elseif(group.checked == true){
all.checked == false;
}
}
I wanted my code to work like THIS.
I dont want to use jQuery for some reasons. So i need my code to be in pure JS.
Any help will be appreciated.
You can't use the same ID on multiple elements.
Try this, notice how I placed the checkboxes in a div
Here it is working: http://jsfiddle.net/Sa2d3/
HTML:
<form>
<div id="checkboxes">
<input type="checkbox" id="all" value="all" name="all" onChange="check()" />ALL <br/>
<input type="checkbox" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" value="amp" name="server[]" onChange="check()" />AMP <br/>
</div>
</form>
JavaScript:
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// loop through all the inputs, skipping the first one
for (var i = 1, input; input = inputs[i++]; ) {
// Set each input's value to 'all'.
input.checked = el.checked;
}
}
// We need to check if all checkboxes have been checked
else {
var numChecked = 0;
for (var i = 1, input; input = inputs[i++]; ) {
if (input.checked) {
numChecked++;
}
}
// If all checkboxes have been checked, then check 'all' as well
inputs[0].checked = numChecked === inputs.length - 1;
}
}, false);
EDIT:
Based on your request in the comment here is the updated javascript:
http://jsfiddle.net/T5Pm7/
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// If 'all' is checked
if (el.checked) {
// Loop through the other inputs and removed the check
for (var i = 1, input; input = inputs[i++]; ) {
input.checked = false;
}
}
}
// If another has been clicked, remove the check from 'all'
else {
inputs[0].checked = false;
}
}, false);
You can only assign the same id to one element. What you want to do is give them a class="servers" and then use document.getElementsByClassName("servers"); in your JavaScript.
You cannot have same id for multiple HTML elements. You could do something like this to achieve what you are asking for.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check(this, 'a')" checked/>ALL <br/>
<input type="checkbox" id="servers1" value="xampp" name="server[]" onChange="check(this, 's')" />XAMPP <br/>
<input type="checkbox" id="servers2" value="wamp" name="server[]" onChange="check(this, 's')" />WAMP <br/>
<input type="checkbox" id="servers3" value="mamp" name="server[]" onChange="check(this, 's')" />MAMP <br/>
<input type="checkbox" id="servers4" value="amp" name="server[]" onChange="check(this, 's')" />AMP <br/>
</form>
<script>
function check(cb, type){
var all = document.getElementById("all");
if (type == "a" && cb.checked){
var els = document.getElementsByName("server[]");
for(var i = 0; i < els.length; ++i)
els[i].checked = false;
} else if( type == "s" && cb.checked) {
all.checked = false;
}
}
</script>
put this function
function jvcheck(id,Vale){
Checkboxesclass = '.group'+id;
$(Checkboxesclass).each(function() {
this.checked = Vale;
});
}
and then put this code in your main checkbox
jvcheck('group222',this.checked);
all checkbox with class group222 now checked .