0

I'm new to the wordpress world. As a starter theme I was suggested to use the basic one given by underscores.me. The search bar is fundamental for my site, so I would like to customize it in order to accept only a specific input from users.

In particular, the only accepted input have to be of the form xay where x and y are numbers between 1 and 999, and a has to be the letter a.

Examples of accepted input: 1a2, 222a999, 130a28.

I read articles How do I add a simple jQuery script to WordPress? and How to Properly Add jQuery Scripts to WordPress on how to properly add a jQuery script in wordpress, but it doesn't work.

This is what I did so far:

Since the theme doesn't have the searchform.php file, I'm using the default search bar. In the folder wp-content\themes\mytheme\js I created the file searchbox.js and in it I wrote the following code

jQuery(function(){
        $("#btn-search").click(function(){
        $(".error").hide();
        var hasError = false;
        var searchReg = /^[0-9]+$/;
        var searchVal = $("#search-text").val();
        if(searchVal == '') {
            $("#search-text").after('<span class="error">Please enter a search term.</span>');
            hasError = true;
        } else if(!searchReg.test(searchVal)) {
            $("#search-text").after('<span class="error">Enter valid text.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});

I found this code here, it will first check that text has been entered and return an error message if the search box is empty. Then it checks that the entered text only contains numeric characters. If either of these validation checks return an error message, then the form submission is stopped with the “return false” command.

This is not exactly what I'd like to have for my search bar, I used it just to try how to add a jQuery script.

Then in the functions.php file I wrote, at the top, this code

function add_my_script() {
   wp_enqueue_script(
       'searchbox', // name your script so that you can attach other scripts and de-register, etc.
       get_template_directory_uri() . '/js/searchbox.js', // this is the location of your script file
       array('jquery') // this array lists the scripts upon which your script depends
   );
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );

Then I tried to do a search on my site, I wrote nothing in the search box and clicked the search button. No error message appeared, and all the posts on the site where shown. Moreover, I wrote in the search box a word (which would not be possibile to search for since the command var searchReg = /^[0-9]+$/; should only accept numeric input, but again no error messages and pages where shown.

What I did wrong?

EDIT

The problem was due to

  • wrong search field and search button IDs in the jQuery script
  • Uncaught TypeError: $ is not a function

Solution

  • substitute #btn-search with .search-submit, and #search-text with .search-field
  • substitute $ with jQuery
  • 1
    I don't think you need to edit the form itself but add validation to the input. You could use jQuery to validate this and display an error message if its not in the correct format. You could also use regular expressions and PHP to validate it. – RiddleMeThis May 29 at 17:16
  • Thank you, could you link me some guides to do it? – sound wave May 29 at 19:46
  • 1
    It isn't working isn't very helpful. What isn't working? Debug your code, put breakpoints in and see where its hitting. Also, I think you need to setup your regExp like this - var searchReg = new RegExp('/^[0-9]+$/'); – RiddleMeThis May 30 at 14:26
  • 1
    It doesn't sound like your script is being called. I tested your code and everything seems to work except the regExp. View the source and make sure your path is correct to /js/searchbox.js. Then you can add some console.log('tests'); in different places to see if its hitting – RiddleMeThis May 30 at 16:31
  • 1
    click on the link to your js file in the above screenshot to make sure it isnt giving you a 404. – RiddleMeThis May 30 at 19:00
0

This code does the job (there is p instead of a)

jQuery(function(){
        jQuery(".search-submit").click(function(){
        jQuery(".error").hide();
        var hasError = false;
        var searchReg = /^[p0-9]+$/;
        var searchVal = jQuery(".search-field").val();
            var searchLen = searchVal.length;
            var num1 = ['1','2','3','4','5','6','7','8','9'];
            var num0 = ['0','1','2','3','4','5','6','7','8','9'];
        if(searchLen < 3) {
            jQuery(".search-field").after('<span class="error">Enter at least 3 characters.</span>');
            hasError = true;
        } else if(searchLen > 7) {
                  jQuery(".search-field").after('<span class="error">Enter no more than 7 characters.</span>');
            hasError = true;
        } else if(num1.indexOf(searchVal.charAt(0)) == -1) {
                  jQuery(".search-field").after('<span class="error">First character has to be a digit between 1 and 9.</span>');
            hasError = true;
            } else if(num0.indexOf(searchVal.charAt(searchLen-1)) == -1) {
                  jQuery(".search-field").after('<span class="error">Last character has to be a digit between 0 and 9.</span>');
            hasError = true;
            } else if(!searchVal.includes('p')) {
                  jQuery(".search-field").after('<span class="error">You have to enter the character "p".</span>');
            hasError = true;
            } else if((searchVal.match(/p/g) || []).length > 1) {
                  jQuery(".search-field").after('<span class="error">Enter only 1 character "p".</span>');
            hasError = true;
            } else if(!searchReg.test(searchVal)) {
            jQuery(".search-field").after('<span class="error">Enter only digits and one "p" character.</span>');
            hasError = true;
        } else if(searchVal.split('p')[0].length > 3 || searchVal.split('p')[1].length > 3) {
                  jQuery(".search-field").after('<span class="error">Exercise and page have to be numbers between 1 and 999.</span>');
            hasError = true;
            } else if(searchVal.charAt(searchVal.indexOf('p')+1) == '0') {
                  jQuery(".search-field").after('<span class="error">Page first digit cannot be 0.</span>');
            hasError = true;
            }
        if(hasError == true) {return false;}
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.