onchange function does not work after reset the form - javascript

I have the following html and JS:
<body>
<form id="form_test">
<label>Your name: </label>
<input type="text" name="name">
<label>Your age: </label>
<input type="number" name="age" onchange="update()" value="0" min="0">
<button type="button" onclick="send(this.form)">Send</button>
</form>
<script>
function send(forma){
let data = Object.fromEntries((new FormData(forma)).entries());
console.log(data);
forma.reset();
}
function update(){
console.log('Input number has changed');
}
</script>
</body>
When I fill the form an send it with an age different of 1 I can go back and fill the form again, as you can see in the code, there is a console log for every time I change the age, however, If I send the form with an age of 1, and then I fill the form again, but changing the age with the input number buttons, it looks like the onchage event does not work, but if I change the value by typing everything works fine.
Do you know why this is happening? As I mentioned, this only happens after sending the form with the input number equals to 1 and by changing the value with the input number buttons.

Prefer to code this "natural" way:
const formTest = document.querySelector('#form_test') // same as CSS notation
formTest.onsubmit = evt =>
{
evt.preventDefault(); // disable form submit / page reload
let data = Object.fromEntries((new FormData(formTest)).entries());
console.clear();
console.log(data);
formTest.reset();
}
formTest.age.onchange = evt => // use form's elements names directly
{
console.clear();
console.log('Input number has changed :', formTest.age.valueAsNumber );
}
<form id="form_test">
<label>Your name: </label>
<input type="text" name="name">
<br> <br>
<label>Your age: </label>
<input type="number" name="age" value="0" min="0">
<br>
<br>
<button type="submit">Send</button>
</form>

Related

Use javascript with POST method

sorry for that, but I need your help on something :
I need to get my values in javascript, as it was filled in my form, and I have no clue how to do it, as whenever I tried to search, it was made for people with at least some understanding of javascript. I have none, but tried my best, the results of my efforts are here :
function validateForm() {
var x = form.('form').elements["sexe"];
if (x == null) {
alert("Un sexe doit être sélectionné");
return false;
}
}
I need to get it done by POST method, as get isn't allowed :
<form action="Monformulairedereferencement." method="post" id="sexe" name="form">
<div id="BlueBorder1">
sexe
<input type="radio" id="Homme" name="sexe" value="Homme" aria-checked="true">
<label for="Homme">Homme</label>
<input type="radio" id="Femme" name="sexe" value="Femme" aria-checked="true">
<label for="Femme">Femme</label>
<input type="radio" id="Autre" name="sexe" value="Autre" aria-checked="true">
<label for="Autre">Autre</label>
</div>
<div>
<label for="civilite">civilite</label>
<select name="civilite" id="civilite">
<option value="M.">M.</option>
<option value="Mme.">Mme.</option>
</select>
</div>
<div>
<label for="nom">nom</label>
<input type="text" id="nom" name="nom" minlength="2">
</div>
<div id="BlueBorder2">
<label for="email">email</label>
<input type="email" id="email">
</div>
<div>
<label for="telephone">telephone</label>
<input type="tel" id="telephone" name="telephone">
</div>
<div>
<label for="website">website</label>
<input type="url" name="website" id="website">
</div>
<div id="BlueBorder3">
<label for="datedenaissance">date de naissance</label>
<input type="date" id="datedenaissance" name="date de naissance">
</div>
<div>
hobbies
<input type="checkbox" id="Jeuxvideo" name="hobbies">
<label for="Jeuxvideo">Jeux video</label>
<input type="checkbox" id="Cinema" name="hobbies">
<label for="Cinema">Cinema</label>
<input type="checkbox" id="Lecture" name="hobbies">
<label for="Lecture">Lecture</label>
<input type="checkbox" id="Sport" name="hobbies">
<label for="Sport">Sport</label>
<input type="checkbox" id="Informatique" name="hobbies">
<label for="Informatique">Informatique</label>
</div>
<input id="token" name="token" type="hidden" value="my first website">
<div>
<label for="validation">validation</label>
<input type="submit" value="Envoyer le formulaire" id="validation">
If you have any clue of what isn't working or anything, then I'll gladly accept it. My only goal is to improve and I'm currently very bad.
Have a nice day and thanks for passing by :)
To get a value of a text input in JS, you need to get this input then get its value.
So for example: <input type="text" id="nom" name="nom" minlength="2">
to get this input value in JS, you have to follow 2 steps:
Assign the input element to variable -> let nom = document.getElementById('nom');
Get the value of this input element -> let nomValue = nom.value;
The previous approach can be applied to any text input (text, password, email, ...), textarea, & select menu
For checkboxes or radio buttons, you need to check if they are checked or not, for example: <input type="radio" id="Homme" name="sexe" value="Homme" > to check this, follow 2 steps:
Assign checkbox or radio button to a variable -> let Homme = document.getElementById('Homme');
Check if this checkbox or radio button is checked -> if (Homme.checked) {console.log('Checked')} else {console.log('Checked')}
For simple validation approach for your code, follow this snippet:
<!-- HTML Form -->
<form action="x.php" method="post" id="sexe" name="form">
<input type="text" id="nom" name="nom" minlength="2">
<input type="radio" id="Homme" name="sexe" value="Homme">
<input type="submit" value='Send' >
</form>
<!-- Validation Script -->
<script>
// Get Form Itself
let myForm = document.getElementById('sexe');
// Add Event To Form On Submit, Trigger The Validation Funcntion
myForm.addEventListener('submit', validateForm)
// Validate Form Function
function validateForm(e) {
// Get All Inputs In Your Form
let nom = document.getElementById('nom'); // Text Input
let Homme = document.getElementById('Homme'); // Radio Input
// Check Text Input Value If Not Empty
if(nom.value === '') {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Name Can Not Be Empty');
}
// Check If Radio Button Not Checked
else if (!Homme.checked) {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Radio Button Is Required');
}
// If The Previous Two Validation Steps Is Done And No Errors, The Form Will Be Sent
}
</script>
In my view, the easiest way to grab the value from the form is to use addEventListners with Submit event. It looks likes an element.addEventListner('submit',function);
var forms = document.getElementsByTagName('form'); //we have selected whole form
function formSubmitted(){
const emails = document.getElementsById('email');//select the email section
let emailValue = emails.value // it will give you the value of email after submitting
}
forms.addEventListner('submit',formSubmitted);//eventlistern which run after submiting the data in form

Send date from html form to Google calendar, etc

This is a noob question. What I'd like to do is set up a birthday party reservation website that has people fill out a form: yes/ no will attend, name, email. After the form is filled out for 'will attend' I'd like to have a popup modal that has the option to 'add to your calendar: Google, iCal, etc.'
Is this possible in an html form (javascript/ ajax)? I know it can be done in WordPress.
Thank you for any help/ suggestions.
Here is a very basic idea of what you could do. I put the form in the console using the answer here: https://stackoverflow.com/a/47188324/12946266 you will need to use php to operate on this form most likely, but I can't use that here.
const form = document.querySelector('form');
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
var values = Object.values(form).reduce((obj, field) => {
if(field.type=='radio'){
obj[field.name] = field.checked;
}else{
obj[field.name] = field.value;
}
return obj
}, {})
console.log(values);
});
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname" value=""><br> Last name: <input type="text" name="lname" value=""><br> email: <input type="text" name="email" value=""><br>
<input type="radio" id="attending" name="attendance" value="attending">
<label for="attending">attending</label>
<br>
<input type="submit" value="Submit"><br>
</form>

How to transfer values from between input

Before anyone marks this as a duplicate, I have looked at many sites and am currently using this one - jQuery - passing value from one input to another for guidance, yet no result... I am trying to pass a value from one input in one form to another input in a 'table'. I have put it in a table because of a very weird reason - it does not display a Sparql value when in a form only displays in a table so the input was placed in a table. My code is below:
Form
<form onclick="txtFullName.value = txtFirstName.value +'_'+ txtLastName.value">
First name : <input type="text" name="txtFirstName" value="#ViewBag.FirstName"/> <br><br>
Last name : <input type="text" name="txtLastName" value="#ViewBag.LastName" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
Table
<table id="results">
<Full name:
<br>
<input id="userInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="submit" type="submit" value="Submit">
</table>
JQUERY
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('txtFullName').val($(this).val());
});
});
I am trying to display the txtFullName into userInput input when pressing submit but right now only the `txtFullName' is displayed when pressing submit. Also the submit is the submit button in the FORM.
Anymore info needed let me know:)
You need to change the onclick to action on the form if you are trying to use submit button. The other way is to use input type button instead of submit:
So:
$(document).ready(function() {
$('#submit12').on('click', function (e) {
console.log('test');
$("#txtFullName").val($("#txtFirstName").val() + '_' + $("#txtLastName").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name : <input type="text" id="txtFirstName" value="First"/> <br><br>
Last name : <input type="text" id="txtLastName" value="Last" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
If you want to display txtFullName into userInput, simply do something like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').val($('#txtFullName').val());
});
And why do you need change function there , if yo need changes when click submit.
Edit your JQuery like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('#txtFullName').val($(this).val());
});
});
$('#submit').on('click', function () { //Form submit
$('#userInput').val($('#txtFullName').val());
});
I don't clearly understand why you do it but It can fix your code.
It is not entirely clear what the two buttons do, but the operation itself is really very simple. See comments inline for explanations:
// Wait until the DOM is loaded and all elements are avaialble
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you'll need
var theForm = document.getElementById("frmTest");
var txtFirstName = document.getElementById("txtFirstName");
var txtLasttName = document.getElementById("txtLastName");
var txtFulltName = document.getElementById("txtFullName");
var txtUserInput = document.getElementById("txtUserInput");
var btn1 = document.getElementById("btnSubmit1");
var btn2 = document.getElementById("btnSubmit2");
// Function to join names together
function combine(){
txtFullName.value = txtFirstName.value + '_' + txtLastName.value;
}
// Set event handlers
frmTest.addEventListener("click", combine);
btn1.addEventListener("click", combine);
});
<!-- Keep you JavaScript out of your HTML -->
<form id="frmTest">
First name : <input type="text" id="txtFirstName" name="txtFirstName" value="#ViewBag.FirstName">
<br><br>
Last name : <input type="text" id="txtLastName" name="txtLastName" value="#ViewBag.LastName" >
<br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="btnSubmit1" type="button" value="Combine Names">
<table id="results">
<Full name:
<br>
<input id="txtUserInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="btnSubmit2" type="submit" value="Submit">
</table>
</form>

Store input radio selections when submit is clicked

I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.

How to genetrate input field and their value based on user input on the other input field in jquery

I have an input field where user will enter isbn number based on the input number i need to populate two input field i.e book title and book author name i am calling a javscript function on onblur of input and i am getting the correct value but my problem is that if user will not move their cursor from the input field and click on submit button then how i will populate these two input field in these scenario onblur is not working
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number" onblur="getdetail()">
</form>
Pick your preferred solution and adapt it to your website:
1) If your browser supports it, the easiest is make all your fields required and use onchange instead of onblur. This will force the user to enter an isbn, which will trigger the onchange containing more inputs with required.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price" required>
<input type="text" name="isbn_number" id="isbn_number" onchange="getdetail()" required>
</form>
2) Do manual submitting after checking fields.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number" onblur="getdetail()">
<input type="submit">
</form>
<script>
document.querySelector('input[type="submit"]').addEventListener('click', function ( event ) {
var valid = false;
event.preventDefault();
// ...
// add validation code here.
// ...
if (valid) document.querySelector('#post').submit();
});
</script>
3) Only activate the submit if everything is valid.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number">
<input type="submit" disabled="disabled">
</form>
<script>
var valid = false;
document.querySelector('#post').addEventListener('change', function ( event ) {
if (event.target.name === 'isbn_number') getdetail();
// ...
// add validation code
// if (stuff && stuff && stuff) valid = true;
if (valid) document.querySelector('input[type="submit"]').removeAttribute('disabled');
});
</script>

Categories

Resources