織夢提交表單(提交留言)前的js校驗

第一種狀況:頁面有引入jq的php

在form標籤上加上idpost

<form action="/plus/diy.php" enctype="multipart/form-data" method="post" id="form1">

js代碼:spa

$("#form1").submit(function() {
    if($("#name").val() == '') {
        alert('請添加姓名');
        $("#name").focus();
        return false;
    }
    if($("#phone").val() == '') {
        alert('請添加電話');
        $("#phone").focus();
        return false;
    }
    if(!$("#phone").val().match(/^((0\d{2,3}-\d{7,8})|(0\d{2,3}\d{7,8})|(1[3456789]\d{9}))$/)) {
        alert("電話格式錯誤!");
        return false;
    }
    if($("#content").val() == '') {
        alert('請添加內容');
        $("#content").focus();
        return false;
    }
});

第二種狀況:頁面沒有引入jq,須要原生js寫code

在form標籤上加上 onsubmit="return doSubmit()"orm

<form action="/plus/diy.php" enctype="multipart/form-data" method="post" onsubmit="return doSubmit()">

js代碼:blog

function doSubmit() {
    var txt1 = document.getElementById("txtname");
    var txt2 = document.getElementById("txttel");
    var txt3 = document.getElementById("txtcontent");
    if(txt1.value == "") {
        txt1.style.backgroundColor = "#e3e3e3";
        txt1.focus();
        return false;
    }
    if(txt2.value == "") {
        txt2.style.backgroundColor = "#e3e3e3";
        txt2.focus();
        return false;
    }
    if(txt3.value == "") {
        txt3.style.backgroundColor = "#e3e3e3";
        txt3.focus();
        return false;
    }
};
相關文章
相關標籤/搜索