Timothy Coetzee Timothy Coetzee - 2 months ago 7
Ajax Question

Ajax / Jquery Add clicked link to text input area

Im new to jquery and even newer to ajax so please bear with me here.

I have the following script which fetches data (branch names) asynchronously via database:

$(document).ready(function () {
$("#pickup").on('keyup',function () {
var key = $(this).val();

$.ajax({
url:'modal/fetch_branch.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
}
});
});
});

<input type="text" class="form-control empty" name="keyword" id="pickup" placeholder="&#xf041;"/>


When the user types,
S
as an example all branches containg
S
will be returned as can be seen in the image below:

enter image description here

WHAT I WOULD LIKE TO DO



I need to find a way to modify my script, to


  • allow user to click the link, for desired result (branch)

  • When link (branch) is clicked it needs to get appended to the form input field as the value of
    pickup



Any help or advise on how the above can be achieved, much appreciated.

P.S returned data (names) are
<a>
elements , thus they are links.

Answer

As far as I understand data in success:function (data) contains some <a> elements, so you need to add a handler to process click on these elements:

// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
    // take `text` of a clicked element and set it as `#pickup` value
    $( "#pickup" ).val( $( this ).text() );
    // return false to prevent default action
    return false;
});