Я пытаюсь захватить значение 2 входов text и выполняет функции, когда пользователь нажимает клавишу ввода.
Я использую Internet Explorer 11.
<script type = "text/javascript">
function myFuncion(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
</script>
Теперь text вводит код
<input type = "text" size = "6" name = "nameAnotherText" id = "idAnotherText" value = ""
onkeydown = "if (event.keyCode == 13) {
myFuncion('" + document.getElementById("idText").textContent + "', '"
+ document.getElementById('idAnotherText').value + "');
}"
/>
<input type = "text" size = "6" name = "nameText" id = "idText" value = ""
onkeydown = "if (event.keyCode == 13) {
myFuncion('" + document.getElementById("idText").textContent + "', '"
+ document.getElementById('idAnotherText').value + "');
}"
/>
Это не работает.
К сожалению, это не работает:
<button onclick = "myFuncion('" +
document.getElementById(\"idAnotherText\").textContent + "', '" +
document.getElementById(\"idText\").textContent + "')" >Press Me</button>
<button onclick = "myFuncion(" +
document.getElementById(\"idAnotherText\").textContent + ", " +
document.getElementById(\"idText\").textContent + ")" >Press Me</button>
<button onclick = "myFuncion(" +
document.getElementById('idAnotherText').textContent + ", " +
document.getElementById('idText').textContent + ")" >Press Me</button>
Как это решить?
Или что-то https://stackoverflow.com/a/155272/811293, но не работает:



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Если вы находитесь в форме с кнопкой отправки, вам нужно вернуть false из обработчика событий, иначе ваша форма будет автоматически отправлена при нажатии return во время ввода.
Как правило, вам следует избегать попыток обрабатывать нажатия Return во входных данных в форме. Это нарушает ожидаемое поведение форм в Интернете, которое заключается в том, что они отправляются при нажатии return. Вместо этого зарегистрируйте обратный вызов в событии отправки формы и выполните его (проверки, ajax и т. д.) Вместо этого.
Удалите кавычки из аргументов функции. Вы также должны использовать value вместо textContent для получения значений из полей ввода в обоих случаях. Попробуйте следующее:
function myFuncion(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}<input type = "text" size = "6" name = "nameAnotherText" id = "idAnotherText" value = ""
onkeydown = "if (event.keyCode == 13) {
myFuncion(document.getElementById('idText').value, document.getElementById('idAnotherText').value);
}"
/>
<input type = "text" size = "6" name = "nameText" id = "idText" value = ""
onkeydown = "if (event.keyCode == 13) {
myFuncion(document.getElementById('idText').value, document.getElementById('idAnotherText').value);
}"
/>Писать JavaScript в HTML - плохая идея. Вы можете сделать следующее, что будет чище:
function myFuncion(event) {
if (event.keyCode == 13) {
var txt1 = document.getElementById('idText').value;
var txt2 = document.getElementById('idAnotherText').value;
window.alert("txt1:" + txt1 + ", txt2:" + txt2);
}
}<input type = "text" size = "6" name = "nameAnotherText" id = "idAnotherText" value = "" onkeydown = "myFuncion(event);"/>
<input type = "text" size = "6" name = "nameText" id = "idText" value = "" onkeydown = "myFuncion(event);"/>Переписывание javascript заставляет его работать. В общем, избегайте вставки фактического кода в код
С этим как javascript
function myOnKeyDown(event) {
if (event.keyCode == 13) {
var text_value = document.getElementById("idText").value
var another_text_value = document.getElementById("idAnotherText").value
myFunction(text_value, another_text_value);
}
}
function myFunction(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
Вы можете иметь это в своем HTML
<input type = "text" size = "6" name = "nameAnotherText" id = "idAnotherText" value = "" onkeydown = "myOnKeyDown(event)"/>
<input type = "text" size = "6" name = "nameText" id = "idText" value = "" onkeydown = "myOnKeyDown(event)"/>
Это должно позволить вашему коду работать.
Я обычно стараюсь идти как можно более родным. Вы можете обернуть поля ввода тегом формы и добавить прослушиватель событий к событию отправки.
Попробуйте следующее.
const form = document.getElementById('myform');
form.addEventListener('submit', onSubmit, false);
form.submit = onSubmit;
function onSubmit(event) {
if (event) {
event.preventDefault();
}
console.info('submitted');
const input1 = document.getElementById('input1').value;
const input2 = document.getElementById('input2').value;
console.info({
input1,
input2
});
}<form id = "myform">
<input type = "text" id = "input1">
<input type = "text" id = "input2">
<button type = "submit" style = "display: none"></button>
</form>
С кнопкой, как будто мое редактирование не работает. Это простой window.alert.