<form name='form1' >
<input type=checkbox name='cbox[]' />
</form>
<script>
var checkbox = document.getElementsByName('ckbox[]')
var ln = checkbox.length
alert(ln)
</script>
How can I count only the checked checkboxes with JavaScript or jQuery?
Doing it with jQuery would shorten the code and make it more readable, maintainable and easier to understand. Use attribute selector with :checked selector
Live Demo
$('[name="cbox[]"]:checked').length
If you want to use plain javascript
var checkbox = document.getElementsByName('ckbox[]');
var ln = 0;
for(var i=0; i< checkbox.length; i++) {
if(checkbox[i].checked)
ln++
}
alert(ln)
jQuery solution:
var len = $("[name='cbox[]']:checked").length;
JavaScript solution:
var len = [].slice.call(document.querySelectorAll("[name='cbox[]']"))
.filter(function(e) { return e.checked; }).length;
$('input:checked').length will do if you do not have any other input tags than in this form.
Try this
jQuery solution:
var len = $(":checked",$("input[name='cbox[]']")).size();
var fobj = document.forms[0];
var c = 0;
for (var i = 0; i < formobj.elements.length; i++)
{
if (fobj.elements[i].type == "checkbox")
{
if (fobj.elements[i].checked)
{
c++;
}
}
}
alert('Total Checked = ' + c);
Try out,
var boxes = $('input[name="cbox[]"]:checked');
find how many are checked,
$(boxes).size();
or
$(boxes).length();
var len = $("[name='cbox[]']:checked").length;
will work but will not work if you are directly comparing like
if ( $("[name='cbox[]']").length= $("[name='cbox[]']:checked").length)
you also do by this
you have to define class for checkBox and then follow below
var chkLength = $('input.className:checked').length;
alert(chkLength);
this will print your total no of checkboxes from list
You may use as below as well
$('[name=cbox\\[\\]]:checked').length
Try this,
var ch_n = $( "input:checked" ).length;
Related
I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
Here is an example of my source code below:
<script>
var element = document.getElementById('#re');
element.addEventListener('click', function() {
document.getElementById("#id1").value = "";
document.getElementById("#id2").value = "";
document.getElementById("#id3").value = "";
});
</script>
Assuming your IDs have the format shown in your example:
for (var i = 1; i <= 3; i++) {
document.getElementById("id" + i).value = "";
}
If that's not the case but you know the ID of every element you can put all IDs in an array and use that:
var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
document.getElementById(id).value = "";
});
Another solution is to give all the elements you want to reset a specific class and target that:
var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
element.value = "";
});
Instead of using ids, you can loop through your inputs for example:
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):
for(var i = 1; i <= 3; i++) {
document.getElementById('id' + i).value = '';
}
If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:
var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
element.value = '';
});
I want to get all DIVs in DIV(id = room) and do the same javascript code on each one.
I think it should look like this
Get element by id room -> Get all divs inside -> do something on them(change each class to "grass")
or by using a loop.
How to do that?
Please don't use jQuery.
Modern browsers (IE9+):
var divs = document.querySelectorAll('#room div');
[].forEach.call(divs, function(div){
div.className = 'green';
});
var a = document.getElementById("room").getElementsByTagName("div");
for(i = 0; i < a.length; i++)
{
a[i].className = "grass";
}
Do you want to get all divs inside, or just direct children?
This one traverses direct children. If you want to go through all internal nodes, you need to recurse it.
function grassify(nodeId) {
var node = document.getElementById(nodeId);
for(var i in node.childNodes) {
// Do things with node.childNodes[i], for example:
node.childNodes[i].className = 'grass';
}
}
Then just:
grassify('room');
var room=document.getElementByID("#room");
var divs=room.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
doSomething(divs[i]);
}
Use getElementByID and getElementsByTagName
Use getElementsByTagName
First get a reference to the container element, then use getElementsByTagName for the type of element you want.
See http://jsfiddle.net/aQtTx/
JS:
var targetDiv = document.getElementById("div1");
var nestedDivs = document.getElementsByTagName("div");
for(var divIndex = 0; divIndex < nestedDivs.length; divIndex++)
{
nestedDivs[divIndex].style.backgroundColor = 'red';
}
function myFunction()
{
var a=document.getElementById('room').childNodes;
for (i=0; i<a.length; i++)
{
a[i].className="grass";
};
}
JsFiddle
var parent = document.getElementById("room");
var divs = parent.getElementsByTagName('div');
for (i=0; i<divs.length; i++)
{
divs[i].className="grass";
};
How can I, using javascript, loop through all input boxes on a page and clear the data inside of them (making them all blank)?
Try this code:
$('input').val('');
It's looping over all input elements and it's setting their value to the empty string.
Here is a demo: http://jsfiddle.net/maqVn/1/
And of course if you don't have jQuery:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
inputs[i].value = '';
}
Since I prefer the functional style, you can use:
Array.prototype.slice.call(
document.getElementsByTagName('input'))
.forEach(function (el) {
el.value = '';
});
[].forEach.call(document.getElementsByTagName('input'), function(e){
e.value = '';
});
Edit: If you want to grab textareas and other elements, you can use querySelectorAll:
[].forEach.call(
document.querySelectorAll('input, textarea'),
function(e) { e.value = ''; }
);
var inputs = document.getElementsByTagName("input"),
clearTypes = { "text" : 1, "password" : 1, "email" : 1 }, // etc. you fill this in
i = inputs.length,
input;
while (i) {
if (clearTypes[(input = inputs[--i]).type]) {
input.value = "";
}
}
Just to register an alternative without JavaScript, the HTML element <input type="reset" /> clear all fields of the form. In some scenarios it may be enough.
Without jquery:
var list = document.getElementsByTagName('input');
for(var i = 0; i < list.length; i++) {
if(list[i].type == 'text' || list[i].type == 'password')
list[i].value = '';
}
You are able to do something like tha following:
<script>
e = document.getElementsByTagName('input');
for (i = 0; i < e.length; i++){
if (e[i].type != 'text') continue;
e[i].value = '';
}
</script>
Edited: added exclude for input which their types are not text!
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML().indexOf("search string") != -1){test[i].style.color="black";}
Hopefully it's obvious what I'm trying to do - if there is a link on the page that contains the search phrase, change it's color to black. This isn't working though. Any ideas?
Thanks.
innerHTML is a property not a function, so don't use ().
innerHTML is not a function, it is a property. Try doing this instead:
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML.indexOf("search string") != -1){test[i].style.color="black";}
A cleaner way of doing it would be to use jQuery:
var searchTerm = 'term1';
$('a').filter(function (a) {
if (this.innerHTML.indexOf(searchTerm) != -1)
return true;
return false;
}).css('color','red')
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++) {
var newElem = test[i].innerHTML;
if(newElem.indexOf("searchString") != -1){
test[i].style.color="black";
}
}
innerHTML is no function! It's a property!
is it possible to clear all textboxes in HTML by calling a javascript function ?
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
var fields = document.getElementsByTagName('input'),
length = fields.length;
while (length--) {
if (fields[length].type === 'text') { fields[length].value = ''; }
}
This should do the work
var inputElements = document.getElementsByTagName('input');
for (var i=0; i < inputElements.length; i++) {
if (inputElements[i].type == 'text') {
inputElements[i].value = '';
}
}
If all you fields started blank you can call the form's reset method:
document.forms[0].reset() (there are usually more elegant ways to get the form handle depending on your specific case).
While not the simplest solution, look into jQuery. You should be able to do something like:
$("input[type=text]").val('');
I'm no jQuery expert, though.
I think
$("input:text").val("");
Should work with jQuery.
Old post..but, with jquery for example:
$("input[type=text],textarea,input[type=email]").val('');