简体   繁体   English

如何使输入中键入的文本显示在单独的div中

[英]How to make the text that are typed inside the input to appear into a seperate div

I've a input field and a separate paragraph. 我有一个输入字段和一个单独的段落。 Now how do I get the text that are typed inside the input to also to appear inside the paragrah.? 现在如何将输入中键入的文本也显示在paragrah中?

HTML CODE HTML代码

<input type="text" />
<p>facebook/<span>your.username</span> </p>

CSS 的CSS

input{
    width: 300px;
    height: 30px;
}
span {
    font-weight: bold;
}

Use the keyup event: 使用keyup事件:

$(function() {
    $('input').on('keyup', function() {
        var username = $(this).val();

        if(username.length > 0) {
           $('p > span').html(username);
        } else{
           $('p > span').html('your.username');
        }
    });
});

See working jsfiddle: http://jsfiddle.net/VDesign/yqt8tx3b/2/ 参见工作jsfiddle: http//jsfiddle.net/VDesign/yqt8tx3b/2/

Try this: 尝试这个:

$(document).ready(function() {
    // When DOM is ready to be manipulated

    $('input').on('keyup', function() {
        // On each key-up in textbox

        $('p span').text($.trim($(this).val()) || 'your.username');
        // Set the value of textbox inside the span
    });
});

Demo: https://jsfiddle.net/tusharj/4yfswj3p/ 演示: https : //jsfiddle.net/tusharj/4yfswj3p/

This way you can make live changes in p tag. 这样,您可以实时更改p标签。

 $('#txt').on('input',function(e){ $('p').html($(this).val()); }); 
 input{ width: 300px; height: 30px; } span { font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="txt"/> <p>facebook/<span>your.username</span> </p> 

Here's a pure JavaScript solution, using the input event that will update the contents of another element as you type and also includes a check on whether or not the input element is empty. 这是一个纯JavaScript解决方案,使用input事件将在您键入时更新另一个元素的内容,还包括检查input元素是否为空。

 var input=document.getElementById("input"),output=document.getElementById("output"); input.addEventListener("input",function(){ output.innerHTML="facebook.com/"+(this.value.trim()||"your.username"); },0); 
 <input id="input" type="text"> <p id="output">facebook.com/your.username</p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM