Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip out non-alpha chracters with Jquery when copying text from one input to another

Tags:

jquery

On my website, I have two input fields: Title & Stock Code. I have two goals:

  1. The text from the Title field should be be copied to the stock code field as the user enters text in the title field.

  2. I also want non-alphanumeric chracters to be stripped out during the copy.

I have found this tutorial that explains how to do the first goal. Here is my working example:

http://jsfiddle.net/2gezC/1/

For the second part, I have found it hard to find a tutorial about stripping characters in Jquery, as most tutorials are for JavaScript.

I have found this tutorial and have tried to integrate it into my code as follows:

(function ($) {
    $(document).ready(function () {

        $('input#edit-title-fragment').keyup(function () {
            var str = $(this).val();
            str = str.replace(/[^a-zA-Z 0-9]+/g, '');
            var txtClone = $(this).val();
            $('input#edit-sku-fragment').val(txtClone);
        });
    });

})(jQuery);

However, it does not work. Could someone tell me what I am doing wrong. Thanks!

like image 283
big_smile Avatar asked Sep 12 '12 17:09

big_smile


1 Answers

Here's what you're doing:

// Get the user input from "this" and put it in str variable
var str = $(this).val();
// Remove all non alpha-nums from str and store it back in the str variable
str = str.replace(/[^a-zA-Z 0-9]+/g, '');
// Get the user input from "this" (yes, again) and put it in the txtClone variable
var txtClone = $(this).val();
// Set your other textbox to be the value in txtClone
$('input#edit-sku-fragment').val(txtClone);

Have you spotted the mistake? You should be setting it to str instead.

$('input#edit-sku-fragment').val(str);

Which now works: http://jsfiddle.net/2gezC/2/

Furthmore, as the comments has noted, jQuery is a library built on JavaScript; it's written in JavaScript itself, as you can see by browsing it's source code; https://github.com/jquery/jquery

like image 93
Matt Avatar answered Nov 08 '22 18:11

Matt