I'm have a set of checkboxes and an array that contains the index of which checkboxes should be selected. I'm trying to loop through the array and for each index in it. I made a sample jsFiddle to give you guys an idea of what I'm trying to do. I have the JQuery library also if that makes things easier. http://jsfiddle.net/7EetA/1/
Try this:
var arrx=new Array();
arrx[0]=4;
arrx[1]=5;
arrx[2]=3;
arrx[3]=1;
for (var i = 0; i < arrx.length; i++) {
document.getElementsByName('cal')[arrx[i]].checked = true;
}
No jQuery needed! jsFiddle example
var arrx=new Array();
arrx[0]=4;
arrx[1]=5;
arrx[2]=3;
arrx[3]=1;
var calArray = document.getElementsByName("cal");
for (var i = 0; i < arrx.length; i++) {
calArray[arrx[i]].checked = true;
}
If you insist on using jQuery:
var arrx=new Array();
arrx[0]=4;
arrx[1]=5;
arrx[2]=3;
arrx[3]=1;
var i = 0;
$('[name=cal]').each(function() {
if ($.inArray(i, arrx) != -1) {
$(this).prop('checked',true);
}
i++;
});
Working example
If you are willing to use jQuery, it can do it quite easily based on the name of the input:
jQuery('[name="cal"]').each(function(i){jQuery(this).attr('checked', 'checked');});
If your goal is to not necessarily select all of them, however, you could use something like this:
jQuery('[name$="_c"]').each(function(i){jQuery(this).attr('checked', 'checked');});
which only checks inputs with _c at the end of the name.
http://jsfiddle.net/7EetA/9/
Related
I want to use the JavaScript index to get the value of the viewBag list.
But I have a mistake in combining the two.
Thanks for guiding me
<script>
for (var i = 0; i < #(Enumerable.Count(ViewBag.paramProperty)); i++) {
select: `#(ViewBag.paramProperty[ + "${i}" + ]);
var element = document.querySelectorAll(`[value="${select}"]`);
element[0].setAttribute("checked", "checked");
}
</script>
Firstly,you need to make sure you JsonConvert.SerializeObject with ViewBag.paramProperty,for example:
ViewBag.paramProperty = JsonConvert.SerializeObject(new List<string> { "a", "b", "c" });
Then try to set a js variable with ViewBag.paramProperty:
var paramProperty = #Html.Raw(JsonConvert.DeserializeObject(ViewBag.paramProperty));
and you can use:
for (var i = 0; i < paramProperty.lenght; i++) {
select: paramProperty[i];
var element = document.querySelectorAll(`[value="${select}"]`);
element[0].setAttribute("checked", "checked");
}
If I understand your code, you are trying to use a server-side variable in client-side.
You can try to declare a javascript variable "paramProperty" and set its value to the ViewBag.paramProperty and then iterate over it
I have multiple checkboxes in a view and each one has some data attributes, example:
Once the button is clicked I'm iterating through all the checkboxes which are selected and what I want to do is get the data-price and value fields for each selected checkbox and create JSON array.
This is what I have so far:
var boxes2 = $("#modifiersDiv :checkbox:checked");
var selectedModifiers = [];
var modifierProperties = [];
for (var i = 0; i < boxes2.length; i++) {
for (var k = 0; k < boxes2[i].attributes.length; k++) {
var attrib = boxes2[i].attributes[k];
if (attrib.specified == true) {
if (attrib.name == 'value') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
if (attrib.name == 'data-price') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
}
}
}
var jsonValueCol = JSON.stringify(selectedModifiers);
I'm not able to get the values for each checkbox and I'm able to get the values only for the first one and plus not in correct format, this is what I'm getting as JSON:
[null,"67739",null,"1"]
How can I get the correct data?
You can use $.each to parse a jquery array, something like:
var jsonValueObj = [];
$("#modifiersDiv :checkbox:checked").each(function(){
jsonValueObj.push({'value':$(this).val(),'data-price':$(this).attr('data-price')});
});
jsonValueCol = JSON.stringify(jsonValueObj);
Please note it's generally better to use val() than attr('value'). More information on this in threads like: What's the difference between jQuery .val() and .attr('value')?
As for your code, you only had one answer at most because you were overwriting the result every time you entered your loop(s). Otherwise it was okay (except the formatting but we're not sure what format you exactly want). Could please you provide an example of the result you would like to have?
if you want to get an object with all checked values, skip the JSON (which is just an array of objects) and make your own....
var checked =[];
var getValues = function(){
$('.modifiers').each(function(post){
if($(this).prop('checked')){
checked.push({'data-price':$(this).attr('data-price'),'value':$(this).attr('value')});
}
});
}
getValues();
sure i'm missing something obvious here.. but mind is elsewhere
This should give an array with values (integers) and prices (floats):
var selected = [];
$("#modifiersDiv :checkbox:checked").each(function()
{
var val = parseInt($(this).val(), 10);
var price = parseFloat($(this).data("price"));
selected.push(val);
selected.push(price);
});
Edit: Updated answer after Laziale's comment. The $(this) was indeed not targeting the checked checkbox. Now it should target the checkbox.
I'm making a program that adds 500 to the sum for each checkbox that is checked so I would like to know what the JS is for finding how many checkboxes are checked in a form. Thanks!
Note: I can't use jQuery, it has to be straight JS, sorry folks!
Use the :checked selector supported by element.querySelectorAll.
DEMO
var checkedCheckboxes = yourForm.querySelectorAll('input[type="checkbox"]:checked');
Therefore to get the sum you can do:
var sum = checkedCheckboxes.length * 500;
Use jQuery:
var $checked = $("input[type=checkbox]:checked");
alert($checked.length);
Without jquery, compatible with older browsers like IE6-8.
var form = document.getElementById('id-of-form');
var list = form.getElementsByTagName('input');
var count = 0;
for (var idx=0, len = list.length; idx < len; ++idx) {
if (list[idx].checked) ++count;
}
alert(count);
I've got a series of checkboxes with the same class. I want to get all the checkboxes with that same class as a collection and extract their id and checked status. But all the select by class examples I've seen just apply a single change to all elements of that class. I need to get a collection/array of all the checkbox elements with that class so I can iterate over them.
Ok, I've tried some of the suggestions and had no luck.
This throws an Object Expected error in IE8:
var checkboxes = document.querySelectorAll("input[type='checkbox'].chkRoles");
And this gives me an empty array every time, regardless of what's checked.
var mandatoryRoleIDs = [];
$('input.chkRoles[type="checkbox"]').each(function (i, checkbox)
{
if ($(checkbox).attr('checked'))
mandatoryRoleIDs.push($(checkbox).attr('id'));
});
Since your question is tagged with jQuery, here's how you can do it with jQuery's each() function:
$('input.someClass[type="checkbox"]').each(function(i,el){
var $this = $(el),
id = $this.attr('id'),
checked = $this.attr('checked');
/* do stuff with id and checked */
});
var checkboxes = document.getElementsByClassName('classname');
Then iterate over it to do what you need.
for(var i = 0; i < checkboxes.length; i++) {
var current = checkboxes[i];
// stuff on current
}
Using jQuery is not necessary in this simple case, and querySelectorAll is not totally supported by older browser; Vanilla JS is the best way to do it!
Since you need to support IE8(damn Microsoft) you should do something like this:
var inputs = document.getElementsByTagName('input'),
className = "classname";
for (var i = 0; i < inputs.length; i++) {
var current = inputs[i];
if (current.type !== 'checkbox' || current.className.indexOf(className) === -1) continue;
//do stuff with current
}
See a working JSFiddle example of this snippet.
I have a requirement which sounds like kind of simple but hard to implement at least for me, so here what it is
I have a dropdown with a search field in it similar to auto complete, when a key word is typed in the search field all the class names becomes empty except the keyword items.
Now i need to get the id's of "li's" only with class names,
I am new to jquery any help is greatly appreciated here is my code
function selectSearchItems() {
alert("hai");
var origul = document.getElementById("orig_ul");
var origlis = origul.getElementsByTagName('li');
for (var i = 0; i < origlis.length; i++) {
alert($('ul#orig_ul li').children('li.active-result'));
}
}
Try this:
function selectSearchItems() {
alert("hai");
var origul = $("#orig_ul");
var origlis = origul.find('li[class]');
for (var i = 0; i < origlis.length; i++) {
alert(origlis[i].id);
}
}