0

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?

1
  • 1
    Its almost as if jQuery makes people lazy ... this is very simple ... any JavaScript developer should really know this kind of stuff .... Commented Nov 28, 2011 at 9:16

5 Answers 5

1
var name = document.getElementById("contactNameAdd");
var phone = document.getElementById("contactPhoneAdd");
var form = document.getElementById("contactForm");

if(name.value != '' || phone.value != '') {
   form.style.display = "block";
}
Sign up to request clarification or add additional context in comments.

Comments

1
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;".

Comments

0
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'

Comments

0

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';
}

3 Comments

getElementById <- lowercase 'g'
Thanks ManselUK, didn't notice my typo at the top.
i didnt want to edit you post - thought it was a bit cheeky !
0
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';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.