Reputation: 23
I'm trying to make a textarea input field which automatically replaces specific characters to different characters; example: when a user types "a" character it should be automatically replaced with "o" character. I'm new to jquery so can you please tell what's wrong with the following code:
$(function() {
$('#myTextBox').keyup(function() {
$("a").replaceWith( "o" );
$("z").replaceWith( "N" );
$("y").replaceWith( "M" );
$("p").replaceWith( "f" );
$("v").replaceWith( "K" );
$("b").replaceWith( "P" );
});
});
I appreciate your help, thank you
edit:
thank you all, the following worked as expected:
$(function() {
$('#myTextBox').keyup(function() {
$(this).val($(this).val().replace(/a/g, "o"));
});
});
Upvotes: 2
Views: 8012
Reputation: 31
$(document).ready(function() {
$(".normal").each(function() {
var text = $(this).html();
text = text.replace(/"/g, '');
$(this).html(text);
});
});
for something like this:
<div class="normal">Lorem "ipsum "dolor"</div>
Result:
<div class="normal">Lorem ipsum dolor</div>
Upvotes: 3
Reputation: 27451
First of all $("a")
actually targets all anchor elements on the page, so I'm guessing that's not what you want (and others don't even exist, except p, so your selector will return nothing). Secondly, you can use regular expressions to do your replace without any special jQuery code.
Instead of:
$("a").replaceWith( "o" );
Try:
$(this).val($(this).val().replace(/a/g, "o"));
To break that down:
var oldValue = $(this).val();
var newValue = oldValue.replace(/a/g, "o");
// Set to new value
$(this).val(newValue);
Upvotes: 4