jQuery:制作相应的文本框会影响彼此的值

时间:2009-05-19 00:05:11

标签: jquery textbox

情况:

2个文本框,TextBoxA和TextBoxB。我在TextBoxA中输入文本,它设置TextBoxB的值。现在,我需要能够编辑TextBoxB的值,并设置TextBoxA的值。很简单,但我需要在单页上为几对文本框工作。

这是我到目前为止所做的:

$(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());
                }
            });
        });

    });

<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" />

一切正常,除了使第二组文本框影响其对应的对应物。你能看出我做错了什么吗?我几乎是一个JavaScript / jQuery noob(我大部分时间都花在CSS / XHTML上)所以请保持温和。

1 个答案:

答案 0 :(得分:1)

我发现了问题。这非常微妙。需要更改第二组的选择器:

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

为:

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