Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'trim' of undefined in Jquery

In Jquery replace the space character to '%20'. but working in other forms not in single form. in consists header as

<header>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
</header>

the code using in other form its working well.

var vname = $("#EarningsTypes").val();
vname = vname.trim().replace(/ /g, '%20');
jQuery.noConflict();
like image 703
Saravanan Arunagiri Avatar asked Sep 23 '15 07:09

Saravanan Arunagiri


People also ask

How do you fix undefined properties Cannot be read?

To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method. Copied!

How do you trim in Javascript?

String.prototype.trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).


1 Answers

You're getting error

Uncaught TypeError: Cannot read property 'trim' of undefined in Jquery

that means, the variable vname is undefined. To prevent this error from occurring, you can use the ternary operator to set the default value of the string to empty string when it is undefined.

var vname = $("#EarningsTypes").val() == undefined ? '' : $("#EarningsTypes").val().trim();
vname = vname.replace(/ /g, '%20');

You can also use || to set the default value

var vname = $("#EarningsTypes").val() || '';

If you're using an older browser that doesn't support trim, you can use polyfill from MDN

if (!String.prototype.trim) {
  String.prototype.trim = function() {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
like image 173
Tushar Avatar answered Sep 20 '22 15:09

Tushar