开发者

jQuery character replacement call activated on click

I have this jquery function to automatically replace sertain characters with others:

jQuery(function() {
    j开发者_StackOverflow社区Query('.textarea').keyup(function() {

    jQuery(this).val(jQuery(this).val().replace(/A/g, "5"));
    jQuery(this).val(jQuery(this).val().replace(/Q/g, "3"));

    });
});

I want to make this function optional and only activated if the user clicks on a button next the text-area input form.

I'm trying something like this:

$("a").toggle(
  function () {

        jQuery(function() {
            jQuery('.tifibox').keyup(function() {

            jQuery(this).val(jQuery(this).val().replace(/A/g, "3"));
            jQuery(this).val(jQuery(this).val().replace(/Q/g, "5"));

            });
        });

    $(this).addClass("selected"); // button selected
  },
  function () {
    $(this).removeClass("selected");
  }
);

I have not tested this yet.. but is that correct? thanks


Change the link to a checkbox and then you can use something like:

$("#checkOne").change(   function () {
      if($(this).is(":checked")) {
         $("#textOne").bind("keyup", function() {
              $(this).val($(this).val().replace(/A/g, "3"));
         });
      } else {
          $("#textOne").unbind("keyup");
      }   }

);

The jsfiddle

This code will only replace newly typed text and old text will remain unchanged. If you want to replace the existing text (i.e. escape the existing text, modify the code as follows:

$("#checkOne").change(
  function () {
      var textarea = $("#textOne");
      if($(this).is(":checked")) {
         escapeText($(textarea));
         $(textarea).bind("keyup", function() {
              escapeText($(this));
         });
      } else {
          $(textarea).unbind("keyup");
      }
  }

);

function escapeText(ele) {
    $(ele).val($(ele).val().replace(/A/g, "3"));
}

the jsfiddle

Of course you can use a link as well, but the syntax is confusing. toggle() takes 3 parameters (3 functions):

1 - handler(eventObject)A function to execute every even time the element is clicked.

2 - handler(eventObject)A function to execute every odd time the element is clicked.

3 - handler(eventObject)Additional handlers to cycle through after clicks.

So in your code above, the first click would call the second function (since one it's odd) the second you call the first function. So turn on the feature in the second function and turn it off in the first.

Also use bind and unbind as I have shown rather than setting classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜