I am confused on how the .val() method in jQuery handles whitespace (if it is a jQuery problem at all).
My example is using an AJAX suggestion box feature which I’m slowly developing. It uses Codeigniter as the framework.
I have this jQuery code:
$(document).ready(function(){
$("#suggestbox").hide();
$("#searchboxinput").live("keyup", function(){
if ($("#searchboxinput").val().length==0){
$("#suggestbox").fadeOut(100);
}else{
$("#suggestbox").fadeIn(100);
$("#sugresultcontain").load('http://localhost/ajaxtest/ajaxhandle/suggest/'+$("#searchboxinput").val()+' #loadsuggest');
};
});
});
The ‘#suggestboxinput’ is a text input as shown:
<div id="content" class="clear">
<div id="searchwrap" class="clear">
<div id="searchbox" class="float-left"><input id="searchboxinput" name="" value="" type="text"></div>
<div id="searchbutton" class="float-right"><input id="searchbuttoninput" name="" type="button" value="Go"></div>
</div>
<div id="suggestbox" class="clear">
<div id="suggesthead">Suggestions:</div>
<div id="sugresultcontain"></div>
</div>
</div>
I then have (Using code igniter) a method which handles the .load() as shown:
public function suggest($q=''){
$suggest = $this->ajax_handle->suggest();
for($i=0; $i<count($suggest); $i++){
$db[$i] = $suggest[$i]['firstname'].' '.$suggest[$i]['lastname'];
}
if(strlen($q)>0){
$sugstr = '';
$e = 0;
for($f=0; $f<count($db); $f++){
if (strtolower($q)==strtolower(substr($db[$f],0,strlen($q)))){
$sugresult[$e] = $db[$f];
$e++;
}
}
if(isset($sugresult)){
$data['sugresult'] = $sugresult;
$this->load->view('ajaxref/suggest', $data);
}else{
$this->load->view('ajaxref/suggest');
}
}else{
$this->load->view('ajaxref/suggest');
}
}
This works almost as intended, if I load the page then use the text input the names from the database do show (according to text field). It works fine if I type the first name and will continue to show no matter how many spaces I put after the field (which is perfect).
However, the problem lies with typing the surname even after just a single space (Dominic Sore) or even just the first letter or the last name (Dominic S). No names show in the suggestion box.
I had read that using a ‘+’ symbol in the input box will work. I tested it, and it did work (Dominic+Sore outputs Dominic Sore in suggestion box). Understandably though, I cannot have users type a ‘+’ for every space they want to use.
So I am just wondering how do I handle this? I’ve been reading a lot but I cannot find a solution.
Thanks.
try
$.trimmethod: