Search code examples
javascripttargetevent-listenerobject-literal

Trying to use element ID to access object values native javascript


I'm trying to write some code to validate a form. I only want to use native js (ie no jQuery etc) and in addition I want to steer clear of inline events.

The (simplified version of the) form looks as follows:

<body onload="addListener()">
<div class="center">
    <form method="get" name="signUpForm">
        <input type="text" id="firstName"><br />
        <input type="text" id="lastName"><br />
        <input type="text" id="age"><br />
        <input type="submit" value="Submit">
    </form>
</div>

What I've then done is created an object to contain relevant information as it pertains to each field (have just added the initial one here to give you the idea:

var Field = { req: true, 
              minlength: 2,
              maxlength: 20,
              errorMessage: "",
              regex: /[^a-zA-Z- ]/}

var firstName = Object.create(Field);
    firstName.maxlength = 30;
    firstName.errorMessage = "Please enter a first name between one and twenty letters. Please use only uppercase and lowercase letters spaces and hyphens.";
    firstName.regex = /[^a-zA-Z- ]/;

What I now want to do is use the id of the field which triggers the event to access the information contained in the Field object.

The two very simple functions I've written thus far tom attempt this are:

function addListener(){
    document.body.addEventListener('keyup', eventIdentify);
}

function eventIdentify(){
    var target = event.target || event.srcElement;
    var id = target.id
    console.log(id.maxlength);
}

However and this where it becomes a bit of a nightmare, id.maxlength keeps returning undefined.

If I try it with: "console.log(firstName.maxlength);" then it's fine but obviously that defeats the point. Not sure what's going on here, I suspect it's something to do with the id being used to reference two different things (the element id and the object) but I'm pretty new to this and not sure.

Would gratefully appreciate it if someone couold point me in the right direction.

Thanks in advance Stef


Solution

  • target.id is a string, and as such it does not have a maxlength property. A quick solution would be to access de variable that is named as your id:

    console.log(window[target.id].maxlength)
    

    Still, a better way would be to create an object and incluse the other objects you already have:

    var obj={};
    obj.firstName=firstName;
    

    And then you can do:

    console.log(obj[target.id].maxlength)