合并两个JavaScript脚本

时间:2010-08-17 21:30:35

标签: javascript function forms checkbox

我有两个JavaScript代码段。当单击“更新”按钮时,这些任务执行特定任务。

我想合并它们。任何帮助表示赞赏。

JavaScript 1:单击该按钮时,它会检查是否至少选中了一个复选框:

function doUpdate(){
    var c = document.getElementsByTagName('input'); 
    for (var i = 0; i < c.length; i++) { 
        if (c[i].type == 'checkbox' && c[i].checked == true) { 
            // At least one checkbox is checked     
            document.holiDay.command.value= 'update';
            document.holiDay.submit();  
            return true; 
        } 
    } 
    // Nothing has been checked 
    alert("Please identify what warehouses comply:"); 
    return false; 
}

JavaScript 2:当选中任何复选框并单击更新按钮时,如果未选中任何复选框,请选中所有复选框或取消选中所有复选框;然后执行更新功能:

function doUpdate(){
    checked=false;
    function All (holiDay) {
        var all= document.getElementById('holiDay');
        if (checked == false){
            checked = true
        }
        else{
            checked = false
        }
        for (var i =0; i < all.elements.length; i++){ 
            all.elements[i].checked = checked;
        }
    }
    //after checked or unchecked all checkboxes then submit the form and other functionality
    document.holiDay.command.value= 'update';
    document.holiDay.submit();  
    return true; 
} 

1 个答案:

答案 0 :(得分:2)

我真的不确定你想做什么,但这里有一个刺:

function doUpdate(){
    var c = document.getElementsByTagName('input');
    for (var i = 0; i < c.length; i++) {
        if (c[i].type == 'checkbox' && c[i].checked == true) {
            // At least one checkbox is checked    
            UpdateHoliday();
            return true;
        }
    }
    // Nothing has been checked
    alert("Please identify what warehouses comply:");
    return false;
}

function UpdateHoliday(){
    checked = false;
    function All (holiDay) {
        var all = document.getElementById('holiDay');
        checked = !checked;
        for (var i =0; i < all.elements.length; i++){
            all.elements[i].checked = checked;
        }
    }
    //after checked or unchecked all checkboxes then submit the form and other functionality
    document.holiDay.command.value = 'update';
    document.holiDay.submit();  
} 

简化和缩进代码真的很有帮助,这样我们就能更清楚地理解它。