I have tried to create a script that gets activated by pressing the button and proceeds to clear div "input-fields". First I failed miserably, was expected though as I am new to JavaScript. So I tried to follow some different guides etc. which didn't help me solve the problem either. At this point I just want a script that actually works.
To be clear: I know about onclik = getElementsByClassName.value = " " but I want to learn more about js hence I'm not using that.
Here is the html code used:
<div >
<input type="text" placeholder="Name">
<input type="text" placeholder="Email Address">
<input type="text" placeholder="Phone">
<input type="text" placeholder="Subject">
</div>
<button>SEND</button>
CodePudding user response:
Explanation in the comments. Add a comment if you need further explanation.
const button = document.querySelector('button') // get button
const div = document.querySelector('.input-fields') // get input div
// console.log(div)
var inputElements = div.getElementsByTagName("input"); // get input array
// console.log(inputElements)
button.addEventListener('click', () => { // add a click event to button
for (var i = 0, max = inputElements.length; i < max; i ) { // loop through input elements and make value ''
inputElements[i].value = ''
}
})
<div >
<input type="text" placeholder="Name">
<input type="text" placeholder="Email Address">
<input type="text" placeholder="Phone">
<input type="text" placeholder="Subject">
</div>
<button>SEND</button>
CodePudding user response:
<div >
<input type="text" placeholder="Name">
<input type="text" placeholder="Email Address">
<input type="text" placeholder="Phone">
<input type="text" placeholder="Subject">
</div>
<button onclick="handleClick">SEND</button>
const input = document.querySelectorAll(".input");
const btn = document.querySelector("button")
console.log(btn,input)
btn.addEventListener("click",()=>{
for(prop in input){
input[prop].value = ""
}
})
CodePudding user response:
The question is a bit misleading (in the way that it might interpreted that you want to clear the div content aka dom elements).
If you want to reset your input fields values, you can wrap your input fields into a HTML form
element and add an <input type="reset"/>
inside your form wrapper.
More info on this native element here: on developer.mozilla.org
If, for any reasons, you cannot update your HTML elements, you can create a function that you can run when you want (e.g. adding a reset button, create a hook for it and call the function):
function resetInputFields() {
// get all input elements with the class name 'input'
const elems = document.querySelectorAll('.input');
// set the value of each input to an empty string
elems.forEach(elem => elem.value = '');
}
CodePudding user response:
While you've already accepted an answer, I thought I'd offer another if only to show how much simpler this can be if you use the affordances and functionality offered through the use of semantic HTML elements such as, in this case, a <form>
to contain the <input>
elements.
Explanatory comments are in the code, below:
// until a following comment explicitly stating that the code is relevant, the following is only relevant to
// adding random data; irrelevant as it may be I will still explain it for the curious.
// Here we have an Array of names sorted alphabetically:
let names = ["Aaron", "Abigail", "Adam", "Alan", "Albert", "Alexander", "Alexis", "Alice", "Amanda", "Amber", "Amy", "Andrea", "Andrew", "Angela", "Ann", "Anna", "Anthony", "Arthur", "Ashley", "Austin", "Barbara", "Benjamin", "Betty", "Beverly", "Billy", "Bobby", "Brandon", "Brenda", "Brian", "Brittany", "Bruce", "Bryan", "Carl", "Carol", "Carolyn", "Catherine", "Charles", "Charlotte", "Cheryl", "Christian", "Christina", "Christine", "Christopher", "Cynthia", "Daniel", "Danielle", "David", "Deborah", "Debra", "Denise", "Dennis", "Diana", "Diane", "Donald", "Donna", "Doris", "Dorothy", "Douglas", "Dylan", "Edward", "Elijah", "Elizabeth", "Emily", "Emma", "Eric", "Ethan", "Eugene", "Evelyn", "Frances", "Frank", "Gabriel", "Gary", "George", "Gerald", "Gloria", "Grace", "Gregory", "Hannah", "Harold", "Heather", "Helen", "Henry", "Isabella", "Jack", "Jacob", "Jacqueline", "James", "Janet", "Janice", "Jason", "Jean", "Jeffrey", "Jennifer", "Jeremy", "Jerry", "Jesse", "Jessica", "Joan", "Joe", "John", "Johnny", "Jonathan", "Jordan", "Jose", "Joseph", "Joshua", "Joyce", "Juan", "Judith", "Judy", "Julia", "Julie", "Justin", "Karen", "Katherine", "Kathleen", "Kathryn", "Kayla", "Keith", "Kelly", "Kenneth", "Kevin", "Kimberly", "Kyle", "Larry", "Laura", "Lauren", "Lawrence", "Linda", "Lisa", "Logan", "Louis", "Madison", "Margaret", "Maria", "Marie", "Marilyn", "Mark", "Martha", "Mary", "Matthew", "Megan", "Melissa", "Michael", "Michelle", "Nancy", "Natalie", "Nathan", "Nicholas", "Nicole", "Noah", "Olivia", "Pamela", "Patricia", "Patrick", "Paul", "Peter", "Philip", "Rachel", "Ralph", "Randy", "Raymond", "Rebecca", "Richard", "Robert", "Roger", "Ronald", "Rose", "Roy", "Russell", "Ruth", "Ryan", "Samantha", "Samuel", "Sandra", "Sara", "Sarah", "Scott", "Sean", "Sharon", "Shirley", "Sophia", "Stephanie", "Stephen", "Steven", "Susan", "Teresa", "Terry", "Theresa", "Thomas", "Timothy", "Tyler", "Victoria", "Vincent", "Virginia", "Walter", "Wayne", "William", "Willie", "Zachary"],
// the randomFill function takes no arguments, and is written using Arrow syntax:
randomFill = () => {
// here we retrieve a NodeList of all '.input-fields' elements, and use an anonymous Arrow function
// taking only one argument, a reference to the current element node of the NodeList over which
// we're iterating:
document.querySelectorAll('.input-fields').forEach(
(group) => {
// here we get a random name from the Array of names using a simple function, multiplying the
// initial 0-1 value returned from Math.random() by the length of the Array, and flooring that
// value to retrieve an integer in the range of 0-names.length:
let randomPerson = names[Math.floor(Math.random() * names.length)],
// retrieving the child elements of the current 'group' ('.input-fields') element:
children = group.children;
// in the first <input> we set the value to the name we retrieved previously:
children[0].value = randomPerson;
// in the second we create a generic email address, using a template-literal string
// to concatenate the ranom name along with the string of '@example.org':
children[1].value = `${randomPerson}@example.org`;
// here we create a four-digit number (a generic extension-number, though this
// could be modified to create a real-looking generic number), first creating
// an Array from an Object with a length property set to 4:
children[2].value = Array.from({
length: 4
})
// we then use Array.prototype.map() to iterate over the four Array-elements:
.map(
// and use the anonymous Arrow function to generate a number in the range of
// 0-9:
() => Math.floor(Math.random() * 9)
// we then join the Array of numbers together, using Array.prototype.join() with
// an empty-string as the argument:
).join('');
// in the fourth element, we generate a typical subject-line, using another random-
// name from the Array of names (because I've used Math.random() so many times I
// would - in normal use - have abstracted this into its own function, but for this
// demo it's not too bad:
children[3].value = `Re: ${names[ Math.floor( Math.random() * names.length ) ]}`;
});
};
// here we retrieve the first element that matches the supplied selector, and binds the
// the randomFill function as the 'click' event-handler for that element:
document.querySelector('button.randomValues').addEventListener('click', randomFill);
// everything above this comment is only relevant for adding random data to the <input> elements;
// below this line is relevant to the demo:
// here we retrieve the only element that matches the CSS selector passed to document.querySelector();
// bear in mind that if no matching element is found the returned value will be null, so a sanity-check
// might be in order if the element isn't guaranteed to be present.
// We then use EventTarget.addEventListener to bind the anonymous Arrow function as the 'click'
// event-handler:
document.querySelector('button.nonFormResetButton').addEventListener('click', (e) => {
// e.currentTarget is the element to which the function is bound, from there
// we navigate to the closest ancesort element that matches the supplied CSS
// selector (again, if none is found the return-value will be null):
let ancestor = e.currentTarget.closest('.wrapper'),
// from the ancestor we retrieve the <input> elements:
inputs = ancestor.querySelectorAll('input');
// we use NodeList.prototype.forEach() to iterate over the <input> elements, again using
// an Arrow function, and passing in a reference to the element of the NodeList over
// which we're iterating:
inputs.forEach(
// and we set the value of the current <input> to its defaultValue, the value that it
// held on page-load:
(el) => el.value = el.defaultValue
)
});
:root {
--gap: 0.5em 1em;
}
*,
::before,
::after {
box-sizing: border-box;
font: normal 400 1rem / 1.5 sans-serif;
margin: 0;
padding: 0;
}
::before,
::after {
color: #999;
}
button.randomValues,
form,
.wrapper {
width: clamp(20rem, 80vw, 800px);
margin-block: 1em;
margin-inline: auto;
border: 1px solid #000;
padding: 1em;
}
form,
.wrapper {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: var(--gap);
}
form::before {
content: '<form> element';
}
.wrapper::before {
content: '<div> element';
}
fieldset,
.wrapper>div {
grid-column: 1 / -1;
}
.input-fields {
border: 0 none transparent;
display: grid;
gap: var(--gap);
margin-block-end: 0.5em;
}
button.randomValues {
display: block;
}
<button type="button" >Enter default values</button>
<form action="#">
<fieldset >
<input type="text" placeholder="Name">
<input type="text" placeholder="Email Address">
<input type="text" placeholder="Phone">
<input type="text" placeholder="Subject">
</fieldset>
<!-- note that there is no functionality added, bound or otherwise
provided to this element; its functionality lies in its type
and inherent behaviour in a <form> element: -->
<button type="reset">Clear</button>
<!-- remove 'type=button' to resume the default submission behaviour,
but submission is unwanted in this demo, hence setting the type
to 'button' -->
<button type="button">Send</button>
</form>
<div >
<div >
<input type="text" placeholder="Name">
<input type="text" placeholder="Email Address">
<input type="text" placeholder="Phone">
<input type="text" placeholder="Subject">
</div>
<button type="reset" >Clear</button>
<button type="button">Send</button>
</div>
References:
Array.prototype.from()
.Array.prototype.forEach()
.Array.prototype.map()
.- Arrow functions.
document.querySelector()
.document.querySelectorAll()
.Element.children
.Element.closest()
.EventTarget.addEventListener()
.HTMLInputElement
.Math.floor()
.Math.random()
.NodeList.prototype.forEach()
.- Template literals.