Form help(HTML/JS) - javascript

I'm (very) new to web development and am working on learning back-end currently.
I am trying to figure out how to use multiple inputs inside a form, but am struggling to get the actual input, instead of the element itself using this code to create the form:
<form id="newPostForm">
<input name="titleInput" placeholder="title"><br>
<input name="bodyInput" placeholder="body">
<button>Submit</button>
</form>
and this JS to try and output the user input to the console:
const newPost = document.getElementById("newPostForm")
const title = document.querySelector(".titleInput")
const body = document.querySelector(".bodyInput")
newPost.addEventListener("submit", (e) => {
e.preventDefault()
console.log(title, Body)
})
When I hit the submit button the console displays null null. This is probably a super simple question, but I'd appreciate any help.

After fixing the case issue with your body variable, you need to get the value of the inputs by accessing their value property. Then you want to move those variables into your submit handler, otherwise you're only getting the value once, when the page loads, and they're blank:
const newPost = document.getElementById("newPostForm");
newPost.addEventListener("submit", (e) => {
const title = document.querySelector(".titleInput").value;
const body = document.querySelector(".bodyInput").value;
e.preventDefault()
console.log(title, body)
})
<form id="newPostForm">
<input name="titleInput" class="titleInput" placeholder="title"><br>
<input name="bodyInput" class="bodyInput" placeholder="body">
<button>Submit</button>
</form>

Related

How to Display User Input (composed of a few submissions) in JavaScript?

I can't figure out what exactly am I doing wrong, I only get errors.
index.html
<div id="user-pets">
</div>
<form id="user-pets-form">
<input type="text">
<input type="submit">
</form>
index.js
document.querySelector("#user-pets")
const createPetForm = document.querySelector("#user-pets-form")
createPetForm.addEventListener("submit", (e) => {
e.preventDefault()
let pet = e.target.input.value
document.querySelector("#user-pets").innerHTML += pet
}
After Reviewing your code, you have made two mistakes let me explain,
In JavaScript Code you forgot to add small bracket on second last line,
that's why its through error
In Html you need to add name attribute to Input field, otherwise the listener of submit will always return undefined
I modified both code for you, please have look below
HTML
<div id="user-comments">
</div>
<form id="user-comments-form">
<input type="text" name="comments">
<input type="submit">
</form>
JavaScript
document.addEventListener('DOMContentLoaded', () => {
console.log("DOM is loaded")
document.querySelector("#user-comments")
const createCommentForm = document.querySelector("#user-comments-form")
createCommentForm.addEventListener("submit", (e) => {
e.preventDefault()
let comment = e.target.comments.value;
document.querySelector("#user-comments").innerHTML += comment;
})
})
I suggest you would change the second input to <button type="submit">Submit</button> and add the event listener to it (not the form). Then you can select the value of the input tag, insert it to the comment div when user clicks the submit button

How can i get value using data.get() function

I am trying to get the value of a textarea that I have append into a fieldset of my form.
To do so, when I submit my form, the following code is triggered:
function handleSubmit(e) {
e.preventDefault();
console.log(document.getElementById('Observation_1').value);
const data = new FormData(e.target);
const value = data.get('Observation_1');
console.log(value);
}
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
<form>
<textarea id="Observation_1"></textarea><br>
<button type="submit">Test</button>
</form>
however, my console.log (value); returns me null, while my console.log(document.getElementById('Observation_1').value);
return me the content of my textarea.
Can someone explain me why i have a null return and help me to fix my code so i can get the actual content of my textarea please.
You probably don't have a name="Observation_1" attribute on the textarea.

client-side javascript file set form tag attribute

I want to make a login, signup webpage with nodejs. So I use form tag to send url and method. In my case form tag has two different submit buttons.
below is HTML code
<form id="login">
<input type="text" placeholder="ID" id="id" name="id"> <br>
<input type="password" placeholder="password" id="passwd" name="passwd"> <br>
<input type="submit" value="login" id="login-btn">
<input type="submit" value="signup" id="signup-btn">
</form>
<script src="index.js"></script>
Since I want to make these two buttons work differently I write simple js file to set forms' action and method.
const response = document.getElementById('login');
const attribute = function(obj, action, method){
response.setAttribute('action', action);
response.setAttribute('method', method);
}
const login = document.getElementById('login-btn');
login.addEventListener('click', attribute(response, '/login', 'POST'));
const signup = document.getElementById('signup-btn');
signup.addEventListener('click', attribute(response, '/signup', 'GET'));
When I write like that both buttons work as signup button. So I only can access signup page.
However, when I write js file without declaring function
const response = document.getElementById('login');
const login = document.getElementById('login-btn');
login.addEventListener('click', () => {
response.setAttribute('action', "/login");
response.setAttribute('method', "POST");
});
const signup = document.getElementById('signup-btn');
signup.addEventListener('click', () => {
response.setAttribute('action', "/signup");
response.setAttribute('method', 'GET');
});
it works well.
Can you guys tell me what is different between two js codes? And why is this happening?
As per the MDN documentation for [addEventListener]1, the syntax is given by
target.addEventListener(type, listener [, options]);
listener
The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function. See The event listener callback for details on the callback itself.
If you observe the 2nd argument in the following line of code, you will notice, that it's not a function, it's rather the return value of the function, which is, undefined by default (because you haven't specified any return values) :
login.addEventListener('click', attribute(response, '/login', 'POST'));
To validate what I am saying here, please do the following:
typeof attribute(response, '/login', 'POST');
> undefined
So, essentially, this following line:
login.addEventListener('click', attribute(response, '/login', 'POST'));
evaluates to
login.addEventListener('click', undefined);
whereas, in the following snippet, the 2nd argument is clearly an arrow function:
document.getElementById('login-btn');
login.addEventListener('click', () => {
response.setAttribute('action', "/login");
response.setAttribute('method', "POST");
});
.. and that is the source of the difference in behavior between two.
I hope I clarified your doubt. If I din't, please post a comment.
You're trying to use attribute as the callback, but you're calling the function which returns undefined and when the click event happens it just tries to call undefined. You need to wrap those attribute calls in another function to be able to run it that way. Something like...
const login = document.getElementById('login-btn');
login.addEventListener('click', () => {
attribute(response, '/login', 'POST')
});
const signup = document.getElementById('signup-btn');
signup.addEventListener('click', () => {
attribute(response, '/signup', 'GET')
});

What code would I put in HTML to apply search filters?

I have provided an example of what it'd look like below. I'm trying to code a (rather nsfw) search table for people to use. I'm not sure how i'd code the filters for the search. I want to either be able to search by name, use the filters, or if you have filters applied, then the search bar only searches for results inside of those filters. I am using HTML, JS, and CSS only!
The Example Image (This is SFW)
Please don't skip because of the reason that this is for an NSFW website..
If you are using vanilla js, you can do a HTML with a form, and listen all the changes the form have when the user do click, something like this:
<form id="my-form">
<input type="text" name="username">
<input type="text" name="full-name">
<input type="password" name="password">
<button type="button" id="search">Search!</button>
</form>
const searchButton = document.getElementById("search")
const inputs = document.getElementById("my-form").elements;
const inputByIndex = inputs[0];
const inputByName = inputs["username"];
searchButton.addEventListener("click", functionWhichIWillCommunicateWithTheServer)
with the form values you can use something like fetch to communicate with your server.
// The parameters of the endpoint are comming from the form
function functionWhichIWillCommunicateWithTheServer() {
fetch("someEndpointWithTheirParameters")
.then(res => res.json())
.then(data => console.log(data))
}
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>

How to clear file(s) selection from file input after the data has successfully be submitted?

I am using react.js, I have a form, that I am submitting to an API and the form works fine up to the point where I want to clear the fields. Well actually one field in particular, the file input. I can't get it to reset back to "No File Selected", I've tried creating a files= attribute and controlling it through the state, and everything. Nothing is working, what am I missing?
I only want to reset it when there has been a successful submission.
What is the right approach to this.
<input
type="file"
name="js-case-upload"
className="form-control-static"
filename={this.state.files}
accept="image/*"
onChange={ this._onChangeFileInput }
/>
Considering the input have id myFile, then the file can be reset by vanilla javascript like the following:
document.getElementById("myFile").value = "";
const Upload = ({ onUpload }) => {
const ref = useRef();
const onChange = (e) => {
onUpload(e.target.files, () => {
ref.current.files = null;
});
};
return <input ref={ref} onChange={onChange} type="file" />;
};
I put a callback once I uploaded the file. On the callback I just set my files to null.
Consider adding a ref="file" to you file input, and after submitting the data, use something like this.refs.file.value = ''.
EDIT:
Even a simpler solution: https://jsfiddle.net/n06qk9h4/

Categories