views:

44

answers:

2

Hey,

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="text" 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!

A: 

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.

Sam
`this` cannot be used because the function is executing globally. Use`$(".tag").text($(".tag").text().replace(/[^a-z\-]/g, '_'));`. (maybe)
digitalFresh
@digitalFresh - Not sure where that idea came from, it's certainly not executed globally, `this` refers to the `<input type="text" class="tag_title" name="input_tag_title" value="" />` element inside it's `blur` handler.
Nick Craver
+3  A: 

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)

patrick dw
+1 - Note that `$(this).val()` or `this.value` is fine for an `<input type="text" />`, the second is actually much faster ;)
Nick Craver
@Nick - But... that's... not jQuery! ;o) You're right. I do like the idea of using the native API when it's simple to do so. Not sure why I chose to change it. I'll make a note. Thanks for the + . :o)
patrick dw