0

I have set up some ajax code to validate multiple fields inside a form using php. The code works like a charm, but I wanna minimize the javascript used.

As you can see at the code below, Im getting the getElements('input') ... that validates all input fields and then getElements('textarea') that validates... ya u know! ;o) Textarea is the last line in the code below and the javascript after that is the same as inpt I'm validating the input, textarea, selection list, checkbox, etc. in my controller using php, but the code after getting the elements is the EXACT SAME.

So I was thinking that I might could make a switch case or if else with javascript to loop the elements and only write the duplicated javascript once....

Could that be done?

window.addEvent('domready', function(){
$('container').getElements('input').addEvent('keyup', function(e){
    //stop the input-tag event
    e = new Event(e).stop();
    //identify which item was activated
    var querystring = this.title;
    var value = this.value;
    var myXHR = new XHR({
        method: 'get',
        onSuccess: function(e){
            var myString = myXHR.response.text;
            var myStringArray = myString.split("###RAWR###");
            $(myStringArray[1]).innerHTML = '<em class="checking">&nbsp;</em>';
            setTimeout( ajax , 3500 );
            function ajax(){
                $(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
            }
        }
    });
    myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
});
$('container').getElements('textarea').addEvent('keyup', function(e){
4

1 回答 1

0

您可以将标记名放在一个数组循环中,并使用您的验证调用一个函数。

window.addEvent('domready', function(){
    var tagNames = ["input", "textarea", "select"];
    for (var i = 0; i < tagNames.length; i++) 
    {
        validate(tagNames[i]);
    }   
});

function validate(tag)
{
    $('container').getElements(tag).addEvent('keyup', function(e){
        //stop the input-tag event
        e = new Event(e).stop();
        //identify which item was activated
        var querystring = this.title;
        var value = this.value;
        var myXHR = new XHR({
            method: 'get',
            onSuccess: function(e){
                var myString = myXHR.response.text;
                var myStringArray = myString.split("###RAWR###");
                $(myStringArray[1]).innerHTML = '<em class="checking">&nbsp;</em>';
                setTimeout( ajax , 3500 );
                function ajax(){
                    $(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
                }
            }
        });
        myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
    });
}
于 2013-06-25T14:28:19.433 回答