15

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();
2
  • 1
    vname is undefined... there is nothing in it
    – Akki619
    Commented Sep 23, 2015 at 7:24
  • Can include #EarningTypes element html at Question ? Commented Sep 23, 2015 at 7:33

2 Answers 2

29

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, '');
  };
}
1
  • 8
    or just use this: var vname = $("#EarningsTypes").val() || "".
    – Jai
    Commented Sep 23, 2015 at 7:30
0

that means the variable vname is undefined. To this error from occurring, you can use optional chaining operator (?.) .

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

vname = vname?.trim()

Not the answer you're looking for? Browse other questions tagged or ask your own question.