Home > Back-end >  Intercept form submission, check submitted value and show easter egg
Intercept form submission, check submitted value and show easter egg

Time:01-21

jQuery(document).ready(function() {
  jQuery(".search-form").submit(function(e) {
    // if submitted value = "easter egg"
    //    e.preventDefault();
    //    show easter egg
    // else do nothing (let the form be submitted as usual)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://galina.xyz/" method="get" id="adminbarsearch">
  <input  name="s" id="adminbar-search" type="text" value="" maxlength="150" />
  <label for="adminbar-search" >Search</label>
  <input type="submit"  value="Search" />
</form>

Could you help me organize this? I failed to find out the submitted value in 'e'.

CodePudding user response:

Can't find it because your class selector is looking for search-form, but it is not set, so add it

e.g. <form ..

Then use Event.preventDefault() in the listener to prevent the submission

e.g. e.preventDefault();

jQuery(document).ready(function() {
  jQuery(".search-form").submit(function(e) {
    const searchVal = $(this).find('input[type=text]').val();
    if (searchVal == 'easter egg') {
      e.preventDefault();
      console.log('surprise');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form  action="https://galina.xyz/" method="get" id="adminbarsearch">
  <input  name="s" id="adminbar-search" type="text" value="" maxlength="150" />
  <label for="adminbar-search" >Search</label>
  <input type="submit"  value="Search" />
</form>

CodePudding user response:

In jQuery you're creating a submit function for .search-form, but in your HTML, there is no element with that class. You should create submit function for your form which has id="adminbarsearch":

jQuery(document).ready(function() {
  jQuery("#adminbarsearch").submit(function(e) {
    if ($("#adminbar-search").val() === "easter egg")
    {
      // show easter egg
      console.log("Easter Egg");
    
      e.preventDefault();  
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://galina.xyz/" method="get" id="adminbarsearch">
  <label for="adminbar-search" >Search</label>
  <input  name="s" id="adminbar-search" type="text" value="" maxlength="150" />
  <input type="submit"  value="Search" />
</form>

  •  Tags:  
  • Related