harry
harry

Reputation: 731

display data in a textbox when checkbox is checked

I have three text boxes having id text1, text2, text3 and one checkbox having id check. I am displaying something in first textbox let's say 10. Now if i will check checkbox then automatically "20" will be displayed in the second textbox. Third textbox remains same as it is. If I will display something in 1st and 2nd textboxes, now if i will check checkbox then same "20" will be displayed in 3rd textbox. After checked if in anytime i will uncheck the checkbox then value "20" will also be removed from the textbox(either 2nd or 3rd) Any idea please? Please be easy with me

index.jsp

<input type="checkbox" id="check"/>

<input type="text" id="text1" value="10"/>
<input type="text" id="text2"/>
<input type="text" id="text3"/>

Upvotes: 2

Views: 4125

Answers (2)

Valky
Valky

Reputation: 1866

Your question is not easy to understand....

When checkbox is checked the next empty input text have to display '20' value ? And if checkbox is unchecked last input with '20' is cleared value ?

Add the "checker" class to each input text.

<input type="checkbox" id="check"/>
<input type="text" id="text1" value="10" class="checker"/>
<input type="text" id="text2" class="checker"/>
<input type="text" id="text3" class="checker"/>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
<br/>
<input type="text" id="anotherTB" value="100"/>

Use this jquery script instead of yours

$(document).ready(function(){
    $('#check').click(function(){

        if($(this).is(':checked'))
        {
            var stop='';
            $('.checker').each(function(){
                if($(this).val()=='' && !stop)
                {
                   $(this).val('20');
                    stop='stop'; 
                   // Add something like that to set other textbox values
                   var add = parseInt($('#anotherTB').val()) + parseInt($(this).val());
                   $('#anotherTB').val(add); 
                }
            });
        }

        else if(!$(this).is(':checked'))
        {
            $('.checker').each(function(){
                if($(this).val()=='20')
                {
                   $(this).val('');
                }
            });
        }
    });
});

You can see it work here : http://jsfiddle.net/w9hAZ/1/

Upvotes: 1

SoWhat
SoWhat

Reputation: 5622

 $('#check').change(function(){if($(this).is(':checked'))$('#text2').val(20);});

If you want to clear the value when it is unchecked use:

 $('#check').change(function(){if($(this).is(':checked'))$('#text2').val(20);else $('#text2').val(''); });

Upvotes: 0

Related Questions