2017-11-15 4 views
-2

コードは、別の入力フィールドを埋めるためにのみ機能します。しかし、私は通常の段落を記入し、別の入力フィールドを記入する必要はありません。どうしたらいいですか?HTML要素をJavaScriptによる入力に基づいてテキストで塗りつぶす

$(".first").on('keydown',function(){ 
 
    $(".second").val($(this).val()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="first" placeholder="type here"> 
 
<input type="text" class="second" placeholder="here it is the reuslt">

答えて

1

要素にテキストを挿入するtext機能を使用してください。

id'sclasses特定要素(id)または要素のclass)のいずれかを指定するために使用することができます。下の例では、CSSを赤色にして各<p>タグの色を変更するクラスを追加しました。私たちのJSでは個々のIDのを選択してください。

//selecting on the insertTextHere id to specify the <p> tag to insert text into 
 
$("#first").on('keyup', function() { 
 
    $("#insertTextHere").text($(this).val()); 
 
}); 
 

 
//you can even set it up to revert back to the original text on click 
 
$("#resetButton").on("click", function() { 
 
    var resetText = "Type into input to overwrite this text"; 
 
    //insert original string as text 
 
    $("#insertTextHere").text(resetText); 
 
    //empty the input value 
 
    $("#first").val(""); 
 
});
.text { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="first" placeholder="type here"> 
 
<button id="resetButton" type="button">reset text</button> 
 
<div> 
 
    <p id="insertTextHere" class="text">Type into input to overwrite this text</p> 
 
    <p class="text">This text will not be overwritten</p> 
 
</div>

+0

は素晴らしい作品が、私はそれが記入すべき特定のどの段落クラスを指定することができますので、代わりにこれを使用しますか? @ master-yoda – DanielsV

+0

はい、うまくいきません。私は、キー入力時に入力した文字をもう一度追加するように、テキストを使用する必要があると思います。 –

+0

@DanielsV pタグに特定のクラスを追加するためのクラスを追加します。 – iArcadia

0

フォームフィールドは、value性(jQueryのでval()方法)を有します。通常の要素にはtextContentというプロパティ(またはJQueryではtext()メソッド)があります。

また、入力時にすべてのテキストを取得するには、を使用する必要があります。

$(".first").on('keyup',function(){ 
 
    $("#output").text($(this).val()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="first" placeholder="type here"> 
 
<p id="output"></p>

-1
$(".first").on('keydown',function(){ 
    $('.selectorOfDOM').text($(this).val()); 
} 

あなたは、このリンクで同様の質問を見つけることができます。 Fill div with text

+0

この回答は、すでに存在する他の2つのものとはどのように異なっているか、またはそれより優れていますか? –

0

代わりのKeyDown/keyUpイベントの '入力' イベントを使用する必要があります - それらのユーザーペーストどちらもを動作する場合。

$('.inputClass').on('input', function() { 
 
    $('.paragraphClass').text($(this).val()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="inputClass"> 
 
<p class="paragraphClass"></p>

+0

第三者のサイトでコードにリンクしないでください。これらのリンクは時間がたつにつれて消滅する可能性があります。したがって、あなたの答えは意味がありません。コードスニペット(回答ツールバーの7番目のボタン)を答えに入力するだけで、実行可能なコードを作成できます。 –

関連する問題