Home > Enterprise >  html form input method get prevent name in url if value is not filled
html form input method get prevent name in url if value is not filled

Time:02-27

Let's say this is my html in reactjs/jsx:

<form action="/search-list" method="GET">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname"><br><br>
  <input type="submit" value="Submit">
</form>

and when i click on the submit buttoin without inputing anything, it make the url like this fname=&lname=

and when i fill anly fname and submit, the url become like this fname=JhonDoe&lname=

Notice here, i didn't fill the lname, yet the lname is here in url which i dont want.

I want, if a field has value, that field should be in url as query params, if not field, that field should not be in url query params.

is it possible to do? how can I do it? All the fields should be optional.

CodePudding user response:

You can use this plain JavaScript to remove the empty inputs from submitting.

<form method="GET" id="myForm">
    <label for="fname">First name:</label><br>
    <input type="text" id="fname" name="fname"><br>
    <label for="lname">Last name:</label><br>
    <input type="text" id="lname" name="lname"><br><br>
    <input type="submit" value="Submit">
</form>

<script>
    Form = document.getElementById("myForm");
    Form.addEventListener('submit',()=>{
    if(Form.fname.value == ""){
    Form.fname.name ="";
    }

    if(Form.lname.value == ""){
    Form.lname.name ="";
    }


    Form.submit();
    });

</script>
  • Related