Paul
Paul

Reputation: 117

Problems with getElementById with jquery load

I have a page, showlist.php, which loads a set of results from a recordset. There is a search field which returns results using jquery load. This works fine for one word, but not if there is more than one word in the search query. Can anybody show how to get this to work for any search query? Must be some basic error but googling around has not helped.

Key elements of showlist.php:-

<div id="contentarea">

<script type="text/javascript"> 
   function contentloader(url){
      $("#contentarea").load(url);
 }
</script>

<input name="search" type="text" id="inputsearch"/>

<a onclick="contentloader('showlist.php?search='+document.getElementById('inputsearch').value+'')">Search</a>

</div>   

Upvotes: 0

Views: 260

Answers (4)

Lahiru Jayakody
Lahiru Jayakody

Reputation: 5410

You can use onClick listener, since you are already using jQuery. I think it is a better than using onClick attribute.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div id="contentarea">

<input name="search" type="text" id="inputsearch"/>
<a id="search">Search</a>

<script type="text/javascript"> 
   $( document ).ready(function (){     // when document ready
      $("#search").click(function(){    // add a click listner
            $("#contentarea").load(
                  encodeURI($('#inputsearch').val())   // encode input string
             );
        }
      );
    })
</script>
</div>

Upvotes: 0

nullable
nullable

Reputation: 2581

You need to call encodeURIComponent with the value to correctly format the query/search term:

<a onclick="contentloader('showlist.php?search='+encodeURIComponent(document.getElementById('inputsearch').value)+'')">Search</a>

See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

Upvotes: 1

user6304752
user6304752

Reputation: 11

type abc%20xyz in the box. if that works, maybe you need to urlencode the value.

Upvotes: 0

VRPF
VRPF

Reputation: 3118

You need to HTML encode the result of document.getElementById('inputsearch').value so that all the works are passes to the server.

See:

HTML-encoding lost when attribute read from input field

Encode URL in JavaScript?

and links therein.

Upvotes: 1

Related Questions