简体   繁体   中英

how i can populate my search fields based on the parameters inside the URL

I am working on an asp.net web application and i have the following code to build a search fields section, which build the URL parameters based on the users' input:-

<script type="text/javascript">

$(document).ready(function(){

    $('#button').click(function(e) {  
        var count=1;
        var s="";

        var inputvalue = $("#journal").val();
        var inputvalue2 = $("#keywords").val();
        var inputvalue3 = $("#datepub").val();
        var inputvalue4 = $("#title").val();
        var inputvalue5 = $("#localcurrency").val();
        var inputvalue6 = $("#locations").val();
        var inputvalue7 = $("#dropdown1").val();
        var inputvalue8 = $("#dropdown2").val();

        if(inputvalue!=null && inputvalue!="")
        {
        s = s+ "FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue+"&";
        count++;
        }
        if(inputvalue2!=null && inputvalue2!="")
        {
        s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
        count++;
        }
        if(inputvalue3!=null && inputvalue3!="")
        {
        s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
        count++;
        }
        if(inputvalue4!=null && inputvalue4!="")
        {
        s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
        count++;
        }
        if(inputvalue5!=null && inputvalue5!="")
        {
        s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
        count++;
        }
        if(inputvalue6!=null && inputvalue6!="")
        {
        s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
        count++;
        }
        if(inputvalue7!=null && inputvalue7!="")
        {
        s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
        count++;
        }
        if(inputvalue8!=null && inputvalue8!="")
        {
        s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
        count++;
        }
        window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s);

    });
});
</script> 

       Journal <input type="text" id="journal"> 
       keywords <input type="text" id="keywords"> 




<select id="datepub">
<option value=""></option>
  <option value="1950">1950</option>
  <option value="2010">2010</option>
  <option value="2017">2017</option>
  <option value="audi">Audi</option>
</select>

title
<select id="title">
<option value=""></option>
  <option value="TestDoc">test doc</option>
  <option value="t">t</option>

</select>

localcurrency
<select id="localcurrency">
<option value=""></option>
  <option value="USD">USD</option>

</select>

locations
<select id="locations">
<option value=""></option>
  <option value="US">US</option>
  <option value="UK">UK</option>

</select>

dropdown1
<select id="dropdown1">
<option value=""></option>
  <option value="a">a</option>
  <option value="b">b</option>

</select>

dropdown2
<select id="dropdown2">
<option value=""></option>
  <option value="aa">aa</option>
  <option value="bb">bb</option>
  <option value="cc">cc</option>
  <option value="dd">dd</option>
</select>
       <button type="button" id="button">search</button>

Where when the user clicks on the search button, the user will be redirected to the /teamsites/Bib%20Test/Forms/search.aspx page with the filter parameters inside the url, which will show the related records according to the parameters being passed.

now the filtering is working well.. but the problem i am facing is that after i redirect the user to this page /teamsites/Bib%20Test/Forms/search.aspx the filter fields values (such as the local currency, locations, title, etc..) will cleared out. so can i using JavaScript to assign the filer fields their original values ? i mean can i extract the fields' values from the URL and assign it to them ? so after the user is being redirected to the /teamsites/Bib%20Test/Forms/search.aspx they can still see the filtering fields populated with the filtering values they have entered?

You can accomplish this by doing the following:

  • Parse the current page's query string to separate out its query parameters
  • Process those to match up filter field names with their values
  • Use $('#' + fieldName).val(value) to set the field values in the page

Below, as a demonstration, I'm passing in a hardcoded query string '?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b' into the populateSearchFields() function. In practice, you would use the three functions here, unmodified, but instead of that hardcoded value, pass in window.location.search .

 // input: '?a=b&b=c&e=f' // output: { a: 'b', b: 'c', e: 'f' } function buildParameterMap(queryString) { // ignore the ? at the beginning and split the query string into // pieces separated by & var pairs = queryString.replace(/^\\?/, '').split('&'); var map = {}; pairs.forEach(function(pair) { // further split each piece to the left and right of the = // ignore pairs that are empty strings if (pair) { var sides = pair.split('='); map[sides[0]] = decodeURIComponent(sides[1]); } }); return map; } // input: { FilterField0: 'Name', FilterValue0: 'Fred', // FilterField1: 'age', FilterValue1: '30' } // output: { name: 'Fred', age: '30' } function buildFilterFieldMap(parameterMap) { var maxFieldCount = 15; var map = {}; for (var i = 0; i < maxFieldCount; i += 1) { var filterFieldName = parameterMap['FilterField' + i]; if (filterFieldName) { map[filterFieldName.toLowerCase()] = parameterMap['FilterValue' + i]; } } return map; } function populateSearchFields(queryString) { // build a map from URL query string parameter -> value var parameterMap = buildParameterMap(queryString); // build a map from search field name -> value var filterFieldMap = buildFilterFieldMap(parameterMap); Object.keys(filterFieldMap).forEach(function(field) { $('#' + field).val(filterFieldMap[field]); }); } populateSearchFields('?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> Journal <input type="text" id="journal"> keywords <input type="text" id="keywords"> <select id="datepub"> <option value=""></option> <option value="1950">1950</option> <option value="2010">2010</option> <option value="2017">2017</option> <option value="audi">Audi</option> </select> title <select id="title"> <option value=""></option> <option value="TestDoc">test doc</option> <option value="t">t</option> </select> localcurrency <select id="localcurrency"> <option value=""></option> <option value="USD">USD</option> </select> locations <select id="locations"> <option value=""></option> <option value="US">US</option> <option value="UK">UK</option> </select> dropdown1 <select id="dropdown1"> <option value=""></option> <option value="a">a</option> <option value="b">b</option> </select> dropdown2 <select id="dropdown2"> <option value=""></option> <option value="aa">aa</option> <option value="bb">bb</option> <option value="cc">cc</option> <option value="dd">dd</option> </select> <button type="button" id="button">search</button> 

You want to send get request from one page to another. Do something like this:
Part I: send search request in the query string.

$(document).ready(function(){

    $('#button').click(function(e) {  
        var count=1; //out of use
        var s = []; //""; //empty array, not empty string

        var inputvalue = $("#journal").val();
        var inputvalue2 = $("#keywords").val();
        var inputvalue3 = $("#datepub").val();
        var inputvalue4 = $("#title").val();
        var inputvalue5 = $("#localcurrency").val();
        var inputvalue6 = $("#locations").val();
        var inputvalue7 = $("#dropdown1").val();
        var inputvalue8 = $("#dropdown2").val();

        if(inputvalue) // !=null && inputvalue!="") //it is redundant. null and empty string are **falsey**
        {
            s.push('journal='+inputvalue);
            //or if you wish to keep your existing format (not recommended because it would produce problems on the search page)
            //s.push("FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue);
            //count++;
        }
        if(inputvalue2) //!=null && inputvalue2!="")
        {
           s.push('keywords='+inputvalue2);
        //for existing format see previous comment
        //s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
        //count++;
        }
        /*
        //same for other vars
        if(inputvalue3!=null && inputvalue3!="")
        {
        s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
        count++;
        }
        if(inputvalue4!=null && inputvalue4!="")
        {
        s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
        count++;
        }
        if(inputvalue5!=null && inputvalue5!="")
        {
        s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
        count++;
        }
        if(inputvalue6!=null && inputvalue6!="")
        {
        s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
        count++;
        }
        if(inputvalue7!=null && inputvalue7!="")
        {
        s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
        count++;
        }
        if(inputvalue8!=null && inputvalue8!="")
        {
        s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
        count++;
        }
        */
        window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s.join('&')); //Use the array here

    });
});

Part II: Restore values in the search fields.

$(document).ready(function(){
    var query = window.location.search.slice(1); //get ?.... less **?**
    var terms = query.split('&'); //get pairs like key=value
    for(var i = 0, term; term = terms[i]; ++i){ //loop the search terms
       var detail = term.split('='); //journal=some
       $('#'+detail[0]).val(detail[1]); //set the value provided fields have the same **id**s
    }
});

Update based on comments

It is all about ASP.NET . .aspx page prepends server control ID s with parent ID s like parId$controlId . To avoid it and make the client script work set ClientIDMode="Static" attribute to the controls in search.aspx .

<asp:TextBox ID="keywords" runat="server" ClientIDMode="Static"></asp:TextBox>

Update 2

The OP is about ASP.NET . Generally speaking the result can be achieved without any client-side code.

Part I

<form method="GET" action="/search.aspx">
   <input type="text" name="keywords" />
   <select name="localcurrency">
     <option value="USD">US Dollar</option>
     <option value="EUR">Euro</option>
   </select>
   <!--other fields -->
   <input type="submit" value="Search" />
</form>

Part II

<%-- search.aspx --%>
<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["keywords"] != null)
                this.keywords.Text = Request.QueryString["keywords"];
            if (!string.IsNullOrEmpty(Request.QueryString["localcurrency"]))
                localcurrency.SelectedValue = Request.QueryString["localcurrency"];
            //other request query strings
            // DoSearch();
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="keywords" runat="server"></asp:TextBox>
            <asp:DropDownList runat="server" ID="localcurrency">
                <asp:ListItem Value="USD">US Dollar</asp:ListItem>
                <asp:ListItem Value="EUR">Euro</asp:ListItem>
            </asp:DropDownList>
        </div>
    </form>
</body>
</html>

Use this if you are not concerned about Internet Explorer or Edge.

When your page has loaded, you can read the search params with the help of URL API . Below is the code to get you started.

Note that this solution depends on being the form param's ID to be equal to the lower cased search param's name.

 $(document).ready(() => { // Change the value to window.location.href for working with browser's URL instead const href = "http://yourhost.com?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b"; // Initializes the URL object with current location const url = new URL(href); // This array will contain all the FilterFields const keys = []; for (let entry of url.searchParams) { if (entry[0].startsWith("FilterField")) { keys.push(entry[0]); } } keys.forEach(field => { // Extract the index of FilterField const idx = field[field.length - 1]; // Get the value of FilterField (this gives us the ID of the form field) const formField = url.searchParams.get(field).toLowerCase(); // Set the value of form field using .val() $("#" + formField).val(url.searchParams.get('FilterValue' + idx)); }); // Rest of the code here }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Journal <input type="text" id="journal"> keywords <input type="text" id="keywords"> <select id="datepub"> <option value=""></option> <option value="1950">1950</option> <option value="2010">2010</option> <option value="2017">2017</option> <option value="audi">Audi</option> </select> title <select id="title"> <option value=""></option> <option value="TestDoc">test doc</option> <option value="t">t</option> </select> localcurrency <select id="localcurrency"> <option value=""></option> <option value="USD">USD</option> </select> locations <select id="locations"> <option value=""></option> <option value="US">US</option> <option value="UK">UK</option> </select> dropdown1 <select id="dropdown1"> <option value=""></option> <option value="a">a</option> <option value="b">b</option> </select> dropdown2 <select id="dropdown2"> <option value=""></option> <option value="aa">aa</option> <option value="bb">bb</option> <option value="cc">cc</option> <option value="dd">dd</option> </select> <button type="button" id="button">search</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM