I've tried it a few different ways based on searches I've done on the subject and for some reason I can't get it to work. I just want my text inputs and textarea to clear after I hit the submit button.
Here's the code.
<div id="sidebar-info">
<form name="contact-form" action="formprocess.php" method="post" target="ninja-frame">
<h1>By Phone</h1>
<p id="by-phone">XXX-XXX-XXXX</p>
<h1>By Email</h1>
<p id="form-row">Name</p>
<input name="name" id="name" type="text" class="user-input" value="">
<p id="form-row">Email</p>
<input name="email" id="email" type="text" class="user-input" value="">
<p id="form-row">Message</p>
<textarea name="message" id="message" class="user-input" rows="10" maxlength="1500"></textarea>
<p>*Please fill out every field</p>
<input type="submit" value="Submit" id="submit" onclick="submitForm()">
<script>
function submitForm() {
document.contact-form.submit();
document.contact-form.reset();
}
</script>
</form>
</div>
Your form is being submitted already as your button is type submit. Which in most browsers would result in a form submission and loading of the server response rather than executing javascript on the page.
Change the type of the submit button to a button. Also, as this button is given the id submit, it will cause a conflict with Javascript's submit function. Change the id of this button. Try something like
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
Another issue in this instance is that the name of the form contains a - dash. However, Javascript translates - as a minus.
You will need to either use array based notation or use document.getElementById() / document.getElementsByName(). The getElementById() function returns the element instance directly as Id is unique (but it requires an Id to be set). The getElementsByName() returns an array of values that have the same name. In this instance as we have not set an id, we can use the getElementsByName with index 0.
Try the following
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
since you are using jquery library, i would advise you utilize the reset() method.
Firstly, add an id attribute to the form tag
<form id='myForm'>
Then on completion, clear your input fields as:
$('#myForm')[0].reset();
You can use HTMLFormElement.prototype.reset according to MDN
document.getElementById("myForm").reset();
You can try this:
function submitForm() {
$('form[name="contact-form"]').submit();
$('input[type="text"], textarea').val('');
}
This script needs jquery to be added on the page.
The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with
$('#element-id').val('')
For all input elements in the form this may work (i've never tried it)
$('#form-id').children('input').val('')
Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.
There may be a better way however this should work for you.
You can assign to the onsubmit property:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit
$('#contact-form input[type="text"]').val('');
$('#contact-form textarea').val('');
var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
btnSave.addEventListener("click", () => {
inputs.forEach((input) => (input.value = ""));
});
**Use the button you want to clear the inputs after clicking on it instead of the btnSave **
Just include this line at the end of function:
document.getElementById("btnsubmit").value = "";
I used the following with jQuery:
$("#submitForm").val("");
where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:
function extractValue() {
var value = $("#submitForm").val().trim();
console.log(value);
};
Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!
Related
I would like to add another input field into the form each time I click the button in the code below. Using appendChild(), it seems as though I can only do this one time. I tried adding the field using innerHTML, but this removes what has already been typed in the existing form fields. What would be the best way to achieve this with vanilla JavaScript while keeping what has already been typed into the form? Thank you in advance for your help.
let getArticleForm = document.getElementById("articleForm");
let cloneInputNode = document.getElementById("textInput").cloneNode(true);
cloneInputNode.setAttribute("id", "newId");
function addInput() {
getArticleForm.appendChild(cloneInputNode);
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
Codepen
Clone it inside the listener, else you've only created one clone (which gets removed from its prior location when appended again).
let getArticleForm = document.getElementById("articleForm");
function addInput() {
getArticleForm.appendChild(document.getElementById("textInput").cloneNode(true));
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
But there are some other fixes to make too:
The cloned nodes will all have the same ID, which is invalid HTML. While you could set a new ID for each input, dynamic IDs are an antipattern anyway - better to leave it off entirely IMO.
type="textarea" doesn't make sense as an attribute on an <input>. If you want a textarea, use a <textarea>.
Instead of cloning the existing input, consider just appending a new input.
const getArticleForm = document.getElementById("articleForm");
function addInput() {
getArticleForm.appendChild(document.createElement('input'));
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
I have a form that I am trying to validate using HTML 5 (and jQuery).
The form has initial values that are loaded in from a database. The users can edit the data and then submit the form. I have an input box with maxlength set to 6 but sometimes the value pulled from the DB has more than 6 characters in it. If the user doesn't do anything and just clicks submit then I want an HTML 5 validation warning. But the form just submits without a warning
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
I have tried adding a pattern {0,6} but this doesn't make any difference.
I don't want the form to remove characters automatically, the user must do this.
I tried using jQuery validate, but I don't think I am doing it correctly:
$(window).on("load", function() {
const $reading01 = document.querySelector('#reading01');
$reading01.validate();
}
If you normalise the <button> (ie. give it type="button" rather than type="submit") you can take advantage of the HTML5 Constraint API for Form Validation.
The HTML5 Constraint API enables you to define your own validation constraints.
Once the form validates, you can use submit() to submit the form.
Working Example:
const checkValuesForm = document.getElementById('checkValues');
checkValuesFormSubmitButton = checkValuesForm.querySelector('[data-type="submit"]');
const checkValues = (formSubmitted = false) => {
const reading01 = document.getElementById('reading01');
if (reading01.value.length > 6) {
reading01.setCustomValidity('This number cannot be more than 6 digits long');
reading01.reportValidity();
}
else {
reading01.setCustomValidity('');
if (formSubmitted === true) {
checkValuesForm.submit();
}
}
}
checkValuesFormSubmitButton.addEventListener('click', () => checkValues(true), false);
reading01.addEventListener('keyup', checkValues, false);
window.addEventListener('load', checkValues, false);
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" />
<button class="btn btn-primary" type="button" data-type="submit">Update</button>
</form>
Further Reading
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation
https://www.sitepoint.com/using-the-html5-constraint-api-for-form-validation/
you just need to display warning or prevent going further , in that case you can do your own validation by getting id and check it is empty or not.
Like Rounin says Je sus Monica said, using setCustomValidity is the cleanest way to send a message to inform of an error on a input. Still, since you are using a submit button, you can listen to your form's submit event and validate it before send the request. Also, you can use the Document.forms read only property, which returns a collection of HTMLFormElement. I like how it looks codewise, because it is very easy to understand that you are working with a form.
const form = document.forms['checkValues'];
form.addEventListener('submit', (e) => {
e.preventDefault();
const validatedInput = form.elements['reading01'];
if (validatedInput.value.length > 6) {
validatedInput.setCustomValidity("The input value cannot be longer than 6.");
return;
}
form.submit();
});
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
One more thing, and this is just a personal taste, when naming variables, I normally add the $ symbol for jQuery elements. So if by chance I am using a jQuery library, I can identify which variable holds a plain javascript element and which a jQuery element.
I have a HTML page containing a form. I want to make some fields "required". The problem is that I'm not using a <input type="submit"> in my form, instead, I use a Javascript function to submit the form because I need to send a Javascript variable to my server. Here is my code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="button" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
So, Even is I have the required attribute in my input but the form is still being submitted even if I don't enter anything in the input.
Here is a JSFiddle of how I want my form to behave when clicking on the button without entering anything.
Anyone knows how form.submit() is different from having an <input> of type="submit" ?
EDIT: After following user2696779's answer and doing a little modification, here's the final working code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="submit" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
if (frm.checkValidity()) {
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
}
Your current HTML input button isn't a submit type, it's a button type. The requred attribute on your input element is therefore ignored. To change this, change your button's type to submit:
<input type="submit" value="Submit">
Browsers which support the required attribute will now display a warning when the button is clicked:
JSFiddle demo.
Submitting using javascript will not trigger any validation. If you want to submit using a regular button + javascript and still have validation, you may use HTML5's checkValidity function to verify form fields, or the entire form.
For example, using JQuery:
if(!$('form')[0].checkValidity()) {
alert('not valid');
}
else {
$('form').submit();
}
See fiddle for working example: http://jsfiddle.net/8Kmck/2/
I have a simple form with one text field for testing. I need to have the info the user types in sent to console.log for now. Is this possible and if so what would I write?
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>
var nameInput = document.getElementById('name');
document.querySelector('form.pure-form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
console.log(nameInput.value);
});
Not sure why this question was down-voted. It's basic, but it's still a perfectly valid question.
The simplest way would be to grab the input by the ID then grab it's value and console.log it.
So, in a separate JavaScript file which you are included, or in a block, you would use:
console.log(document.getElementById('name').value);
You'll probably want to hook that to some event as well, so it prints each time they do something. The "change" event is probably the most appropriate. It fires every time the user types something and then changes focus (sometimes it'll also trigger when they stop typing, but not usually). If you want it to print every time a letter changes, you would want to use (one of) the "keydown", "keyup" or "keypress" events instead.
document.getElementById('name').addEventListener('input', function() {
console.log(this.value);
});
Sure
var input = document.getElementById('name');
console.log(input.value);
Here it is with an on change event as well as a keyup (in case you need to see it somewhat 'live').
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" onChange="inputChange(event)" onKeyUp="inputChange(event)" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>
<script type="text/javascript">
function inputChange(e) {
console.log(document.getElementById("name").value);
}
</script>
you can create a function like this and get the value of text box by its id.
function getData() {enter code here
let search = document.getElementById("search").value;
console.log(search);
}
I have a form in HTML with multiple inputs of type submit:
<form id = "myForm1" action="doSomethingImportant/10" class="postLink" method="post">
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
<input type="submit" value="clickThisLink"></input>
<input type="submit" value="Don'tclickThisLink"></input>
</form>
What I want to do is select only the first input with type submit while ignoring the others, the snippet of code I currently have is as follows, note it is within a for-each loop that goes through all forms on my page, hence (this) to avoid confusion:
var name = $(this).find("input[type='submit']").val();
I'm thinking this already grabs the first input of type submit by default, I'm not sure if that assumption is correct or if there's a more formal way of going about it, thanks.
Try:
$(this).children("input[type='submit']:first").val();
how about the first selector
var name = $("input[type='submit']:first").val();