Clear all HTML fields using javascript - javascript

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('');

Related

How can get length on checked checkbox array javascript

<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;

clear all ASP label fields

I am trying to clear all the fields in my .aspx page using javascript (Should be cross-browser). The below code is working fine for TextBox fields but not for Label fields.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].type == "text") {
elements[i].value = "";
}
else if (elements[i].type == "label") {
elements[i].value = "";
}
}
Later I saw that HTML is rendering asp.net Labels as span so I also tried:
else if (elements[i].type == "span") {
elements[i].innerHTML = "";
}
Still the Labels are not being cleared. Am I doing something wrong here?
And the other problem is, whenever I refresh the page, the cleared TextBox fields are again being populated with the old values.. (really frustrating)
I am trying the above code by referring this
Please help.
In modern browsers, this will clear all span elements.
[].slice.call(document.querySelectorAll("span")).forEach(function(e){
e.innerHTML="";
})
If you have applied the class "label" to your ASP labels, then you could be more specific:
[].slice.call(document.querySelectorAll(".label")).forEach(function(e){
e.innerHTML="";
})
Here is an example that will work in older browsers:
var spans = document.getElementsByTagName("span");
for (var i=0; i < spans.length; i++)
{
if ("label" == spans[i].className)
spans[i].innerHTML = "";
}
It is because there are no such types as label or span. span and label are completely different tag so you should use getElementsByTagName for each of them. The following code should do the trick bu use more clear conditions for the if blocks.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].type == "text") {
elements[i].value = "";
}
}
elements = document.getElementsByTagName("span");
for (var i = 0; i < elements.length; i++) {
if (elements[i].className == "aspLabel") {
elements[i].innerHTML = "";
}
}
elements = document.getElementsByTagName("label");
for (var i = 0; i < elements.length; i++) {
if (elements[i].className == "labelClass") {
elements[i].innerHTML = "";
}
}
Why not using html label or span with runat="server", then you will not be facing any problem with different rendering of control in different browsers
<label id="lblMyLabel" runat="server"></label>
or
<span id="spMySpan" runat="server"></span>
and this code should work then
var elements = document.getElementsByTagName("label");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "";
}
By referring #Bert Evans post I solved my problem.. The problem was that my all label fields including the headings had class name as 'label'. So if I use the Bert's solution, It will clear all the label fields including headings (which I dont want). Earlier, I thought I can solve this by assigning multiple classes to the fields which I want to clear. something like this
<asp:Label class="label clear" ID="lblBoxId" runat="server" Text="Box Id:"></asp:Label>
and then Bert's solution,
var spans = document.getElementsByTagName("span");
for (var i=0; i < spans.length; i++)
{
if ("clear" == spans[i].className) //replacing 'label' with 'clear'
spans[i].innerHTML = "";
}
This doesn't solve the problem. but when I used combination of both classes, the problem solved :).
if ("label clear" == spans[i].className) //using combination of classes as condition
This maybe simple but I really wasted my precious time understanding it. So I shared :)
EDIT: Can also be solved using simple indexOf()
if (spans[i].className.indexOf("clear") != -1) //not tested

Loop though all input boxes and clear them

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!

Change link colour if it contains certain 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!

How to determine which checkboxes are checked in an HTML form?

I have 11 checkboxes in my HTML form and already have a section in my onclick function to determine how many of them were checked, but I would like to be able to tell which of the checkboxes were checked, and possibly just add whichever checkboxes were checked to an arraylist by id/value etc.
EDIT: (Fixed code..?)
var formobj = document.forms[0];
var ingNum = 0;
checked = [];
for (var j = 0; j < formobj.elements.length; j++) {
if (formobj.elements[j].type == "checkbox" && formobj.elements[j].checked) {
ingNum++;
checked.push(formobj.elements[j].value);
}
}
If you want to convert the ones checked to an array of their value attributes (if id attribute, swap value with id), you could use...
var inputs = document.getElementById('your-form').getElementsByTagName('input'),
checked = [];
for (var i = 0, length = inputs.length; i < length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
checked.push(inputs[i].value);
}
}
That will work on any of the older IEs you may care about.
If you have the luxury of only supporting newer browsers, you could use...
var checked = [].slice.call(document
.querySelectorAll('#your-form input[type="checkbox"]'))
.filter(function(checkbox) {
return checkbox.checked;
})
.map(function(checkbox) {
return checkbox.value;
});
If you were using a library such as jQuery, it's even simpler...
var checked = $('#your-form :checkbox:checked')
.map(function() {
return this.value;
})
.get();
var checkedBoxes = [];
$("input:checked").each(function() {
checkedBoxes.push($(this));
});
Actually, I think you could just do this:
var checkedBoxes = $("input:checked");
but I'm not 100% sure if that works.

Categories