jQuery: Generate valid tag of string
I am looking for a way to generate a valid tag (string with only a-z and minus as valid chars) out of a given string.
Just let me show you the code:
<p>
<label>Tag Title *:</label>
<input type="text" class="tag_title" name="input_tag_title" value="" />
</p>
<p>
<label>Tag (A-Z; -) *:</label>
<input type="t开发者_如何学Pythonext" class="tag" name="input_tag" value="" />
</p>
As soon as Tag title looses focus, the Tag input box shall be filled with a valid string. It should only contain characters a-z (regardless of case) and a minus. But this should only take place if the tag-input is empty. If it is not empty, the entered string (in the tag input field) shall be checked for invalid chars and automatically replace all non-valid characters (replace all non-alphabetical characters with minuses).
I tried it with
$(".tag_title").blur(
function()
{
$(".tag").text = this.value.replace(/[^a-z\-]/g, '_');
}
);
But that does not work. Any hints?
Thanks!
You need to use .val(...)
to change the value of a text input.
I also used .val()
against the .tag_title
element (wrapped in a jQuery object) that received the blur
event to get the value the user typed.
Test it out: http://jsfiddle.net/8mqzd/
$(".tag_title").blur(
function() {
var $tag = $('.tag');
if( $tag.val() == "" ) {
$tag.val( $(this).val().replace(/[^a-z\-]/g, '-') );
}
}
);
http://api.jquery.com/val/
EDIT: Made it so it only replaces if the .tag
element is empty (as requested).
EDIT: As Nick pointed out, your use of this.value
to retrieve the value of the element that received the blur
was just fine. I changed it to use jQuery's .val()
, but please don't take from that the idea that you must use .val()
. :o)
One problem is that an input element needs to the jQuery val() function
$(".tag").text = this.value.replace(/[^a-z\-]/g, '_');
could be like this:
var t = $('.tag');
t.val(t.val().replace(/[^a-z\-]/g, '_'));
EDIT: Thanks digitalFresh, I've reviewed and made changes.
精彩评论