tags:

views:

130

answers:

1

Situation:

2 text boxes, TextBoxA and TextBoxB. I enter text into TextBoxA and it sets the value of TextBoxB. Now, I need to be able to edit the value of TextBoxB, and have that set the value of TextBoxA. Simple enough, but I need this to work for several pairs of text boxes on a single page.

This is what I have so far:

$(function() {
        $(':text').css("border", "1px solid #666"); // Remove for actual app

        // Sets value of corresponding textbox by ID
        $(':text').blur(function() {
            $('#inputval_' + ($(this).attr("id"))).val($(this).val());
        });

        //Styles all inputs set to read only
        $('input[readonly=readonly]').css("border", "none");

        $('input[readonly=readonly]').click(function() {// on click allows edit of readonly inputs
            if ($(this).attr("readonly") == true) {
                $(this).removeAttr("readonly");
                $(this).css("border", "1px solid #666");
            }
            $(this).blur(function() {//on blur sets readonly back to true
                if ($(this).attr("readonly") == false) {
                    $(this).attr("readonly", "readonly");
                    $(this).css("border", "none");
                    $('#' + ($(this).attr(("id").remove("inputval_")))).val($(this).val());
                }
            });
        });

    });

And:

<input type="text" id="text1" name="userinput" /><br /><br />
<input type="text" id="text2" name="userinput" /><br /><br />
<input type="text" readonly="readonly" id="inputval_text1" />
<input type="text" readonly="readonly" id="inputval_text2" />

Everything works, except for making the second set of text boxes affect their corresponding counterparts. Can you see what I'm doing wrong? I'm pretty much a JavaScript/jQuery noob (spend most of my time in CSS/XHTML) So be gentle.

+1  A: 

I found the problem. It's very subtle. The selector for the second set needs to be changed from:

$('#' + ($(this).attr(("id").remove("inputval_")))).val($(this).val());

to:

$('#' + ($(this).attr("id")).replace("inputval_","")).val($(this).val());
Jose Basilio
This works perfect. Thanks!