Vital
Vital

Reputation: 91

jquery/JS simple data bind for dynamic controls

I have on the html page an and elements, created dynamically via js.

<input type="text" id="MyInput" name="MyInput" 
class='form-control copyMe' placeholder="enter smth pls"/>
<div id="jsonTextAreaDiv" contenteditable="true">
<span id="MyInput_JSON"></span>
</div>

And I want to have text binding from input to span.

So, I go with next JS:

$(document).on('input', 'input.copyMe', function(){
  var valToInsert = $(this).val();
  var idToInsert = $(this).attr("id") + "_JSON";        
    document.getElementById(idToInsert).innerHTML = valToInsert;
});

Could be all in one line jquery, but... Anyway. This binding works fine during entering text to input. But once input looses focus - suddenly span looses inner text. I don't know why. This is exactly my question, how is it happening?

I've "worked around" this issue with adding

 $(document).on('input', 'input.copyMe', function(){
  var valToInsert = $(this).val();
 var idToInsert = $(this).attr("id") + "_JSON";        
    document.getElementById(idToInsert).innerHTML=valToInsert;
}).on('blur', '.copyMe', function(){ 
var valToInsert = $(this).val();
  var idToInsert = $(this).attr("id") + "_JSON";        
    document.getElementById(idToInsert).innerHTML=valToInsert;});

This way it works like I want it. But this is ridiculous. Any ideas regarding why does the value disappear from span at the first place?

Thanks in advance.

Upvotes: 0

Views: 42

Answers (1)

TheValyreanGroup
TheValyreanGroup

Reputation: 3599

Change your input event to use the change event instead. IE does not support the 'input' event correctly. Alternatively, you could try using the keyup event.

$(document).on('change', 'input.copyMe', function(){
  var valToInsert = $(this).val();
  var idToInsert = "#" + $(this).attr("id") + "_JSON";        
  $(idToInsert).html(valToInsert);
});

Also, i changed your last line to jQuery as well. There's no reason to mix jQuery and pure JS together. It makes it easier to read if you keep it uniform.

Upvotes: 1

Related Questions