Search code examples
jquerykeyuponkeyup

Key up event handler for name attribute assigned to a variable


I want to create a keyup event for every text field on my page. I will eventually have two text fields, both with different name attributes. (The example only has one text field.) Each text field will be created by pressing the button I assigned to it. Questions:

  1. Can I create one keyup event for every text field?

  2. If I call the keyup handler function before I create the text field, will the keyup function fire on the new text field?

  3. I want to use a variable name to assign the keyup handler in my function txtField. This would create a keyup event handler for text fields with the name attribute that matches the value of my fieldName variable. Is this possible? $('[name=fieldName]').keyup(myFunction) doesn't seem to work.

  4. Is there a better way to do what I'm trying to do?

    // creates a text field
    function txtField(fieldName, fieldVal){
        var objTxtField = document.createElement("input");
        objTxtField.type = "text";
        objTxtField.name = fieldName;
        objTxtField.value = fieldVal;
        return objTxtField;
    };
    
    // button fires this function
    // if there is no appended text field, create one and give it focus
    function appendNewField() {
        if ($('[name="appTxtField"]').length === 0) {
            var newTxtField = new txtField("appTxtField", "");
            $("#mainDiv").append(newTxtField);
        };
        $('[name="appTxtField"]').focus();
    };
    

Solution

    1. Yes you can ( sounds like a campaign line, I know ) you should read about direct-and-delegated-events
    2. No, binding events to non-existing element will not fire, unless you use jquery's delegation syntax. again direct-and-delegated-events

    3. There's nothing wrong with the "txtField" function, you could have used jQuery in a number of ways to achieve that, But there's no reason to do that since jQuery abstraction is unnecessary in such a simple operation.

    "appendNewField" - Can and should be improved, here's why:

    • $('[name="appTxtField"]') is looked up every time the function is called, which is terrible. this is actually looking for the node & constructing the jquery instance of that node on each run ( same goes for "mainDiv" )

    What I would do is set a reference in a "appendNewField" outer scope, and use jquery's find method on each call. For example:

    var mainDiv = $("#mainDiv");
    
    function txtField( fieldName, fieldVal ) { ... };
    
    function appendNewField() {
        if ( mainDiv.find( '[name="appTxtField"]' ).length === 0 ) {
            // utilize the chaining api and use focus directly after the appending.
            $( new txtField("appTxtField", "") ).appendTo( mainDiv ).focus();
        };
    }