skip to Main Content

I’m following the answer here to use the selection from a dropdown in a URL. I am using asp.net core, using:

asp-page="/Page" asp-page-handler="Action"

To do the redirect

The script below (from the link above) works great, except if you select an item from the dropdown then select a different one (and on and on), it appends both to the URL.

<script>
$("[name=selectedAnalyst]").on("change", function () {
    var analystId = $(this).val();
    var accept = $(this).closest('td').next().find("a")[0];
    var oldUrl = accept.href;
    var newUrl = oldUrl + "&analystid=" + analystId;
    $(accept).attr("href", newUrl);
})

I tried scrubbing the parameter in question (using params.delete) but it’s not working:

<script>
$("[name=selectedAnalyst]").on("change", function () {
    var analystId = $(this).val();
    var accept = $(this).closest('td').next().find("a")[0];
    var oldUrl = accept.href;
    let params = new URLSearchParams(oldUrl.search);

    params.delete('analystid')
    var newUrl = oldUrl + "&analystid=" + analystId;

    $(accept).attr("href", newUrl);
})

Is there a way to get the above script to work how I envision, or a better way to do this?

Thank you

2

Answers


  1. Chosen as BEST ANSWER

    Building on what Ruikai Feng posted I think this is working:

    $("[name=selectedAnalyst]").on("change", function () {
    var analystId  = $(this).val();
    var accept = $(this).closest('td').next().find("a")[0];
    var oldUrl = accept.href;
    var a = oldUrl.indexOf("analystId ");
    if (a == -1) {
        var newUrl = oldUrl + "&analystId =" + analystId ;
    }
    else {
        var newUrl = oldUrl.substring(0, a - 1) + "&analystId =" + analystId;
    }
    
    $(accept).attr("href", newUrl);
    })
    

  2. it seems that

    let params = new URLSearchParams(oldUrl.search);
    
        params.delete('analystid')
    

    does not work
    I tried with the codes and it could work

    <script>
            $("[name=selectedAnalyst]").on("change", function () {
                var analystId = $(this).val();
                var accept = $(this).closest('td').next().find("a")[0];
                var oldUrl = accept.href;
                var a = oldUrl.indexOf("analystid");
                console.log(a);
                if (a == -1)
                {
                    var newUrl = oldUrl + "&analystid=" + analystId;
                }
                else
                {
                    var newUrl= oldUrl.substring(0, oldUrl.length - 1) + analystId;
                }          
                
                console.log(newUrl);
                console.log(oldUrl);           
                $(accept).attr("href", newUrl);
            })
        </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search