Jquery – How to change form text with Jquery but keep it when filled by user


(I hope my title is comprehensible, it was hard to sum up.)

I have some script which change some text inside a form depending on the selected radio button as you can see here:

The problem is that if some user enter some text and then click on a other radio button it will remove his text.

What I'm looking for is a way change the grey text ONLY when there isn't any text filled by the user. And if the user remove his text, it will fill blank with the text depending on the radio button selected.

You can see my code here:

Best Solution

Check to see if the input has the class "hint". Only change the text is it does.

Full example:

$(document).ready(function() {
    function setText(){
        var kf = this.title.split('|');
        if (kf.length < 0) return;
        if($('#' + this.name + '_text').hasClass('hint')){
            $('#' + this.name + '_text').val(kf[0]).addClass('hint');
        $('#' + this.name + '_text').attr('title', kf[0]);


This works by checking the input textbox for the class "hint" and changing the value only when it is found. As mentioned in the comments by Jonathan Sampson "the .focus() event removes the class "hint," and the .blur() event adds it again if no text has been provided".

I would also run your code through the html validation service provided by W3C. JavaScript can be funny if you do not have valid code. (Plus everyone should write valid html)

A also noticed you were including jQuery twice in your code, I would suggest you remove one of the one of them.

Updated (July 10th, 2009): Fixed a bug mentioned in the comments below.