Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to clear the value of any input inside a div?

Is there a simple way to iterate over the child elements in an element, say a div, and if they are any sort of input (radio, select, text, hidden...) clear their value?

Edit to add link to example solution code. Many thanks to Guffa and the other respondents! I learned from this!

like image 473
jerrygarciuh Avatar asked Sep 30 '09 18:09

jerrygarciuh


2 Answers

This is an old post but someone can see it.

function clearFields(divElement) {
    var ancestor = document.getElementById(divElement),
    descendents = ancestor.getElementsByTagName('*');

    var i, e, d;
    for (i = 0; i < descendents.length; ++i) {
        if (descendents[i].tagName.toLowerCase() == 'input'){
            switch (descendents[i].type){
                case 'text':
                case 'password':
                case 'color':
                case 'date':
                case 'email':
                case 'month':
                case 'number':
                case 'range':
                case 'search':
                case 'tel':
                case 'time':
                case 'url':
                case 'week':
                    descendents[i].value = '';
                    break;

                case 'radio':
                case 'checkbox':
                    descendents[i].checked = false;
            }
        }
        else if (descendents[i].tagName.toLowerCase() == 'select'){
            descendents[i].selectedIndex = 0;
        }
    }   
}

and to use it:

clearFields ('divName');

Of course you can add more elements to rest it

like image 80
AlejandroAlis Avatar answered Oct 08 '22 10:10

AlejandroAlis


Very simple with JQuery:

$('#myDiv').children().find('input,select').each(function(){
   $(this).val('');
});

We can put as many tags in the "find" call.

like image 43
haresh Avatar answered Oct 08 '22 11:10

haresh