I am using a form to get a word from a user then displaying it on a web page, here is my js code:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('form').onsubmit = function() {
const word = document.querySelector('#wrd').value;
const header = document.querySelector('h1');
document.querySelector('h1').innerHTML = word;
}
});
the word flickers for a second then disappears,can you help me?
You must be submitting more than once while cleaning document.querySelector('#wrd').value if that's the only way to fill document.querySelector('h1'). Also, you might be reloading the page, without looking into your code I can't say for sure. The default behaviour of html submit is to reload the page, which would make it empty and appear to "flick"
When you submit a form it's synchronous by default. It takes the action attribute on the form and tries to post data to it. So in order to prevent that you have to capture the event and prevent its default action.
Take an example below for the different forms.
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#form1').onsubmit = function() {
const word = document.querySelector('#wrd').value;
document.querySelector('h1#first').innerHTML = word;
}
document.querySelector('#form2').onsubmit = function(e) {
e.preventDefault();
const word = document.querySelector('#wrd2').value;
document.querySelector('h1#second').innerHTML = word;
}
});
<form id="form1">
<input type="text" id="wrd" name="content" />
<button type="submit">Regular Submit</button>
</form>
<h1 id="first"></h1>
<hr>
<form id="form2">
<input type="text" id="wrd2" name="content" />
<button type="submit">Submit w/ Default Action Prevented</button>
</form>
<h1 id="second"></h1>
Related
Due to the layout of my page I would like to place a custom element outside of a form.
Can I make something like <my-custom-element form="foo"> work?
Presuming you want the submit button to return the value of your element even though it is outside the form. This is one way, there are many more (including using the function here called addExtras() to dynamically append your external name/value pair(s) to the form).
<my-custom-element> <input name="custom" id="custom" value="foo"></my-custom-element>
<form id="myForm" onsubmit="return addExtras()" method="post">
<input type="hidden"" name="customItem" id="customItem" />
<input name="anotherField" value="india" />
<button type="submit">submit</button>
</form>
<script>
function addExtras() {
document.getElementById("customItem").value = document.getElementById("custom").value;
return true;
}
// ==========================================================
//Code to display the submitted items, and prevent submission for test purposes
//Not needed for production
document.getElementById("myForm").addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
for (var i = 0; i < document.getElementById("myForm").elements.length; i++) {
var e = document.getElementById("myForm").elements[i];
console.log(e.name, e.value)
}
});
</script>
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.
Hi I'm in the process of building a basic tableau extension using HTML and JavaScript that takes start and end dates from the user, on submission of which my view in Tableau gets filtered to the range.
However, each time I click submit in the form the dates keep getting resetting to the default value defined in my HTML code and passes that to my JS code to process. It does not retain the user input, could someone have a look at the code below and advise on what I'm missing here?
<html>
<head>
<title>My Extension</title>
<script src="/tableau.extensions.1.latest.js"></script>
</head>
<body>
<h1>Hello! This is a basic filter extension</h1>
<form>
<label for="sdate">Start Date:</label><br>
<input type="date" id="sdate" name="sdate" value="2015-01-01"><br>
<label for="ldate">End Date:</label><br>
<input type="date" id="ldate" name="ldate" value="2016-01-01"><br><br>
<button onclick="tableau.extensions.initializeAsync()">Submit</button>
<script>
tableau.extensions.initializeAsync().then(() => {
let fieldName = 'Order Date';
let dashboard = tableau.extensions.dashboardContent.dashboard;
let selectedWorksheet = dashboard.worksheets.find(w => w.name === 'Sale Map (2)');
updateFilterRange(selectedWorksheet, fieldName);
});
function updateFilterRange(worksheet, fieldName) {
let today=new Date();
var lastDate=new Date(document.getElementById("ldate").value);
var startDate=new Date(document.getElementById("sdate").value);
worksheet.applyRangeFilterAsync(fieldName, { min: startDate, max: lastDate});
}
</script>
</form>
</body>
</html>
You can try this. Add an id to that button and add an eventlistener to prevent the default way form submission is handled
<button id = "submit">Submit</button>
<!-- HTML Code -->
<script>
const button = document.getElementById("submit")
button.addEventListener("click", function(e) {
e.preventDefault()
// Your code for handling button click
}
</script>
Add the button type to your button type="button" or return false in the onclick.
<button type="button" onclick="tableau.extensions.initializeAsync()">Submit</button>
Or
<button onclick="tableau.extensions.initializeAsync(); return false">Submit</button>
By default button type is submit you have to change it to button like following
<button type="button">
If you have form element, when you click button, it will submitted and becoz you have not set form action url, it will just reload page, so your input elements will be setted as defult string.
so, you have to prevent form action.
If you have only one button on your page, you can do like this
$('button').onClick(function (e)){
// button actions here.
e.preventDefault();
}
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 have a legacy HTML form (that i dont control) that looks like this:
<form action="submit_action" method="get">
<textarea rows="4" cols="40" name="textarea1"></textarea>
<input type="submit" value="Submit" name="result" />
<input type="submit" value="Cancel" name="result" />
</form>
I need to read the values out of this form and do a HTTP POST to a REST API service. I wrote a function that would read out the input elements from the form and create a object from them like this:
const form = this._elementRef.nativeElement.querySelector('form');
form.onsubmit = (event) => this.onFormSubmit(event);
function onFormSubmit() {
event.preventDefault();
const action = form.attributes['action'].value;
let result = Object.keys(form.elements).reduce((acc, k) => {
const element = form.elements[k];
acc[element.name] = element.value;
return acc;
}, {});
console.log('Form Result', action, result);
}
In a classical form submit, the button that triggered the submission is passed a parameter. In this example: https://www.w3schools.com/tags/att_button_name.asp you see when you click the FORM it passes the button that was clicked in the post.
Is there a better way to do this so that I can read that out?