Javascript why can not access file input value with customized function?

I made something like jquery $(‘#aControl’).val(‘’); .

This works for all controls but not for a file input with id : $(‘#fileInputControl’).

var $ = function( element_id )
{
    return new GetControl( element_id );
}

function GetControl( element_id ) {
var _elemId;

if(element_id instanceof HTMLElement){_elemId="#"+element_id.getAttribute('id'); }else{_elemId=element_id;}

    this.node = document.querySelector(_elemId);

       //....Other things...//

    this.val = function(arg = null) { if(arg == null){return this.node.value; }else{  this.node.value = arg;}};

}

The error I get at console log :

Uncaught TypeError: $(…).val is not a function
at HTMLInputElement.onchange

My first question is why are you defining the dollar sign as a function?

IMHO this seems like a very poor decision. The error is because as you have written it, that function does not have a “val” method.

I guessing you want to use jQuery, that typically is “$”, and that you would do better to rename the function to something else. Otherwise you will need to change that function to do what you want it to do and forget about using any jQuery code that depends on what it doesn’t have.

1 Like

GetControl is a Function.
You’re trying to invoke it as a Class.

Change your declaration for GetControl, or the invocation, or… just in general don’t use jQuery’s syntax, for sake of not confusing every person who reads your code afterwards.

The code you posted by itself won’t throw any errors, even for file input elements. Where is the part where you are actually assigning an onchange handler?

Such constructor functions are a valid way to create object instances; actual classes have only been introduced to JS in 2015, and are mostly syntactic sugar for this.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.