I was wondering if there was a way to get the value of a form input value without having to use a event listener.
Heres the portion of the code related to that:
<form class="searchBar" id="form">
<input type="text" id="search" name="search" placeholder="Search">
<button type="submit" id="submit">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="#666666" d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z" />
</svg>
</form>
Heres what I've tried so far:
const form = document.getElementById('form');
const search = document.getElementById('search');
let query;
/*function submitted(event) {
event.preventDefault();
console.log(search.value)
search.value = "";
}
form.addEventListener('submit', submitted);*/
console.log(search.value)
The commented out code correctly displayed the search value, but this used the event listener.
I wanted to assign the search value to the query. When I commented out the block of code, nothing was displayed in the console after I typed in an input.
Wondering how to assign value of search.value to query.
It seems you are trying to get the value without submit event. If yes, Please try to do like this.
const form = document.getElementById('form');
const search = document.getElementById('search');
let query;
search.addEventListener('input', (event) => {
query = event.target.value;
});
Related
So I have this html form:
<form action="">
<input type="text" name="form-0-product_name" id="id-form-0-product_name">
<input type="text" name="form-0-product_price" id="id-form-0-product_price">
<button>Change form</button>
</form>
Please note the name and id attributes and how they contain "form-0". For a reason that doesn't really matter too much, I want the user to be able to click the "Change form" button and have all the instances of "form-0" change to "form-1". I came up with this javascript function that does that:
let button = document.querySelector("button");
let form = document.querySelector("form");
button.addEventListener("click", e => {
e.preventDefault();
const replacedForm = "form-0";
form.innerHTML = form.innerHTML.replaceAll(replacedForm, "form-1");
})
This does the trick of replacing the "form-0" strings with "form-1" ; however, it seems as though this completely resets the form. In other words, if the client has already typed some data into the text fields and then presses the change form button, the fields are cleared of their values. What I want to know is if there's a really efficient way to change the form's fields' attributes (mainly id and name) without clearing the values of the fields if their are values in them. Thanks and please let me know if I need to clarify.
You'll have to iterate over the elements and attributes individually.
let button = document.querySelector("button");
let form = document.querySelector("form");
button.addEventListener("click", e => {
e.preventDefault();
const replacedForm = "form-0";
// Select all elements with a name or id
for (const elm of form.querySelectorAll('[name], [id]')) {
for (const attrib of ['name', 'id']) {
elm[attrib] = elm[attrib].replaceAll(replacedForm, "form-1");
}
}
})
<form action="">
<input type="text" name="form-0-product_name" id="id-form-0-product_name">
<input type="text" name="form-0-product_price" id="id-form-0-product_price">
<button>Change form</button>
</form>
But this is a really strange thing to want to do in most cases. IDs in particular should not be dynamic. Strongly consider if there's an alternative way to approach the problem you're trying to solve.
You can also iterate over form.elements and modify the attribute's value property
const form = document.querySelector('form');
Array.from(form.elements).forEach(el => {
Array.from(el.attributes).forEach(att => {
att.value = att.value.replaceAll('form-0', 'form-1')
console.log(att.value)
});
})
<form action="">
<input type="text" name="form-0-product_name" id="id-form-0-product_name">
<input type="text" name="form-0-product_price" id="id-form-0-product_price">
<button>Change form</button>
</form>
I am trying to create a simple google search bar in my website. It works fine. However, I am accounting for user error, and for some reason I cannot re-enable my submit button once it is clicked, under the condition that no input is provided. Please see Javascript code below.
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
setTimeout(() => msg.remove(), 3000);
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
As you can see, if no text is input, it will let the user know they will need to enter an actual search query. However, after that point, the submit button just wont work again.
I tried using .querySelector().disabled = false; , as well as .removeAttribute("disabled"), but nothing is working. What exactly am I missing here, to re-activate the submit button once it was clicked with no input?
Your button works just fine. You just remove the complete element and then the msg = document.querySelector(".msg"); doesn't find anything. In addition i would leave the timeout out and let the message there until the user writes something.
You should do it like that:
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
msg.innerHTML= '';
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
When button type is set on submit value, it will send the information to the server anyway. (not if you use preventDefault() method!)
My suggestion is to change button type to button and then write an onclick event for it and check the validation there , if everything was right then call for form submit event!
This is how you can prevent incorrect information from being sent into the server side and avoid the errors that it can cause.
I am making a UI and below is my basic getting input from forms, but it won't display the value of secondLetter if I do it like
const form = document.querySelector('#form');
let firstLetter = document.querySelector('#firstLetter').value;
let secondLetter = document.querySelector('#secondLetter').value;
const output = document.querySelector('#check');
form.addEventListener('submit', function(e){
e.preventDefault();
console.log(secondLetter);
})
But If do it like
const form = document.querySelector('#form');
let firstLetter = document.querySelector('#firstLetter').value;
let secondLetter = document.querySelector('#secondLetter');
const output = document.querySelector('#check');
form.addEventListener('submit', function(e){
e.preventDefault();
console.log(form.secondLetter.value);
})
I get the value. I don't understand what I am doing wrong or why second example work and not first. Following is my HTML for reproducing purpose
<form id="form">
<label for="firstLetter">First Letter</label>
<input type="text" id="firstLetter">
<label for="secondLetter">Second Letter</label>
<input type="text" id="secondLetter">
<input type="submit" id="check">
</form>
Your 1st code runs when the page loads (your form laod):
let secondLetter = document.querySelector('#secondLetter').value;
so secondLetter will be set to value "" , even when your form will be submited the varable is already set so you will get "".
AT the 2nd code: you set secondLetter to the element reference, and only on submit you give the value to secondLetter, not before the submit.
<input type="text" id="secondLetter"> doesn't have a value attribute, so document.querySelector('#secondLetter').value is going to be an empty string.
(If you wanted to type something into the input and then read the value, then your JS would need to wait until something had been typed … you would normally use an Event Listener for that).
When testing code, any entered value to the list vanishes after pressing "enter".
I am very very new to programming and web development. Please be specific so I can understand.
function addItem(){
var item = document.getElementsByID("toDoInput").value;
var text = document.createTextNode("item");
var li = document.createElement("li");
newItem.appendChild(text);
document.getElementsByID("Ordered List").appendChild(newItem);
}
...
<head>
<link rel= "stylesheet" href = "styles.css">
</head>
<body>
<h1> To Do List </h1>
<form id = "toDoForm">
<input type = "text" id = "toDoInput">
<button type = "button" onclick = "addItem()"> Click Me </button>
</form>
<ul id = "Ordered List"></ul>
<script src="toDoList.js"></script>
...
I expect when I enter a word to the list, it will appear down below. Instead, it vanishes.
Any advice would help.
Your code is mostly right.
However, it had a few errors:
document.getElementsByID is not valid. It's document.getElementById
newItem is not declared. I think you meant li here
Both of these problems will have caused an error that would have made your function stop executing prematurely. You should get familiar with the console in your browser's developer tools and you will see that it will log errors there.
Additionally:
document.createTextNode("item") creates a text node with just the text "item". You'll want to use the value from the input box, instead.
You should be listening to the submit event, not the onclick event.
Unfortunately, you have to call preventDefault on the onsubmit to prevent the page from navigating elsewhere
You can trigger the submit event from the form using the button by making the button type submit
Here's a working version of your code:
function addItem(event) {
event.preventDefault(); // don't let the form POST
const input = document.getElementById("toDoInput");
const text = document.createTextNode(input.value);
const li = document.createElement("li");
li.appendChild(text);
document.getElementById("orderedList").appendChild(li);
input.value = "";
}
<h1>To Do List</h1>
<form id="toDoForm" onsubmit="addItem(event)">
<input type="text" id="toDoInput">
<button type="submit">Click Me</button>
</form>
<ul id="orderedList"></ul>
Alternatively, and this is better practice, don't use onsubmit on the markup at all and bind the event using addEventListener:
document.getElementById("toDoForm").addEventListener("submit", addItem);
I think it is unintentional form submit.
When you press enter in form, default behavior is to submit form. Then page will create request to server. In your case, there is no form action attribute, so you will observe page reload.
Possible solutions are:
Remove form (use div instead)
Disable submit on enter. This code will do the job.
document.getElementById("YOURFORMNAMEHERE").onkeypress = function(e) {
var key = e.charCode || e.keyCode || 0;
if (key == 13) {
e.preventDefault();
}
}
if you want to prevent the enter key action of clearing and submitting the form
function addItem() {
const input = document.getElementById("toDoInput");
const text = document.createTextNode(input.value);
const li = document.createElement("li");
li.appendChild(text);
document.getElementById("orderedList").appendChild(li);
input.value = "";
return false;
}
<form id="toDoForm" onsubmit="return addItem()">
<input type="text" id="toDoInput">
<button type="button" onclick="addItem()"> Click Me </button>
</form>
<ul id="orderedList"></ul>
I've got a form that creates inputs dynamically.
An example of it would be something like this:
<form>
<input name="item[0][name]">
<input name="item[1][name]">
</form>
The 0 and 1 being the id of the item.
Note that the 0 and 1 could be 15 and 49, or even 520, 854 and 2.
There's no order neither ordination and, there is also no limit for being only two items.
The question is:
"What is the best way of getting the values that will be typed at those inputs, before sending them to the backend?"
The only way I can think of is adding ids when generating the form, but that doesn't seem elegant at all.
If you cant figure a better way, that would be lovely =)
You can use document.querySelectorAll() and Attribute Selector
function submit() {
let inputs = document.querySelectorAll('input[name*=item]');
let values = Array.from(inputs).map(({value})=>value);
console.log(values);
}
<form>
<input name="item[0][name]">
<input name="item[1][name]">
</form>
<button onclick="submit()">Sumbit</button>
Try
function submit() {
let inputs = document.querySelectorAll('input');
let values = [...inputs].map(x=>x.value);
console.log(values);
}
<form>
<input name="item[0][name]">
<input name="item[1][name]">
</form>
<button onclick="submit()">Send</button>
You could use the HTMLFormElement.elements property.
const formInputs = document.getElementById('a-form').elements
const dataObject = {}
for (let i = 0; i < formInputs.length; i++) {
dataObject[formInputs[i].name] = formInputs[i].value
}
console.log(dataObject)
<form id="a-form">
<input type="text" name="item[0][name]" />
<input type="text" name="item[1][name]" />
<input type="text" name="item[2][name]" />
</form>
Set a specific data attribute (for instance data-my-input) on them, then use querySelectorAll(‘input[data-my-input]’) to get them all and send them to your backend.