Changing css with javascript

In cases like this, the elements collection of the form is used, and it’s better to use the dot property instead.

if (form.elements.firstname.value.length != 8) {

Because that’s looking like a trainwreck (look at all of those .dot couplings) which can lead to misunderstanding and confusions, you can use a function to check the value instead.

function validateFirstname(form) {
  var firstname = form.elements.firstname;
  return firstname.value.length === 8;
}

if (!validateFirstname(form)) {

Would validateFirstName(form) go inside the eventListener() ?

It’s better for it to be outside the event listener, as the functions in there become clutter, distracting away from what the event listener is supposed to do.

A good place to put the function is somewhere above the even listener, perhaps just below the comment about validation.

Something like this?

function validateFirstName()
{
	// validation goes here.
}
		
form.addEventListener('Submit',function(event)
{
	validateFirstName();	
})

Yes that right, although in the event listener validateFirstName() would be used as the condition of an if statement.

By the way, wrapping code with three backticks (that’s the key just below the Esc key) results in the code looking better when you post it.

For example, when you wrap the code with three backticks:

```
// a comment
var someVariable = “Some text”;
```

The code ends up looking like this:

// a comment
var someVariable = "Some text";

That condition being if the field text value is not equal to “” I assume.

There’s a couple of options here.

One is to use a function that checks if the firstname is invalid, but using negative terms as a function name becomes cumbersome, not only in how do you give it a good name, but you need to remember that this function returns true when things are bad, so false means that it’s good, which gets confusing too.

function notValidFirstName() {
  ...
}
if (notValidFirstName(form)) {

Instead of that, it’s more beneficial to avoid negative terms in function names, because it’s easier to give good and meaningful names to the functions, and the exclamation mark in the condition tells you exactly what you need to know.

function validFirstName() {
  ...
}
if (!validFirstName(form)) {

Oh yes, and when showing code in posts, you can use ```html or ```javascript or ```css which helps to provide better color coding for the code.

A ```javascript example of what you type, and how it looks

For example, here is how you would type it in the reply box:

```javascript
function someFunctionName(param) {
}
```

and here is how it looks in the preview, and in your post.

function someFunctionName(param) {
}

A plain ``` example of what you type, and how it looks

But when you use ``` without mentioning the coding language, it only does a basic job of it.

Here’s what you would type in the repy box

```
function someFunctionName(param) {
}
```

And here’s how it ends up looking in the preview and in your reply.

function someFunctionName(param) {
}

Note: I’ve been using \ as an escape character, where \`\`\` forces ``` to show as text on the screen, for the purpose of demonstrating what you would type.

2 Likes

I tried this to start with, baby steps.

form.addEventListener('Submit',function(event)
		{
			alert();	
		})

If the alert executed I would replace it with the function, it didn’t. What am I missing?

Perhaps that the event name should be in lowercase?

You will also want to prevent the default behaviour of the form from occurring, that default behaviour being to submit the form. That will help to prevent the page from navigating somewhere else, while you are testing.

form.addEventListener("submit", function(evt) {
    evt.preventDefault();
    alert();	
});

Also when using it to validate things later on, you don’t want the form submitting until you are satisfied that everything validates properly, at which point you can run form.submit() from the event listener to submit the form.

That didn’t do anything. Frustrating.

Okay, let’s see the HTML and JavaScript code that you’re working with.

Are you developing the code on codePen or jsfiddle where you can link us to the code that you’re working with?

Good one. I see that you are using a scripting variable of form, but you haven’t told the script what that form variable refers to.

It’s obvious to us of course, but not to JavaScript.

The form has an id of “validate1” so you could use that to easily gain a reference to the form.

var form = document.querySelector("#validate1");
form.addEventListener("submit", function (evt) {

I know where the problem is, just not what it is. I put an alert between var form and addEventListener and one after the preventDefault(); Only one alert executed.

Is your code as it’s shown on the pastebin page? Because if so, the scripting will show on the screen as if it were text, instead of scripting, as can be seen at https://jsfiddle.net/0mdL4L7L/

Putting the scripting in <script> tags results in the scripting working properly. https://jsfiddle.net/0mdL4L7L/1/

The web page won’t let the submit event occur until the required parts of the form have been done, such as the radio input and the number field. After that, submitting the form shows the alert button.

Here’s an update where the scripting is in its own scripting area. https://jsfiddle.net/0mdL4L7L/2/
The benefit of this is that it’s easier to keep the HTML code visible while working on the script, and the script can be configured to run on the load event, or at the end of the body, which is the preferred technique these days.

1 Like

Progress. I got the eventListener to call the validate function above it which executed an alert. Cheers.

1 Like

If the form submits I can execute Javascript using echo. I tried this
echo '<script>function DisplayError(){change css here}';
but it doesn’t execute. How do I get it to execute?

IDK… I’d rather not hard-code name properties in the middle of the lookup chain like this. It couples the JS and the markup very tightly; my suggestion would be to at least abstract this away so you can maintain the props in a separate place, like e.g.

var NAMES_TO_CHECK = ['firstname', 'lastname']
var myForm = document.getElementById('my-form')

var validateInput = function (form, name) {
  return form.elements[name].value.length
  // Depending on your trust in the markup, this might be better though:
  // return form.elements[name] && form.elements[name].value.length
}

var hasMissingFields = NAMES_TO_CHECK.some(function (name) {
  return !validateInput(myForm, name)
})

if (hasMissingFields) {/* ... */}

Even better though would be looping over elements directly; if the required attribute is too generic for your purposes, you might use a dedicated class or data-* attribute for this:

var inputsToCheck = myForm.querySelectorAll('[data-validate]')

var namesToCheck = Array.from(inputsToCheck).map(function (input) {
  return input.name
})

var validateInput = function (form, name) {
  return form.elements[name].value.length
}

var hasMissingFields = namesToCheck.some(function (name) {
  return !validateInput(myForm, name)
})

if (hasMissingFields) {/* ... */}

Or a bit nicer…

var validateForm = function (form) {
  return function (name) {
    return form.elements[name].value.length
  }
}

var validateInput = validateForm(myForm)
var hasMissingFields = !Array.from(namesToCheck).every(validateInput)

This way, the information which inputs to check is entirely in the markup and you don’t have to adjust the JS at all in case that might change – you don’t have to worry if the element in question even exists.

You’ll have to actually call that function when the validation fails; like, with the above example:

if (hasMissingFields) {
  displayError()
}

(Note that by convention function names are lowerCamelCased unless they are supposed to be used as constructors, i.e. called with the new keyword.)

That’s the part I’m trying to figure out, if the validation fails in PHP, how do I call the Javascript function that changes the css to display errors?