Этот код клиента Meteor пытается очистить все элементы textarea
и input
как продаваемые, перемещая фокус на первый из этих элементов на странице.
Иногда он не работает, если на странице нет "textarea". Любая идея, как это исправить?
$('textarea, input').val('');
$('textarea, input').first().focus();
<div id="main">
<form>
<button class="open" style="visibility:hidden">Open</button>
<form id="pener"></form>
<p class="whole">Enter number</p>
<input class="required whole uppercase" placeholder="Number" name="Num" type="text">
<select class="half" data-id="df4tBwQ8EBu8ak7ms" name="rand">
<option class="whole" value="">Select rand...</option>
<option value="">Tl</option>
<option value="">Ve</option>
</select>
<br><br>
<div class="progress" style="display: none;">
<div id="animate" class="progress-bar" style="width:0"></div>
</div>
</form>
</div>
Там разница между очисткой <form>
и сбросом a <form>
. В демо, форма C и D демонстрируют эту разницу. Я думал, что вторая половина вопроса, связанная с .focus()
, будет простой, но на самом деле это неожиданное требование. Элемент, на который мы хотим сосредоточиться, должен иметь tabindex
атрибут tabindex
.
Детали прокомментированы в демонстрации
input {
font: inherit;
width: 12ch;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title></title>
<style></style>
</head>
<body>
<header> </header>
<section>
<form id='formA'>
<label>Form A</label>
<textarea>Form control field values that are written
within the source HTML are default values</textarea>
<input value='Default'>
<input value=''>
<input value='Default'>
<textarea>Default</textarea>
<p>With textareas...</p>
</form>
<hr>
<form id='formB'>
<label>Form B</label>
<input value='Default'>
<input value='Default'>
<input value=''>
<p>...without textareas</p>
</form>
<hr>
<form id='formC'>
<label>Form C</label>
<input value=''>
<input value='Default'>
<input value='Default'>
<ol>
<li>Type anything in the first input of Form C</li>
<li>Purpose: Determine what clearing a form does.</li>
<li>Results: All fields are emptied (cleared)</li>
</ol>
</form>
<hr>
<form id='formD'>
<label>Form D</label>
<input value=''>
<input value='Default'>
<input value='Default'>
<ol>
<li>Type anything in the first input of Form D</li>
<li>Purpose: Determine what reseting a form does.</li>
<li>Results: The text typed in the first input is cleared, but the remaining inputs with default values remain.</li>
</ol>
</form>
<hr>
<hr>
<fieldset id='btnGrp'>
<input type='button' value='CLEAR A' data-id='1'>
<input type='button' value='CLEAR B' data-id='2'>
<input type='button' value='CLEAR C' data-id='3'>
<input type='button' value='RESET D' data-id='4'>
</fieldset>
</section>
<footer> </footer>
<script>
function clearFields(x) {
/* Use HTMLFormControlsCollection to gather all forms
|| and their form controls (<input>, <textarea>, etc.)
|| Array.from() is then used to make the HFCC into a
|| real array.
|| An integer is passed to determine which <form>
|| will be processed by it index.
*/
const F = Array.from(document.forms[x].elements);
/* Run each FC (Form Control) through a loop
|| that calls an anonymous function...
*/
F.forEach(function(field, index) {
// Clear FC value
field.value = '';
// If this is the first FC in the array...
if (index === 0) {
/* SET TABINDEX TO A VALUE OF -1 OR MORE
|| Without tabindex, the FC cannot gain focus
|| programmatically.
*/
field.setAttribute('tabindex', '0');
// Focus on said FC
field.focus();
}
});
}
// Register the click event on fieldset#btnGrp...
document.getElementById('btnGrp').addEventListener('click', function(e) {
// Reference the clicked id
var tgt = e.target;
// Get the data-id of the button that was clicked (e.target)
var ID = Number(e.target.getAttribute('data-id'));
// if clicked button (e.target) is the forth one...
if (ID === 4) {
/* Using HFCC to reference button and call the reset()
|| method on the fourth <form>
|| Form C and D demonstrates the difference between
|| clear and reset
*/
document.forms[3].reset();
tgt.setAttribute('tabindex', '0')
tgt.focus();
} else {
clearFields(ID - 1);
}
});
</script>
</body>
</html>
Присвоить id
вашей форме, например <form id="myForm">
$("#myForm")[0].reset();
Это приведет к сбросу всей формы независимо от того, что она содержит.
Вы можете сбросить все поля формы, используя эту строку
document.getElementById("myForm").reset();
Затем просто сфокусируйте первый элемент так, как вы