Enter键验证contenteditable

时间:2018-02-28 13:05:58

标签: javascript html css

我有一个标题,用户可以通过contenteditable修改。 我希望当用户按下Enter时,这会验证标题而不是传递一行。

<div class="panel-participants-title"
     *ngIf="thread.title !== '' ">
    <div class="panel-title"
         contenteditable="true">
           {{thread.title.substring(1)}}
    </div>
</div>


.panel-participants-title:hover > *[contenteditable="true"] {
  background: #989898;
}
.panel-participants-title > *[contenteditable="true"] {
  outline: 0;
}

///// UPDATE

<div class="panel-participants-title">
     <div class="panel-title"
          contenteditable="true"
          (keypress)= "validateTitle($event)">
              {{thread.title.substring(1)}}
     </div>
</div>

validateTitle(event: any): void {
  if(event.keyCode===13) {
    document.getElementById("panel-title").submit();
  }
}

//////// UPDATE2

validateTitle(event: any): void {
  if(event.keyCode===13) {
    event.preventDefault();
    event.stopPropagation();
    event.submit();
  }
}

2 个答案:

答案 0 :(得分:1)

onKeyPress="if(event.keyCode == 13) validerForm();"

function validerForm(){ document.getElementById("formulaire").submit(); }

通常这就是你要做的事情。基本上当键号13(Enter键)并按下它时会启动一个将验证表格的功能。

答案 1 :(得分:1)

以下是小提琴的一个工作示例,如果它关闭:)

&#13;
&#13;
document.querySelector('#id1').addEventListener('keypress', function (e) {
    var key = e.which || e.keyCode;
    if (key === 13) { // 13 is enter
      	var text = document.getElementById("id1").value;
        if (text.includes("w")) {
        	alert("Omg, the string contains a W, try again");
        } else {
     		document.getElementById("id1").blur();
        }
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input Field <input id="id1" type="text" name="fname">
&#13;
&#13;
&#13;