Search code examples
jqueryformsinputreplacekeyup

Jquery replacing space in search form with #


Wondering if someone can advise to why this is not working please.

The idea so when a user enters SPACE on the search form, Its replaced with a #,, So if "Red Boots size 9" was typed in the search bar it would be replaced with (the # Doesnt get sent to database, Its just for show) #Red#boots#size#9

        $("#s").keyup(function () {
            var textValue = $(this).val();
            textValue =textValue.replace(/ /g,"#");
            $(this).val(textValue);
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form role="search" method="get" id="searchform" class="searchform" action="http://tag2.testsiteonline.co.uk/"> 
        <label class="screen-reader-text" for="s">Search for:</label> 
        <input type="text" value="" name="s" id="s" /> 
        <input type="submit" id="searchsubmit" value="Search" /> 
    </form>

Head code

<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<!-- Magnific Popup core CSS file -->
<link rel="stylesheet" href="magnific-popup/magnific-popup.css">
 <link rel="stylesheet" href="/fonts/styles.css">

<!-- jQuery 1.7.2+ or Zepto.js 1.0+ -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://tag2.testsiteonline.co.uk/searchjs.js"></script>
<!-- Magnific Popup core JS file -->
<script src="magnific-popup/jquery.magnific-popup.js"></script>
    <link rel="profile" href="http://gmpg.org/xfn/11" />
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />

    <?php wp_head(); ?>
</head>

Also on my searchjs.js - This is everything I have on there? Should I have anything before or after this?

$("#s").keyup(function () {
        var textValue = $(this).val();
        textValue =textValue.replace(/ /g,"#");
        $(this).val(textValue);
    });

Solution

  • Your code works fine, here's a jsfiddle for proof: http://jsfiddle.net/zez7w74d/

    Post your <head> content where you're loading your js files to check for a possible interruption.

    Edit: Remove all manually loaded jQuery from wordpress, since wordpress comes with jQuery according to their dev page: https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/

    And call your jQuery code like this:

    jQuery("#s").keyup(function () {
            var textValue = $(this).val();
            textValue =textValue.replace(/ /g,"#");
            $(this).val(textValue);
    });