如果需要空字段属性

if empty field attribute required

本文关键字:字段 属性 如果      更新时间:2023-09-26

我有一个登录表单,我想使字段必需,所以没有空字段被发送。

问题是密码字段,如果我使它是必需的,javascript函数将清除它,它不会被发送(所需的msg将出现在字段中)。

JS函数创建另一个隐藏字段,并将散列密码放在那里,然后必须清空密码字段(password。Value = ";).

我正在考虑使用jquery attr()如果是空的。

function formhash(form, password) {
    if (password.value = "") {
        password.attr("required", true);  // somehow this is not working...
    }
    // Create a new element input, this will be our hashed password field.
    var p = document.createElement("input");
    // Add the new element to our form.
    form.appendChild(p);
    p.name = "password";
    p.type = "hidden";
    p.value = hex_sha512(password.value);
    // Make sure the plaintext password doesn't get sent.
    password.value = "";
    // Finally submit the form.
    form.submit();
}

有什么问题吗?我还需要回去吗?

注册和修改密码等其他功能呢?我如何简化这么多if ?

你需要使用表单的onsubmit事件处理程序而不是onclick处理程序,因为required标志不能阻止click事件被触发。

那么你应该在脚本中附加你的事件处理程序,而不是内联和…

    阻止表单提交
  1. 然后对密码值进行散列。
  2. 然后重新提交表单

// Get the form element
var form = document.getElementById('login');
// Attach the submit event handler to the form element
form.onsubmit = function (e) {
    // Stop initial submission event
    e.preventDefault();
    // Get the password element
    var password = document.getElementById('password');
    // Update the password element's value with a hashed value
    password.value = hex_sha512(password.value);
    // Resubmit the form   
    this.submit();
}