如何在html中同步两个文本框的内容?

时间:2014-03-02 04:00:06

标签: html5 angularjs

我有两个文本框,我想保持同步,即两个文本框的内容应该完全相同。如果一个文本框更改,则其他文本框内容应自动同步,反之亦然。

3 个答案:

答案 0 :(得分:1)

在angularjs中,它非常容易

<input type=text ng-model='prop'>
<input type=text ng-model='prop'>

绑定到同一范围属性。

答案 1 :(得分:-1)

我认为这应该使用jquery:

$("#textbox1").blur(function() {
  $("#textbox2").val($("#textbox1").val());
});

$("#textbox2").blur(function() {
  $("#textbox1").val($("#textbox2").val());
});

答案 2 :(得分:-1)

假设您的下一个问题(被拒绝)与此原始问题相关,则有一个纯粹的JavaScript解决方案......

假设您可以在两个页面上控制javascript并确保一个页面打开另一个页面(请参阅:https://developer.mozilla.org/en-US/docs/Web/API/Window.open),以便您可以保留窗口参考

var theOtherWindow = window.open(pageurl, 'newwindow');

然后您可以使用postMessage(https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage)转移说明。

假设您在两个页面上都有一个名为“bob”的输入字段,您可以执行类似的操作(为简洁起见,我将使用jquery)

<input type="text" name="bob"></input>

<script>
    // send message on change
    $('input[name=bob]').on( 'change', bobchange );
    function bobchange(){
        var theMessage = ([
            'updateInput',
            'bob',
            $('input[name=bob]').value();
        ]).join('::');
        theOtherWindow.postMessage(theMessage);
    }

    // receive message
    $(window).on('message', function(e){
        if(e.origin !== 'http://example.com:8080') return; // minimal security
        theMessage = e.data.split('::');
        switch(theMessage[0]){
            case 'updateInput':
                $('input[name='+theMessage[1]+']')
                    .off('change') // prevent infinite loop
                    .value(theMessage[2]) // update field
                    .on( 'change', bobchange ); // restore event
            break;
        }
    });
</script>