skip to Main Content

I have a link that looks like this.

<a id="link" href="../customer_record/?id=1&customer_id=2"></a>

I also have an input box as the following.

<input type="text" id="search">

I am trying to get jQuery to add a parameter to the link as the user types into the input box.

// add search to link
$('#search').on('keyup', function(){
    var href = $('#link').attr("href");
    var data = $(this).val();
  $('#link').attr('href', href + '&search-string=' + data);
});

I don’t think I am far away but I just can’t get it to work.

Any help would be gratefully appreciated.

2

Answers


  1. u almost there

        <a id="link" href="../customer_record/?id=1&customer_id=2"><input type="text" id="search"></a>
    
    $(document).ready(function(){
        // Store the original URL
        var originalHref = $('#link').attr("href");
    
        $('#search').on('keyup', function(){
            var data = $(this).val();
            
            // Create new URL by appending search string to original URL
            var newHref = originalHref + '&search-string=' + encodeURIComponent(data);
            
            // Update href attribute
            $('#link').attr('href', newHref);
    
    Login or Signup to reply.
  2. You can set the URL query string with URLSearchParams: set() method of URL API. See the following example.

    // add search to link
    $('#search').on('keyup', function() {
      var href = $('#link')[0].href;
      var urlHref = new URL(href);
      urlHref.searchParams.set('search-string', $(this).val());
      $('#link').attr("href", urlHref);
      console.log($('#link').attr("href"));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a id="link" href="../customer_record/?id=1&customer_id=2">link</a>
    <input type="text" id="search">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search