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

前端 未结 8 962
谎友^
谎友^ 2020-12-13 07:36

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 v

相关标签:
8条回答
  • 2020-12-13 08:32

    Oh boy, this would be a one liner with jQuery:

    $(':input:not(:button)', div).val([])
    

    Without jQuery you've got to account for <select> fields, text fields, password fields and radio/checkbox fields:

    function clearFields(container) {
        var selects = container.getElementsByTagName('select');
    
        for(var i=0, len=selects.length; i < len; i++) {
            selects[i].selectedIndex = -1;
        }
    
        var fields = container.getElementsByTagName('input');
        for(var i=0, len=fields.length; i < len; i++) {
            var field = fields[i];
            switch(field.type)
            {
                case 'radio':
                case 'checkbox':
                    field.checked = false;
                    break;
    
                case 'text':
                case 'password':
                case 'hidden':
                    field.value = ''
            }
        }
    
        var fields = container.getElementsByTagName('textarea');
        for(var i=0, len=fields.length; i < len; i++) {
            fields[i].value = ''
        }
    }
    
    0 讨论(0)
  • 2020-12-13 08:33
    $('#div_id input[type=textbox], #div_id select, #div_id textarea').val(''); 
    $('#div_id input[type=radio], #div_id input[type=checkbox]').prop('checked', false);
    

    for jquery.

    0 讨论(0)
提交回复
热议问题