如何在 JS 上的 A 边 else 条件中添加类

how to add a class in side a else condition on js

本文关键字:条件 else 添加 JS 上的      更新时间:2023-09-26
function check_empty() {
if (document.getElementById('CompanyName').value == "" || document.getElementById('ContactName').value == "" || document.getElementById('Address').value == "" || document.getElementById('PhoneNumber').value == "" || document.getElementById('Email').value == ""){
alert("Fill All Fields !");
} else {
/*want to add a class="my" */
alert("Form Submitted Successfully...");
}
}
/*html code*/
<a href="javascript:%20check_empty()" class="my">Submit to download</a>

当我单击链接"提交下载"时,调用"check_empty()",如果所有filds都为空,它将询问"填写所有字段!"否则我想称一个类为"my",它现在位于html元素上。如何在js上添加它?

更新:

我认为您正在寻找的是如何使用 attr placeholderrequiredautofocus您不需要 JavaScript 来检查输入是否为空,请尝试以下操作:

<form>
    <input id=CompanyName type=text placeholder=CompanyName required autofocus />
    <input id=ContactName type=text placeholder=ContactName required />
    <input id=Address type=text placeholder=Address required />
    <input id=PhoneNumber type=text placeholder=PhoneNumber required />
    <input id=Email type=text placeholder=Email required />
    <input type=submit value=send />
</form>

现在,您可以在表单准备就绪时执行某些操作

function sendMyForm(event){
    alert("Form Submitted Successfully...");
}
var sendForm = document.querySelector("form");
sendForm.addEventListener("submit", sendMyForm, false);
<form>
    <input id=CompanyName type=text placeholder=CompanyName required autofocus />
    <input id=ContactName type=text placeholder=ContactName required />
    <input id=Address type=text placeholder=Address required />
    <input id=PhoneNumber type=text placeholder=PhoneNumber required />
    <input id=Email type=text placeholder=Email required />
    <input type=submit value=send />
</form>

使用classList

 document.querySelector("#CompanyName").classList.add('my');

所以你的代码可能看起来像这样

function check_empty() {
   if (document.getElementById('CompanyName').value == "" || document.getElementById('ContactName').value == "" || document.getElementById('Address').value == "" || document.getElementById('PhoneNumber').value == "" || document.getElementById('Email').value == ""){
      alert("Fill All Fields !");
   } else {
      /*want to add a class="my" */
      document.querySelector("#CompanyName").classList.add('my');
      /*document.getElementById("CompanyName").classList.add('my')*/
      alert("Form Submitted Successfully...");
   }
}

您是否在问如何一键调用两个 JavaScript 函数:

如果是这样.. 试试这个...

<a href="javascript:void()" onClick="return check_empty() ? my() : false"> Submit to download </a>