vijaus
vijaus

Reputation: 1

trim value in jquery

this is my input text box

input type="text" id="country" name="country" class="input_text"

am fecting values from database country and state from jquery

var country;
jQuery(function(){
$("#country").autocomplete("countries.jsp");
});

it is working fine but the problem is onclick of drop down value it will display that value in textbox,while displaying in textbox it is taking 5 extra space in between country and state, any body tell me how can i trim this value having only one space in between country and state

EDIT

yes it is from server only in text box it is taking to much of space

try { 
    ResultSet rs = null; 
    java.sql.Statement stmtGet = null; 
    stmtGet = pg.gclsWFDbUtil.getDbConnection().createStatement(); 
    String query = request.getParameter("q").toLowerCase(); 
    String QueryString = "Select country,state from emp_master where country like '" 
        + query +"%'"; 
    rs = stmtGet.executeQuery(QueryString); 
    response.setHeader("Content-Type", "text/html"); 
    while (rs.next()) { 
         out.print(rs.getString(1)+""); 
         out.print(rs.getString(2)+"\n");
    }

Upvotes: 0

Views: 2550

Answers (3)

Ady Ngom
Ady Ngom

Reputation: 1302

Use jQuery trim, plain and simple: http://api.jquery.com/jQuery.trim/

alert($.trim('     so much space around me    '));

Upvotes: 0

Blender
Blender

Reputation: 298246

Here's what I would do clientside. Ideally (no, practically), this should be done serverside, as this won't work at all for people without JavaScript and Russian hackers who want to pwn your webapp:

String.prototype.innerTrim = function() {
  var temp = this;

  while (temp.indexOf('  ') != -1) {
    temp = temp.replace('  ', ' ');
  }

  return temp;
};

alert('t           es           t'.innerTrim());
// Outputs: t es t

Amazingly, this thing works almost just as fast as a regex solution. Your browser will freeze for ~10 seconds while it tests, but it'll output the execution time of each iteration: http://jsfiddle.net/Blender/UrQNs/

Upvotes: 1

Mark Keats
Mark Keats

Reputation: 1400

You could use some Regex to replace multiple whitespace characters with a single space using this JavaScript:

str = str.replace(/\s{2,}/g,' ');

You should really do this king of processing serverside so you have the data in the correct format before sending to the client.

Upvotes: 1

Related Questions