Ch Hong
Ch Hong

Reputation: 378

Javascript to remove spaces from .value

//loop thought all the sku field
$('.optionSku').each(function() {

    //if found field are empty
    if (jQuery.trim(this.value) == "") {

        //loop thought all the name field to copy to the empty field
        $('.optionName').each(function() {

            if ($(this).closest("tr").find(".optionSku").val() == "") {

                empty++;
                $(this).closest("tr").find(".optionSku").val($(this).val());
            }

        });
    }
})

How to remove space from this.value using JQuery? I try to put if (jQuery.trim(this.value) == ""), but it cannot remove the inline space and removes the leading and trailing spaces only.

Upvotes: 2

Views: 2503

Answers (5)

Sunil B N
Sunil B N

Reputation: 4225

this.value =  this.value.trim(); 
//you need to assign the trimmed value back to it.

Note that trim may not be available in IE < 9 version. So you can use:

this.value = $.trim(this.value);

Upvotes: 3

WLatif
WLatif

Reputation: 1388

The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
if you want to remove leading and trailing spaces use

//loop thought all the sku field
 $('.optionSku').each(function() {
    //if found field are empty
    if ($.trim(this.value)=="") {
       //loop thought all the name field to copy to the empty field
       $('.optionName').each(function() {
          if ($(this).closest("tr").find(".optionSku").val() == "") {
             empty++;
             $(this).closest("tr").find(".optionSku").val($(this).val());
          }
       });
    }
 });

if you want to inline spaces use

//loop thought all the sku field
 $('.optionSku').each(function() {
    //if found field are empty
    if (this.value.trim()=="") {
       //loop thought all the name field to copy to the empty field
       $('.optionName').each(function() {
          if ($(this).closest("tr").find(".optionSku").val() == "") {
             empty++;
             $(this).closest("tr").find(".optionSku").val($(this).val());
          }
       });
    }
 });

Upvotes: 2

Kushal Jain
Kushal Jain

Reputation: 3186

This is how trim work in javascript.

var val = this.value.trim();

Upvotes: 1

Paras Wadhwa
Paras Wadhwa

Reputation: 64

.replace(/ /g,'') The g character means to repeat the search through the entire string. If you want to match all whitespace, and not just the literal space character, use \s as well:

.replace(/\s/g,'')

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48417

Try this:

if(this.value.trim()==""){
    //code here
}

Upvotes: 0

Related Questions