First thing's first. I can't use JQuery, only JS.
I have some checkboxes all with different names. I need the different names. I then have another checkbox that when clicked should deselect the previous checkboxes.
var isAllCheck = false;
function togglecheckboxes(cn) {
var cbarray = document.getElementsByName(cn);
for (var i = 0; i < cbarray.length; i++) {
cbarray[i].checked = !isAllCheck
}
isAllCheck = !isAllCheck;
}
<input type="checkbox" name="email">
<input type="checkbox" name="phone">
<input type="checkbox" name="sms">
<input type="checkbox" name="whatsapp">
<input type="checkbox" onclick="togglecheckboxes('cb')" value="Toggle all">
if the names are all 'cb' then it works but I need them to be different. Is there anyway i can get this to work while maintaining different names?
huge thanks in advance.
Use document.querySelectorAll to select elements based on their attributes like class name.
var isAllCheck = false;
function togglecheckboxes() {
var cbarray = document.querySelectorAll('input.check-box');
for (var i = 0; i < cbarray.length; i++) {
cbarray[i].checked = !isAllCheck
}
isAllCheck = !isAllCheck;
}
<input type="checkbox" class="check-box" name="email">Email
<input type="checkbox" class="check-box" name="phone">Phone
<input type="checkbox" class="check-box" name="sms">SMS
<input type="checkbox" class="check-box" name="whatsapp">Whatsapp
<input type="checkbox" onclick="togglecheckboxes()" value="Toggle all">Toggle All
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Use getElementsByClassName() instead of getElementsByName(). This way they can all have individual names, but a common class that you use to collect them all and deselect their checkboxes. Remember that HTML-elements can also have multiple classes, so this works even if you need to do some specific styling on the different checkboxes using classes, while elements can only have a single name. For this reason you generally always want to do logical operations on multiple elements using a common class (or an ID if you're targetting only one specific element).
var isAllCheck = false;
function togglecheckboxes(cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
cbarray[i].checked = !isAllCheck
}
isAllCheck = !isAllCheck;
}
<input class="cn" type="checkbox" name="email">
<input class="cn" type="checkbox" name="phone">
<input class="cn" type="checkbox" name="sms">
<input class="cn" type="checkbox" name="whatsapp">
<input type="checkbox" onclick="togglecheckboxes('cn')" value="Toggle all">
Related
I have been using the following script to check multiple checkboxes at a time, and all is going well:
<script type="text/javascript">
function toggle(source) {
var aInputs = document.getElementsByTagName('input');
for (var i=0;i<aInputs.length;i++) {
if (aInputs[i] != source && aInputs[i].className == source.className) {
aInputs[i].checked = source.checked;
}
}
}
</script>
Some general code where I use this is:
...
<li>surface analysis</li>
<input type="checkbox" id="checkbox_wpc_sfc00" class="wpc_sfc">00Z
<input type="checkbox" id="checkbox_wpc_sfc03" class="wpc_sfc">03Z
<input type="checkbox" id="checkbox_wpc_sfc06" class="wpc_sfc">06Z
<input type="checkbox" class="wpc_sfc" onClick="toggle(this)"> Toggle All surface
<li>upper air analysis</li>
<input type="checkbox" id="checkbox_wpc_ua00" class="wpc_ua">00Z
<input type="checkbox" id="checkbox_wpc_ua03" class="wpc_ua">03Z
<input type="checkbox" id="checkbox_wpc_ua06" class="wpc_ua">06Z
<input type="checkbox" class="wpc_ua" onClick="toggle(this)"> Toggle All upper air
...
This creates a list of 'surface analyses' checkboxes for 00Z, 03Z, 06Z, and an option to select all 3 of these boxes at once. There is another list of the same style but for 'upper air analysis'. This works great the way that this is.
The issue is I now want to create 00Z, 03Z, and 06Z checkboxes. In other words, the 00Z checkbox would mark the 'checkbox_wpc_sfc00' as well as the 'checkbox_wpc_ua00' text. However, I have run into a bit of a wall as I would figure a separate 'toggle' function would work where I use a str.contains('00'), but this seems to be failing. Any thoughts on this? I would like to try and keep this to either HTML or Javascript, if possible.
I think this should do the job:
function toggle(source, aux) {
var aInputs = document.getElementsByTagName('input');
if (aux != "surface and air"){
for (var i=0; i<aInputs.length; i++) {
if (aInputs[i] != source && aInputs[i].className == source.className) {
aInputs[i].checked = source.checked;
}
}
} else {
var sSelection = source.id;
var sType = sSelection.slice(-2);
var sCheckBox, sLast2;
for (var i=0; i<aInputs.length; i++) {
sCheckBox = aInputs[i].id;
sLast2 = sCheckBox.slice(-2);
if (sLast2 == sType) {
aInputs[i].checked = source.checked;
}
}
}
}
<li>surface analysis</li>
<input type="checkbox" id="checkbox_wpc_sfc00" class="wpc_sfc">00Z
<input type="checkbox" id="checkbox_wpc_sfc03" class="wpc_sfc">03Z
<input type="checkbox" id="checkbox_wpc_sfc06" class="wpc_sfc">06Z
<input type="checkbox" class="wpc_sfc" onClick="toggle(this, 'surface')"> Toggle All surface
<li>upper air analysis</li>
<input type="checkbox" id="checkbox_wpc_ua00" class="wpc_ua">00Z
<input type="checkbox" id="checkbox_wpc_ua03" class="wpc_ua">03Z
<input type="checkbox" id="checkbox_wpc_ua06" class="wpc_ua">06Z
<input type="checkbox" class="wpc_ua" onClick="toggle(this, 'air')"> Toggle All upper air
<li>general type selection</li>
<input type="checkbox" id="checkbox_wpc_00" class="wpc_00" onClick="toggle(this, 'surface and air')">00Z
<input type="checkbox" id="checkbox_wpc_03" class="wpc_03" onClick="toggle(this, 'surface and air')">03Z
<input type="checkbox" id="checkbox_wpc_06" class="wpc_06" onClick="toggle(this, 'surface and air')">06Z
Your current method is to pass the "master checkbox" as the sole argument, and use values extracted from it in the control function. This doesn't appear to be necessary. If it was not more than the most expedient manner you saw to accomplish your goal, please comment such that I might provide a better solution.
function toggle(selector, state) {
Array.from(
document.querySelectorAll(selector)
).forEach(
(element)=>element.checked = state
)
}
Contrasted with your current implementation, this expects values to be passed based on your "master checkbox," versus passing the checkbox itself. I'm also using an array function instead of an explicit loop, and I'm using an arrow function. If you're unfamiliar with either, I can provide references.
Use of this would be as follows:
<li>surface analysis</li>
<input type="checkbox" id="checkbox_wpc_sfc00" class="wpc_sfc">00Z
<input type="checkbox" id="checkbox_wpc_sfc03" class="wpc_sfc">03Z
<input type="checkbox" id="checkbox_wpc_sfc06" class="wpc_sfc">06Z
<input type="checkbox" class="wpc_sfc" onClick="toggle(`.${this.className}`,this.checked)"> Toggle All surface
<li>upper air analysis</li>
<input type="checkbox" id="checkbox_wpc_ua00" class="wpc_ua">00Z
<input type="checkbox" id="checkbox_wpc_ua03" class="wpc_ua">03Z
<input type="checkbox" id="checkbox_wpc_ua06" class="wpc_ua">06Z
<input type="checkbox" class="wpc_ua" onClick="toggle(`.${this.className}`,this.checked)"> Toggle All upper air
<li>Toggle Region</li>
<input type="checkbox" class="all_00Z" onClick="toggle(`[id$='00']`,this.checked)">
<input type="checkbox" class="all_03Z" onClick="toggle(`[id$='03']`,this.checked)">
<input type="checkbox" class="all_06Z" onClick="toggle(`[id$='06']`,this.checked)">
The above uses string templates and expression matching selectors. Again, if these are unfamiliar, I can help you find some references.
I have 4 html input elements:
<input type="checkbox" class="viewButton" id="html-button">
<input type="checkbox" class="viewButton" id="css-button">
<input type="checkbox" class="viewButton" id="javascript-button">
<input type="checkbox" class="viewButton" id="output-button">
What I'd like to do is get the name of each id in every element with a class of "viewButton" and put them in an array.
In order to do that, I wrote this:
var viewButtonsArray = [];
viewButtonsArray.push($(".viewButton"));
var buttonIdsArray = [];
for (var i = 0; i < viewButtonsArray[0].length; i++) {
buttonIdsArray.push(viewButtonsArray[0][i].id);
}
The code works. However, I was wondering if there was an easier way to do this.
Thanks!
(I don't think this is a duplicate. The link being claimed as a duplicate solves a problem regarding an element within another element, the parent has the class, child has the id. My question is about elements with BOTH a class and id, hence the title "ids of every element with a certain class" and not "id of elements within a parent element with a class".)
You can do this with map() and get() DEMO
var viewButtonsArray = $('.viewButton').map(function() {
return $(this).attr('id');
}).get();
console.log(viewButtonsArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="viewButton" id="html-button">
<input type="checkbox" class="viewButton" id="css-button">
<input type="checkbox" class="viewButton" id="javascript-button">
<input type="checkbox" class="viewButton" id="output-button">
You could use:
var ary = [];
$('.viewButton').each(function(){ ary.push(this.id) })
I have the following series of checkboxes coming from the datatables in the form like below:
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
How can I separate that id from list-chk. Do I have to include data-id parameter?
As per my understanding, Try that
$('input[id^="list-chk"]').click(function(){
$(this).attr("id"); //Getting click control ID
$(this).val(); //Getting Value
});
You can use split if you know the ID always has that format.
var ins = document.getElementsByTagName('input');
for (var i = 0; i < ins.length; i++) {
document.write(ins[i].id.split('_')[1]);
}
// jQuery
$('input').each(function() {
$('body').append(this.id.split('_')[1]);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
Split will make an array from the given string, splitting it where you tell it to.
"list-chk_1".split('_') // results in ["list-chk", "1"]
Other methods could be using var idnr = this.id.replace('list-chk_', '');
I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...
var form = document.forms['myForm'];
var env = form.env.value;
The form itself looks like this...
<form name="myForm" action='JavaScript:xmlhttpPost("/path/to/some/pythoncode.py")'>
<input type="radio" name="env" id="env" value="inside">Inside
<input type="radio" name="env" id="env" value="outside" checked="checked">Outside
<input type="radio" name="env" id="env" value="both">Both
<input type="radio" name="env" id="env" value="neither">Neither
I have some text boxes on the form that I can use the same technique to find the value (
var name = form.fname.value
with a
<input type="text" name="fname" id="fname">
However, when I submit the form and build my post, the value for the radio buttons is always undefined. It works fine in Chrome, but nothing in IE or FireFox.
I tried var env = document.getElementById('env').value, but for some reason that always defaults to the first value (inside) no matter what I select. That method also does not return a value when using Chrome.
Is there something I'm missing for reading the checked value of a radio input in FF or IE?
Try this
function getValueFromRadioButton(name) {
//Get all elements with the name
var buttons = document.getElementsByName(name);
for(var i = 0; i < buttons.length; i++) {
//Check if button is checked
var button = buttons[i];
if(button.checked) {
//Return value
return button.value;
}
}
//No radio button is selected.
return null;
}
IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.
You are using the same ID for multiple Elements, ID is unique for element on the page.
use different IDs.
edit: names can be the same. because then the radio buttons are as a group.
As stated, the IDs should be different to be valid, but you could accomplish this by eliminating the IDs all together and using just the input name:
var form = document.forms['myForm'];
var radios = form.elements["env"];
var env = null;
for(var i=0;i<radios.length;i++) {
if(radios[i].checked == true) {
env = radios[i].value;
}
}
<form name="myForm">
<input type="radio" name="env" value="inside">Inside
<input type="radio" name="env" ivalue="outside" checked="checked">Outside
<input type="radio" name="env" value="both">Both
<input type="radio" name="env" value="neither">Neither
</form>
Short & clear on ES-2015, for use with Babel:
function getValueFromRadioButton( name ){
return [...document.getElementsByName(name)]
.reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}
console.log( getValueFromRadioButton('payment') );
<div>
<input type="radio" name="payment" value="offline">
<input type="radio" name="payment" value="online">
<input type="radio" name="payment" value="part" checked>
<input type="radio" name="payment" value="free">
</div>
You can try this:
var form = document.querySelector('form#myForm');
var env_value = form.querySelector('[name="env"]:checked').value;
I've dynamically loading check box fields, how can I send those to server based on user selection.
For example I've following doc,
<label>Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label>Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
Suppose if user selected first two values for each of them, then I need to send like
response[0][0]=199; // Id
response[0][1]=['Apple','Mango']; //values
response[1][0]=200
response[1][1]=['Red','Blue'];
I've tried some approaches suggested in existing posts but failed to implement how I want.
You can make some minor changes in the html then use .map()
<label class="set" data-id="199">Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label class="set" data-id="200">Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
then
var array = $('.set').map(function () {
var $this = $(this),
id = $this.data('id'),
array = [id];
array.push($('input[name="set_' + id + '\\[\\]"]').filter(':checked').map(function () {
return this.value;
}).get())
return [array]
}).get()
Demo: Fiddle
Yet another solution:
<lable>Set1</lable>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<input type="button" value="check" class="js-submit">
Js:
$(".js-submit").on("click", function(){
var a = $("input[type='checkbox']:checked");
var values = {};
a.each(function(){
var value = $(this).val();
var name = $(this).attr("name");
if(!values[name]) values[name] = [];
values[name].push(value)
});
console.log(values)
});
Demo
To expand on my comment a little, here's how I'd do this... given that you're sending this as an ajax request, I'd still wrap these elements in a form element, and use that as a starting-point to build the object we'll be sending...
var myForm = document.getElementById('formID').elements,//get all input nodes
data = {},temp;
for (var i=0;i<myForm.length;++i)
{
temp = myForm.item(i).name.replace(/[[]]/g,'');//replace square brackets
if (!data[temp])
data[temp] = [];//create array if key does not exist
if (myForm.item(i).checked)//for checkboxes
data[temp].push(myForm.item(i).value);
}
That's the basic setup. If you want, you can add checks and further tailor this, so you can deal with various types of input fields, but in essence, it'll boil down to this.
You might also want to use Array.prototype.forEach on the myForm.elements NodeList, and use a callback to keep your code nice and clean.
Here's an example of a slightly more usable version of the same code:
btn.addEventListener('click', function()
{
var data = {};
Array.prototype.forEach.call(frm.elements, function(item)
{
var temp;
if (item === btn) return;//don't includ the button element
if (item.type === 'checkbox' && !item.checked ) return;//not checked, ignore
if (item.name.match(/[[]]/))
{
temp = item.name.replace(/[[]]/g, '');
if (!data[temp]) data[temp] = [];//if property does not exist, make an array
data[temp].push(item.value);
return;
}
//normal elements:
data[item.name] = item.value;
});
//ajax request using data variable goes here!
console.log(data);
},false);
And here's the fiddle of it
First of all thanks for all who have given answers to this question. I've derived my own solution for this issue but it is not possible without your help, especially this
var checkBoxArray = {};
$.each($("input[name^='set_'][type='checkbox']:checked"), function(i, item) {
var Id = item.name.replace(/^(set_)|[\[\]]/g, "");
var value = $(item).val();
if(!checkBoxArray[Id])
checkBoxArray[Id] = [];
checkBoxArray[Id].push(value)
});
$.map(checkBoxArray, function(value, index) {
reponse.push([index, value]);
});
Its worked for me, suggest if anything not proper in above code snippet.