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
Related
I am using the following code to uncheck selected check boxes on page refresh.
for (i = 0; i < object.length; i++)
{
object[i].checked = false;
}
The validation after refresh will work but the checkboxes will stay as selected.(Tick wont go)
Please Help.
The attribute checked of the checkbox didn't use value true or false. (Input checked attribute on W3Schools)
In order to uncheck the checkboxes, you have to remove the attribute from the element:
for (i = 0; i < object.length; i++) {
if (object[i].hasAttribute("checked")) {
object[i].removeAttribute("checked");
}
}
Obviously, you can check the checkboxes by adding the attribute to the element:
for (i = 0; i < object.length; i++) {
if (!object[i].hasAttribute("checked")) {
object[i].addAttribute("checked");
}
}
This will work on every single browser by the way.
try :
for (i = 0; i < object.length; i++)
{
object[i].checked = "off";
}
For this particular challenge I am required to toggle membership of an already created class for all <li> elements in two given lists (at the same time). If a <li> element in either list is not currently assigned the class, it is assigned the class; if a <li> element in either list is currently assigned the class, the class is removed. Everytime a button is clicked, the class is added and removed (e.g on first click, the class could be added - then on second click, the class could be removed, etc).
I have been asked to do this particular task specifically in normal JavaScript. While I know that jQuery would be the easier option, I have been asked to undertake this task with just normal JavaScript.
When I press the button, the css class is being applied as expected (here, the font-family, font-size, and the font-stretch properties are being altered); however, when I click on the button the second time, nothing changes (e.g the class being removed), and everything going back to normal.
If anyone can point me towards a non-jQuery way of adjusting my current code, let me know.
Thanks for your help :).
Here is the relevant HTML, CSS, and JavaScript for this task:
HTML:
<ul id="newZealandList">
<li>Auckland</li>
<li>Wellington</li>
<li>Christchurch</li>
<li>Tauranga</li>
<li>Dunedin</li>
</ul>
<ul id="usaList">
<li>Los Angeles</li>
<li>San Francisco</li>
<li>San Diego</li>
<li>Denver</li>
<li>Boulder</li>
</ul>
<button id="modifyListsToggle">Change Lists - Toggle</button>
CSS:
.modifyListElements{
font-family:"Comic Sans MS", cursive;
font-size:24px;
font-stretch:extra-expanded;
}
JavaScript
var newZealandListItems = document.getElementById("newZealandList").getElementsByTagName("li");
var usaListItems = document.getElementById("usaList").getElementsByTagName("li");
function addClass(obj)
{
obj.className="modifyListElements";
}
function removeClass(obj)
{
obj.className = "";
}
function toggleClass()
{
for (var i = 0; i < newZealandListItems.length; i++) {
if(i.className != "modifyListElements") {
//newZealandListItems[i].className = "modifyListElements";
addClass(newZealandListItems[i]);
}
else
{
//newZealandListItems[i].className = "";
removeClass(newZealandListItems[i]);
}
}
for (var i = 0; i < usaListItems.length; i++) {
if(i.className != "modifyListElements") {
//usaListItems[i].className = "modifyListElements";
addClass(usaListItems[i]);
}
else
{
//usaListItems[i].className = "";
removeClass(usaListItems[i]);
}
}
}
var modifyListsToggle = document.getElementById("modifyListsToggle");
modifyListsToggle.onclick = toggleClass;
Issue is here
for (var i = 0; i < newZealandListItems.length; i++) {
if(i.className != "modifyListElements") {
//con....
and here
for (var i = 0; i < usaListItems.length; i++) {
if(i.className != "modifyListElements") {
//con....
i is just the loop counter variable, you need to use it access the item at that index so should be
for (var i = 0; i < newZealandListItems.length; i++) {
if (newZealandListItems[i].className != "modifyListElements") {
//con..
and
for (var i = 0; i < usaListItems.length; i++) {
if (usaListItems[i].className != "modifyListElements") {
//con..
On another note, this code will potentially have an issue if multiple classes are used, as the .className property will return all the classes on an element. If that may be an issue in the future, I would pursue using a className.replace('modifyListElements','') for remove (that way it will only remove that class and not other ones if there). And the tests for one class on className will also not work if multiple classes are there. In this case pursuing a test and then a .replace would probably be the solution.
A small bug in your code checking classname . I modified your code it working fine . Please check it
http://jsfiddle.net/kRva7/ .
var newZealandListItems = document.getElementById("newZealandList").getElementsByTagName("li");
var usaListItems = document.getElementById("usaList").getElementsByTagName("li");
function addClass(obj)
{
obj.className="modifyListElements";
}
function removeClass(obj)
{
obj.className = "";
console.log(obj.className);
}
function toggleClass()
{
for (var i = 0; i < newZealandListItems.length; i++) {
var item = newZealandListItems[i];
if(item.className != "modifyListElements") {
//newZealandListItems[i].className = "modifyListElements";
addClass(item);
}
else
{
//newZealandListItems[i].className = "";
removeClass(item);
}
}
for (var i = 0; i < usaListItems.length; i++) {
var item = usaListItems[i];
if(item.className != "modifyListElements") {
//usaListItems[i].className = "modifyListElements";
addClass(item);
}
else
{
//usaListItems[i].className = "";
removeClass(item);
}
}
}
var modifyListsToggle = document.getElementById("modifyListsToggle");
modifyListsToggle.onclick = toggleClass;
The easiest way you could do this (although IE support is problematic) is like this:
var btn = document.getElementById('modifyListsToggle'),
lists = document.querySelectorAll('ul');
btn.addEventListener('click', function(e) {
for(var i = 0; i < lists.length; i++) {
var items = lists[i].querySelectorAll('li');
for(var j = 0; j < items.length; j++) {
items[j].classList.toggle('modifyListElements');
}
}
}, false);
demo
querySelectorAll() is only supported by IE8+
addEventListener() is only supported by IE9+
classList is only supported by IE10
I have a long table with many many columns and it looks really ugly for the users. What I wanted to do was create a simple button that would act as a switch, to turn on and off some of the columns.
Some of the columns are not needed, so what I did was add a class to every that wasn't needed, eg: ....
Now, what I thought I could do was this:
var hidden = 1;
function toggleTable(){
element_array = document.getElementsByClassName('disabled');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
This works for the most part in Firefox, but some quick tests in IE(7+8) and I get the following:
Message: Object doesn't support this property or method
Obviously indicating that IE doesn't want to let me simply change "display: none;" for something like table columns/rows.
I can't think of any workarounds. Ideally I'd like a fully cross-compatible solution to toggling the display of certain table columns,but if it's not compatible in the older browsers (eg: IE6) then that would also be OK.
The error that you're getting is not because IE doesn't want to set the display property, it's because the getElementsByClassName method isn't implemented in IE. If you want an implementation of that methods you can use this one which was written by Dustin Diaz.
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Then you would re-write your method as follows.
var hidden = 1;
function toggleTable(){
var element_array = getElementsByClass('foo');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
toggleTable();
And what about jQuery.toggle()?
$(".disabled").toggle();
I want to be able to have a javascript function that hides divs for me. For example, I have something like
<div id='container'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
And i would like the function to hide every 'item' class element after say the first 3. How would i go about this?
Thanks for any help
In JS, you could do something like this, provided the item divs are the only children of the container div:
var itemDivs = document.getElementById("container").children;
for(var i = 0; i < itemDivs.length; i++) {
if(i > 2) {
itemDivs[i].style.display = 'none';
}
}
Try it here: http://jsfiddle.net/eY9ZD/
Otherwise, you could do this:
var divs = document.getElementById("container").getElementsByTagName("div");
for(var i = 0; i < itemDivs.length; i++) {
if(i > 2 && divs[i].className == 'item') {
itemDivs[i].style.display = 'none';
}
}
Try it here: http://jsfiddle.net/6TcWE/
And finally, if jQuery is an option, there's a one-liner using the gt selector:
$("#container div.item:gt(2)").hide();
Try it here: http://jsfiddle.net/J8wK6/
With plain JavaScript something like:
function hideElements(elements, start) {
for(var i = 0, length = elements.length; i < length;i++) {
if(i >= start) {
elements[i].style.display = "none";
}
}
}
Then you can do:
var elements = document.getElementById('container').getElementsByClassName('item');
hideElements(elements , 3);
Reference: getElementById, getElementsByClassName
Update:
Interestingly, IE8 seems to support the more powerful querySelectorAll() function. So if you don't care about < IE8, then you can also do:
var elements = document.querySelectorAll('#container .item');
hideElements(elements , 3);
Unfortunately, there is not the "one" solution to select the elements you want in all browsers. If you don't want to think about cross-browser compatibility, consider to use jQuery as #karim suggests.
You can do this easily with jQuery, but your tag doesn't include that so I'm going to show you a vanilla Javascript way:
var divs = document.getElementById('container').getElementsByTagName('div');
var numItemDivs = 0;
for (var i=0; i<divs.length; i++) {
if (divs[i].className == "item") {
numItemDivs++;
if (numItemDivs > 2) {
divs[i].style.display = "none";
}
}
}
If you are just using regular javascript you can do something like this:
var container = document.getElementById("container");
var items = container.childNodes;
for(var i = 0; i < items.length; i++){
if(i >= 3)
items[i].style.display = "none";
}
If you're looking for a pure javascript implementation, this should work; it will also only hide DIV child nodes.
function hideMe(){
var item_list = document.getElementById('container').children;
for(var i = 0; i < item_list.length; i++){
if(i > 2 && item_list[i].tagName == "DIV"){
item_list[i].style.display = "none";
}
}
}
EDIT: changed the style from visibility to display, you probably don't want the layout space lingering.
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('');