Question

(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: http://jsbin.com/onowu/

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: http://jsbin.com/onowu/edit

Was it helpful?

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]);
    }

    $("input[type='text']").inputdynvalue();
    $("input[type='radio']").click(setText);
});

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top