Wilf Wilf - 1 month ago 9
HTML Question

Update div on typing base on data attribute

I want to have text preview to display the example layout of a page. So when I put the title it's text will show in the title div base on the

data-target
value. Meaning I have multiple inputs to do.

So I write code but it's somehow not send the preview text to the desired div. I'm not good in jquery nor english, sorry.

HTML

<div id="h1"></div>
<div id="h2"></div>
<hr />

<input type="text" onkeypress="livePreview(this.value);" data-target="h1" placeholder="h1 value" />
<input type="text" onkeypress="livePreview(this.value);" data-target="h2" placeholder="h2 value" />


Javascript

var timerHandle = false; // global!
function livePreview(what) {
$('div').data('target').html(what);//use target to display in div
if (timerHandle) clearTimeout(timerHandle);
timerHandle = setTimeout(sendItOff, 500); // delay is in milliseconds
}

function sendItOff() {
what = document.getElementsByClassName("live").value;
console.log("Sending " + what);
}


This is the fiddle : https://jsfiddle.net/ue2aysdq/1/

Answer

The event should be keyup

https://jsfiddle.net/tejashsoni111/ue2aysdq/7/

jQuery('input[type="text"]').on('keyup', function(){
    var id = "#"+jQuery(this).data('target');
    jQuery(id).html(jQuery(this).val());
})