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:
Can I create one keyup event for every text field?
If I call the keyup handler function before I create the text field, will the keyup function fire on the new text field?
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.
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();
};
No, binding events to non-existing element will not fire, unless you use jquery's delegation syntax. again direct-and-delegated-events
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:
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();
};
}