1

My search button is not working. When I try to manually enter the URL it is giving me the required result. Any help is very much appreciated.

<script type="text/javascript">
    function Search() {
        var st= document.getElementById("Searchtxt").value;
        var cd = document.getElementByID("coldropdown").value;
        var url="";
        
        if(st!=""){
            if(cd=="Title"||cd=="Last_x0020_Name"||cd=="Country"||cd=="Designation"){
                url="FilterField1="+cd+"&FilterValue1="+st;
                window.location.href="AllItems.aspx?"+url;
            }
            else{
                    url="FilterName="+cd+"&FilterMultiValue=*"+st+"*";
                    window.location.href="AllItems.aspx?"+url;
            }
        }
        else {
                return false;
        }
    }
    function Clear(){
        window.location.href="AllItems.aspx";
    }
    </script>
       
            Search Field:<select id="coldropdown">
            <option value="Title">First Name</option>
            <option value="Last_x0020_Name">Last Name</option>
            <option value="Country">Country</option>
            <option value="Designation">Designation</option>
            </select>
            Search text:<input id="Searchtxt" type="text"/>
            <input id="btnsearch" onclick="return Search();" type="button" value="Search"/>
            <input id="btnClear" onclick="return Clear();" type="button" value="Clear"/>

1 Answers1

0

You don't have access to the Search or Clear functions within the onclick attributes. This answer gives a detailed explanation on how to call a JavaScript function in response to an HTML event: https://stackoverflow.com/a/1947531/8360496

Basically, you need to add an event listener on your buttons and specify which function to call in response to an event. Similar to this:

  <body>
    <input
      id="btnsearch"
      type="button"
      value="Search"
    />
    <input
      id="btnClear"
      type="button"
      value="Clear"
    />
    <script>
      function clear() {
        console.log("clearing!");
      }
      function search() {
        console.log("searching!");
      }
      const searchButton = document.querySelector("#btnsearch");
      const clearButton = document.querySelector("#btnclear");

      searchButton.addEventListener("click", search);
      clearButton.addEventListener("click", clear);
    </script>
  </body>

Codesandbox link

Robert Cooper
  • 2,160
  • 1
  • 9
  • 22
  • Thanks Robert for your input. I don't think so that the problem as my clear function is working. My search function is not working I guess I am doing something wrong in my search function. I don't know much of HTML and Java but my logic seems to be correct. Is there any syntax issue? – Ankita Joshi Jul 16 '20 at 20:23