Java验证表单onsubmit不返回false

时间:2018-07-11 09:02:10

标签: javascript html

注意:我搜索了类似的问题,但仍无法解决,因此我再次询问。 我有一个表格及其onsubmit = "return submit()"。它检查textarea是否为空。如果是,则返回false,但这不起作用。即使文本区域为空,操作仍将转到下一个网站。

        let firstName = document.querySelector('#firstname');
    let lastName = document.querySelector('#lastname');
    let password = document.querySelector('#password');
    let retypePass = document.querySelector('#repassword');
    let radioMale = document.querySelector('#male');
    let radioFemale = document.querySelector('#female');
    let textArea = document.querySelector('#textarea');
    let select= document.querySelector('#select');
    let button = document.querySelector('#button');
    let form = document.querySelector('#form');

    function submit(){
        if (textArea.value = "") {
           textArea.nextElementSibling.innerHTML = "Fill this box";
           return false;
     }
  }
HTML :`


    <div class='wrapper'>
    <h1>Registration Form</h1>
    <form  action="http://google.com" id='form' onsubmit="return submit()">
        <input placeholder="First Name" type="text" id='firstname' required>
        <span></span>
        <br>
        <input placeholder="Last Name" type="text" id='lastname' required>
        <span></span>
        <br>
        <input placeholder="Password" type="text" id='password' required>
        <span></span>
        <br>
        <input placeholder="Retype Password" type="text" id='repassword' required>
        <span></span>
        <br>
        <input placeholder="Phone Number" type="tel" id='tel' >
        <br>
        <div class='radio'>
            <h4>Selector Your Gender</h4>
            <input type='radio'name='same' id='male'>Male
            <input type='radio'name='same' id='female'>Female
        </div>
        <p style="margin:5px 0px;color:white">ADDRESS:</p>
        <textarea id='textarea'></textarea>
        <span></span>

        <p style="margin:5px 0px;color:white">Country:</p>
        <select type='country' style="width:84%" id='select'>
            <option>England</option>
            <option>Japan</option>
            <option>America</option>
            <option>France</option>
            <option>NetherLands</option>
        </select>
        <br><br>
        <input type='submit' value='submit'>
    </form>
</div>

3 个答案:

答案 0 :(得分:1)

您的systax错误:

if (textArea.value = "")

应该是:

if (textArea.value == "")

答案 1 :(得分:0)

尝试

if (!textArea.value) {
       textArea.nextElementSibling.innerHTML = "Fill this box";
       return false;
 }

OR

if (textArea.value == '') {
       textArea.nextElementSibling.innerHTML = "Fill this box";
       return false;
 }

答案 2 :(得分:0)

您必须更改函数的名称

示例

<form action="http://google.com" id='form' onsubmit="return validate()">

function validate() {
    if (textArea.value == "") {
        textArea.nextElementSibling.innerHTML = "Fill this box";
        return false;
    }
}