I need to be able to set the onclick function without onclick being in the input tag. The below code works great, but the input tags are generated and I cannot add the onclick event to them. Jquery solution is fine too.
function setValue(){
var val="";
var frm = document.getElementById("form1");
var cbs = document.getElementById("form1")['amenities[]'];
for(var n=0;n<cbs.length;n++){
if(cbs[n].checked){
val+=cbs[n].value+",";
}
}
var temp = val.split(",");
temp.pop();
frm.textname.value=temp
}
<form id="form1">
<input type="checkbox" name="amenities[]" value="coffee" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="tea" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="beer" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="soda" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="orangejuice" onclick="setValue(this.value);">
<input type="text" name="textname">
</form>
Use the .map() function
$(".checkbox").change(function() {
$("#text").val( $('.checkbox:checked').map(function() { return this.value; }).get().join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input type="checkbox" class="checkbox" name="amenities[]" value="coffee" >
<input type="checkbox" class="checkbox" name="amenities[]" value="tea" >
<input type="checkbox" class="checkbox" name="amenities[]" value="beer" >
<input type="checkbox" class="checkbox" name="amenities[]" value="soda">
<input type="checkbox" class="checkbox" name="amenities[]" value="orangejuice" >
<input type="text" name="textname" id= "text">
</form>
//attach a change handler to the form.
//the change event bubbles up to the parent
var $form = $('#form1').on('change', function(){
//set the value of the textname
$form.find('[name="textname"]').val(
//get all the checked checkbox and map all their values to an array
$form.find(':checkbox:checked').map(function(){
//return the value for each checked element
return this.value;
}).get() //use get() to get a basic array, not a jQuery object
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input type="checkbox" name="amenities[]" value="coffee">
<input type="checkbox" name="amenities[]" value="tea">
<input type="checkbox" name="amenities[]" value="beer">
<input type="checkbox" name="amenities[]" value="soda">
<input type="checkbox" name="amenities[]" value="orangejuice">
<input type="text" name="textname">
</form>
you can try this:
$('input[type=checkbox]').change(function() {
//logic goes here
});
Plain JS:
var mForm = document.getElementById("form1");
mForm.addEventListener("click", function(event){
console.log("clicked", event.toElement); // do whatever you want with this element, add condition to sort checkboxes only
});
UPDATED:
var frm = document.getElementById("form1");
var cbs = document.getElementById("form1")['amenities[]'];
function setValue(frm, cbs){
var output = [];
for( var n in cbs){
if(cbs[n].checked){
output.push(cbs[n].value);
}
}
frm.textname.value=output.join();
}
frm.addEventListener("click", function(event){
if (event.toElement.type == "checkbox") {
setValue(frm, cbs);
}
});
Related
I'm trying to get a function working that hides a label in the form depending on the radio button option selected. Here's my code so far.
HTML
<form action="">
<input type="radio" id="test" value="first"> first<br>
<input type="radio" id="test" value="second"> second<br>
<input type="radio" id="test" value="third"> third
</form>
<label class="hidden">Hide this</label>
Javascript
var rbtn = document.getElementById("test");
var x = document.getElementsByClassName("hidden");
function hidelabel() {
if (rbtn == 'third') {
x.style.display='none';
}
}
You must fire your hide function after radio button clicked like this:
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
if (radVal == 'third') {
document.getElementsByClassName("hidden")[0].style.display = 'none';
}
}
ps: document.getElementsByClassName returns an array. So you cannot use x.style.display='none';.
Working example: https://jsfiddle.net/5ts0dak4/
First name the radio button ID's with something decent:
<form action="">
<input type="radio" id="first" value="first"> first<br>
<input type="radio" id="second" value="second"> second<br>
<input type="radio" id="third" onclick="hide();" value="third"> third
</form>
<label class="hidden" id="hidden">Hide this</label>
Then try this:
function hide(){
var x = document.getElementById('hidden');
if(document.getElementById('third').checked) {
x.style.display='none';
}
}
You can test it here https://jsfiddle.net/o54mzrk5/
Try this one.
CSS:
<style type="text/css">
.hidden{ display:none; }
</style>
HTML:
<form action="">
<input type="radio" name="test" value="first" onclick="func(this, true);"> first<br>
<input type="radio" name="test" value="second" onclick="func(this, true);"> second<br>
<input type="radio" name="test" value="third" onclick="func(this, false);"> third
</form>
<label class="hidden">Hide this</label>
Script:
<script type="text/javascript">
func = function(ctrl, visible) {
if(visible)
document.getElementsByClassName("hidden")[0].style.display='block';
else
document.getElementsByClassName("hidden")[0].style.display='none';
};
</script>
I want to uncheck all checkboxex inside the 'test' div without those checkboxes whose attributes are disabled.
<div id="test">
<input type="checkbox" id="check1" name="check1">
<input type="checkbox" id="check01" name="check01" disabled="disabled">
<input type="checkbox" id="check2" name="check2" disabled="disabled">
<input type="checkbox" id="check3" name="check3">
<input type="checkbox" id="check4" name="check4">
<input type="checkbox" id="check50" name="check50">
<input type="checkbox" id="check6" name="check6">
</div>
<input type="button" id="uncheckAll" onclick="uncheckAll('test')">
<script language="javascript">
function uncheckAll() {
$('#' + divid + ' :checkbox').attr('checked', false);
/*
This function uncheck all of the checkboxes, which i don't want, i want to
uncheck only checkboxes whose attributes are not disabled.
/*
}*/
</script>
You need to accept the param named divId then use :enabled filter to filter out disabled checkboxes
function uncheckAll(divid) {
$('#' + divid + ' :checkbox:enabled').prop('checked', false);
}
Demo: Fiddle
If no jQuery
function uncheckAll(divid) {
var checks = document.querySelectorAll('#' + divid + ' input[type="checkbox"]');
for(var i =0; i< checks.length;i++){
var check = checks[i];
if(!check.disabled){
check.checked = false;
}
}
}
Demo: Fiddle
You can take a common class to each input.
Try this
<div id="test">
<input type="checkbox" id="check1" class="check" name="check1">
<input type="checkbox" id="check01" class="check" name="check01" disabled="disabled">
<input type="checkbox" id="check2" class="check" name="check2" disabled="disabled">
<input type="checkbox" id="check3" class="check" name="check3">
<input type="checkbox" id="check4" class="check" name="check4">
<input type="checkbox" id="check50" class="check" name="check50">
<input type="checkbox" id="check6" class="check" name="check6">
</div>
<input type="button" id="uncheckAll" onclick="uncheckAll()">
<script language="javascript">
function uncheckAll()
{
$("input.check").each(function(){
if($(this).prop('disabled')!=true)
{
$(this).attr('checked',false);
}
});
}
</script>
Following Single line jQuery code will do your work.
function uncheckAll(divid) {
$('#' + divid + ' :checkbox:not([disabled])').attr('checked', false);
}
Simplest solution ever:
// index.html create this in <body>:
<button type="button" id="desativar-tudo">Uncheck All</button>
<button type="button" id="ativar-tudo">Check All</button>
// after that create this:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function uncheckAll() {$('input').prop('checked', false);}
function CheckAll(){$('input').prop('checked', true);}
$('#desativar-tudo').click(uncheckAll);
$('#ativar-tudo').click(CheckAll);
</script>
This question already has answers here:
How to select all checkboxes with jQuery?
(15 answers)
Closed 8 years ago.
I have multiple checkboxes , there is a checkbox with select all name, now i want that when some tick
the select all checkbox, then all the checkbox must be selected. I think this will be in jquery.
any tutorial link or codes with hints would be appreciated.the code snip is under...
<input type="checkbox" value="">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
This should check all checkboxes when you check the "Select All" one, and also uncheck all checkboxes when you uncheck it.
$("#selectAll").click(function () {
$(":checkbox").not(this).prop("checked", $(this).is(":checked"));
});
If you don't want the uncheck behavior:
$("#selectAll").click(function () {
if ($(this).is(":checked")) {
$(":checkbox").not(this).prop("checked", true);
}
});
But of course, you must identify it. Do it by adding the id="selectAll" attribute (or any other id you wish, just make sure you change the JavaScript code as well):
<input type="checkbox" value="" id="selectAll">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
<input type="checkbox" id="exp" />Tick All Checkbox<br/>
<input type="checkbox" value="demo1" class="subchkbox"/>No 1<br/>
<input type="checkbox" value="demo2" class="subchkbox"/>No 2<br/>
<input type="checkbox" value="demo3" class="subchkbox"/>No 3<br/>
<input type="checkbox" value="demo4" class="subchkbox"/>No 4<br/>
<input type="checkbox" value="demo5" class="subchkbox"/>No 5<br/>
<sctipt type="text/javascript">
/*Include the jquery library 1.9.1*/
$(document).ready(function() {
$('#exp').click(function(event) {
if(this.checked) {
$('.subchkbox').each(function() {
this.checked = true;
});
}else{
$('.subchkbox').each(function() {
this.checked = false;
});
}
});
});
[the fiddle is here][1]
Using jQuery :
$("input[type=checkbox]").prop({ checked : true })
JSFiddle
Using pure JavaScript :
var inputs = document.querySelectorAll('input[type=checkbox]')
Object.keys(inputs).forEach(function(i){
inputs[i].checked = true
})
JSFiddle
$("checkboxContainer").find("input[type='checkbox']").each(function() {
$(this).prop("checked", true);
});
I think using .find() is faster when selecting multiple elements.
If you want to do this in plain JS, it's also pretty simple.
You just have to loop through all of the inputs and set checked to true (or false), which isn't very efficient.
document.getElementById("all").addEventListener("change", function() {
if (this.checked) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = true;
}
}
} else {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = false;
}
}
}
});
<input type="checkbox" value="" id="all">Select All
<br/>
<input type="checkbox" value="">A
<br/>
<input type="checkbox" value="">B
<br/>
<input type="checkbox" value="">C
<br/>
<input type="checkbox" value="">D
<br/>
<input type="checkbox" value="">E
<br/>
<input type="checkbox" value="">F
<br/>
<input type="checkbox" value="">G
<br/>
<input type="checkbox" value="">H
<br/>
Derived from the current answer marked as correct, it can all be much simpler:
$(document).ready(function()
{
$('#exp').click(function(event)
{
$('.subchkbox').prop({
checked: $(this).prop('checked')
});
});
});
I have a code like this and I want to compare in a loop the attribute values of name with user entered input stored in variable "user". How can I do this?
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
See this answer for an example of how to loop through radio buttons in native javascript, quoted here for convenience:
<html>
<head>
<script>
var userChoice;
var setUserChoice = function(event) {
event.preventDefault();
var choices = event.target.userChoice;
for (var i =0; i < choices.length; i++) {
if (choices[i].checked) {
userChoice = choices[i].value;
}
}
event.target.choice.value = userChoice;
}
window.onload = function() {
var form = document.getElementById('userInput');
form.addEventListener('submit', setUserChoice, false);
};
</script>
</head>
<body>
<form id="userInput">
<input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
<input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
<input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
<input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
<input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
<input type="submit" value="Enter" /></br>
<output name="choice"></output>
</form>
</body>
</html>
You can compare tha values like in this fiddle: http://jsfiddle.net/5wd8p/
HTML
<form action="demo.html" id="myForm">
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
var user = "three"; //default value: depends on youur code..
//Loop through each radio element of the DOM
$("input[type=radio]").each(function(){
//Compare values of the "name" attribute and the user var
if (user == $(this).attr("name")){
alert("Same: " + $(this).attr("name"));
}else{
alert("Different: " + $(this).attr("name"));
}
});
});
try this:
document.getElementsByName(user)[0]
I have the below checkboxes and I need to get them as an array values.
<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />
I need to pass them to one ajax request as array as below:
xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);
I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this
contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5
I have done this as follows
function getContacts(){
var contacts = document.myform.contact_id, ids = [];
for (var i = 0; i < contacts.length; i += 1){
if (contacts[i].checked)
ids.push(contacts[i].value);
}
return ids;
}
http://jsfiddle.net/xQezt/
Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.
First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.
//submit event registration
submitButton.onclick = function () {
var contactArray = inputsToArray(contacts.children);
var data = serializeArray(contactArray, 'contact_id[]');
console.log(data);
}
Then I made your method "getContacts" more generic:
function inputsToArray (inputs) {
var arr = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
arr.push(inputs[i].value);
}
return arr;
}
Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:
function serializeArray (array, name) {
var serialized = '';
for(var i = 0, j = array.length; i < j; i++) {
if(i>0) serialized += '&';
serialized += name + '=' + array[i];
}
return serialized;
}
I also slightly modified your HTML:
<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>
<button id="submit">Submit</button>
Which let me query the DOM like this:
var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');
Your input's id are duplicate. so I recommend you to use name instead of id
For Example, Your HTML will look like this :
<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>
Then if you want to get the value to querystring then use the JQuery Serialize
$('#contactform').serialize();
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5
jsFiddle : http://jsfiddle.net/Eqb7f/
$(document).ready(function() {
$("#submit").click(function(){
var favorite = [];
$.each($("input[class='check']:checked"), function(){
favorite.push($(this).val());
});
document.getElementById('fav').value = favorite.join(", ");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cd-form-list">
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="A">
<label for="cd-checkbox-1">A for Apple</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="B">
<label for="cd-checkbox-2">B for Ball</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-3" class="check" value="C">
<label for="cd-checkbox-3">C for Cat</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-4" class="check" value="D">
<label for="cd-checkbox-4">D for Dog</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-5" class="check" value="E">
<label for="cd-checkbox-5">E for Ear</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-6" class="check" value="F">
<label for="cd-checkbox-6">F for Fish</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-7" class="check" value="G">
<label for="cd-checkbox-7">G for God</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-8" class="check" value="H">
<label for="cd-checkbox-8">H for Hen</label>
</div>
</div>
<div>
<input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">