Nelie
Nelie

Reputation: 93

Updating two dynamic text fields simultaneously

See below code. I am creating 2 text fields at a time. Now how could I type on one text field and make the other twin text field have the same values simultaneously?

<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
<script>
$(document).ready(function() {
    var tfCont = 0;
    var InputsWrapper = $("#InputsWrapper");
    var x = InputsWrapper.length; 
    var namefield = $("#tfButton");

    $(namefield).click(function() {
        tfCont++;
        $(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..."/>' + '<br>' + '</div>' + '</div>');

         $(OuterWrapper).append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '">' + '</div>');
        x++;
        return false;
    });
});
</script>

Upvotes: 0

Views: 1281

Answers (2)

jwatts1980
jwatts1980

Reputation: 7356

I created a fiddle that I think does what you want: http://jsfiddle.net/3h1h5j7y/

Here is the code. HTML

<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>

JavaScript

I added a data- attribute to the inputs with the tfCont id so that they can operate in pairs as they are added.

Also, I am using the on() method so that objects can be added dynamically. It is filtering on the fTypex class.

$(document).ready(function() {
    var tfCont = 0;
    var InputsWrapper = $("#InputsWrapper");
    var x = InputsWrapper.length; 
    var namefield = $("#tfButton");

    $(namefield).click(function() {
        tfCont++;

        $(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/>' + '<br>' + '</div>' + '</div>');

         $("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');


        x++;
        return false;
    });


    $(document).on("click blur keyup", "input.fTypex", function() {
        var tfc = $(this).data("tfcount");
        $("#tf_" + tfc).val(this.value);
    });
});

I had to change $(OuterWrapper) from your example to $("#OuterWrapper") because there was not a variable.

Upvotes: 1

user3991493
user3991493

Reputation:

Try something like this :

use onkeyup to call a function which binds the values HTML

  <body>
   <input id='ip1' onkeyup='updateOther(this);' type='text'>
   <input id='ip2' type='text'>


   <script src="script.js"></script>
  </body>

JS:

function updateOther(obj){
    $('#ip2').val($(obj).val())  ;
}

http://plnkr.co/edit/dpwav5fGcisZcjBIzYyz?p=preview

Upvotes: 0

Related Questions