Monday, May 24, 2010

jQuery Note

<?php
// Scroll to the bottom of div
$("#div-id").scrollTop($("#div-id").get(0).scrollHeight);

// set a value to a form element
$("#element-id").val("TEST");

// set a value to a item
$("#item-id").html("TEST");

// ##########################################
// This should do the trick if the ID of your form is myform:

$(':input','#myform') 
 .not(':button, :submit, :reset, :hidden') 
 .val('') 
 .removeAttr('checked') 
 .removeAttr('selected'); 
// It is using the :input selector which will match all input, textarea, select and button elements. Since we are passing #myform as the second argument, it will only find inputs inside this form element. Then it filters out all buttons, submits, resets and hidden inputs using not(). Then it is using val() to set the value of the remaining fields to an empty string, and then it uses removeAttr to remove the checked and selected attribute of the fields in case you have any radio/checkbox/select inputs.

function clear_form_elements(ele) {

    $(ele).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}

// ##########################################
// From http://groups.google.com/group/jquery-dev/msg/2e0b7435a864beea:

$('#myform')[0].reset(); 
// setting .val('') might not emulate "reset" 100% if you have an input like this:

// <input name="percent" value="50"/> 
// Eg calling .val() on an input with a default value of 50 would set it to an empty string, whereas calling reset() would reset it to its initial value of 50.

// ##########################################
// Here is something to get you started

$('form') // match your correct form  
.find('input[type!=submit], input[type!=reset]') // don't reset submit or reset 
.val(''); // set their value to blank 
// Of course, if you have checkboxes/radio buttons, you'll need to modify this to include them as well and set .attr({'checked': false});

// edit Paolo's answer is more concise. My answer is more wordy because I did not know about the :input selector, nor did I think about simply removing the checked attribute.

// ##########################################
// Clearing forms is a bit tricky and not as simple as it looks. 

// Suggest you use the jQuery form plugin and use its clearForm or resetForm functionality. It takes care of most of the corner cases.
// ##########################################
// I usually do:

$('#formDiv form').get(0).reset() 
// or

$('#formId').get(0).reset() 
?>

Reference: http://stackoverflow.com/questions/680241/reset-form-with-jquery

No comments: