将文本从一个输入复制到另一个输入时,使用Jquery删除非alpha字符

big*_*ile 7 jquery

在我的网站上,我有两个输入字段:标题和股票代码.我有两个目标:

  1. 当用户在标题字段中输入文本时,应将标题字段中的文本复制到股票代码字段.

  2. 我还希望在复制过程中删除非字母数字字符.

我发现本教程解释了如何实现第一个目标.这是我的工作示例:

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

对于第二部分,我发现很难找到关于在Jquery中剥离字符的教程,因为大多数教程都是针对JavaScript的.

我找到了本教程,并尝试将其集成到我的代码中,如下所示:

(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);
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用.有人能告诉我我做错了什么.谢谢!

Mat*_*att 19

这是你正在做的事情:

// 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);
Run Code Online (Sandbox Code Playgroud)

你有没有发现错误?您应该将其设置为str.

$('input#edit-sku-fragment').val(str);
Run Code Online (Sandbox Code Playgroud)

现在有效:http://jsfiddle.net/2gezC/2/

此外,正如评论所指出的那样,jQuery是一个基于 JavaScript 的库; 它是用JavaScript编写的,正如你可以通过浏览它的源代码看到的那样; https://github.com/jquery/jquery