Image

Imageex_wronghead997 wrote in Imagejavascript 😯confused

Raw Noobage - Problem Solved!

I'm very new to Javascript, and am trying to figure out how to do some form validation with an event handler. Don't worry, I'm doing this in my spare time, not for pay. =P

I figured out how to make this work, so if anyone is interested please check it out beneath the LJ cut.


Whenever a user is finished with a field, I want it to be validated to make sure they haven't broken any rules. If an error comes up, I want to un-hide a hidden div and replace the div's contents with the error message(s). So far I've only entered one aspect of the validation to see if I can get the actual mechanisms of hiding/showing content working, but so far it's no good.

Here's my code:

    function validateInput(id)
    {
        // get input referred to by id
        var inputField = document.getElementById(id);
        
        // define error messages array
        var errors = new Array();
        
        // get errors div
        var errorsDiv = document.getElementById("javascript_errors");
        
        if (id == 'string')
        {
            var valString = inputField.value;
            if (valString.length == 0)
            {
                errors['string'] = 'No search string!';
                // alert('No search string');
                errorsBool = true;
            }
        }

        if (errorsBool == true)
        {
            var errorsText = "";
            errorsDiv.style.display = 'block';
            for (val in errors)
            {
                errorsText = errorsText + errors[val];
            }
            errorsDiv.innerHTML = errorsText;
        }
    }


Which is called on the input element via:
onblur="javascript:validateInput('string');

And then there's a div I have in the HTML markup itself:
<div id="javascript_errors" style="display:none;">
You should not see this message
</div>



In modern browsers, this will replace the text within the div with error messages. I could in theory add multiple error possibilities provided each one sets the errorsBool variable to true. I'd prefer to simply do an array join and change the visibility of the div if there are elements in the errors array, but for whatever reason neither errors.join() (the end result would always be null, even if I had elements in the array) nor if (errors.length >= 1) worked as I wanted them to. If anyone could give me some info on those two issues I'd greatly appreciate it -- they always acted as if errors was a completely empty array, no matter how much I pumped into them.


Thanks to Imagescimon for helping me figure this out!