简体   繁体   中英

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.

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);

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());
          }
       });
    }
 });

这就是修剪在 javascript 中的工作方式。

var val = this.value.trim();

Try this:

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

.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,'')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM