translate jQuery to pure javascript
-
10-03-2021 - |
题
I have to fix some form validation but there's no jQuery included in the host page. I'd normally do something like this...
if ($("#contactNameAdd").val() !== '' || $("#contactPhoneAdd").val() !== '') {
$("#contactForm").show()
};
How can I re-write that in normal js?
解决方案
var name = document.getElementById("contactNameAdd");
var phone = document.getElementById("contactPhoneAdd");
var form = document.getElementById("contactForm");
if(name.value != '' || phone.value != '') {
form.style.display = "block";
}
其他提示
if (document.getElementById('contactNameAdd').value !== '' || document.getElementById('contactPhoneAdd').value !== '') {
document.getElementById('contactForm').style.display = 'block';
}
In plain javascript, you use document.getElementById('id') to get DOM nodes based on the id attribute. You use .value
on a DOM Input element to get its value. And you use .style
on any DOM element to set css attributes. In this case "show" means "display: block;".
if (document.getElemenById('contactNameAdd').value != '' || document.getElementById('contactPhoneAdd').value != '') {
document.getElementById('contactForm').style.display = 'block';
}
Try this - checks the 2 values then changes the style.display property of the 'contactForm'
This should do the trick.
var contactNameAdd = document.getElementById("contactNameAdd");
var contactPhoneAdd = document.getElementById("contactPhoneAdd");
if((contactNameAdd !== null && contactNameAdd.value !== '') || (contactPhoneAdd !== null && contactPhoneAdd.value !== ''))
{
document.getElementById("contactForm").style.display = 'block';
}
var contactName = document.getElementById('contactNameAdd');
var contactPhone = document.getElementById('contactPhoneAdd');
if(contactName.value !== '' || contactPhone.value !== '') {
// Different as JQuery, there will be no animation.
// I assume you use 'display:none' to hide the form.
var form = document.getElementById('contactForm');
form.style.display = 'block';
}
不隶属于 StackOverflow