Flask wtforms Integerfield() returning NaN - javascript

Can someone explain IntegerField() to me? I have searched everywhere and haven't found a good example for what I am looking for. I have a counter on my website; the up-arrow adds 1, the down-arrow subtracts 1. However, when I click either arrow, it just returns NaN, and it wont update. Any ideas?
wtform:
class BetaForm(FlaskForm):
streak = IntegerField('Streak')
total = IntegerField('Total')
submit = SubmitField('Update')
Route
def beta():
form = BetaForm()
if form.validate_on_submit():
current_user.streak = form.streak.data
current_user.total = form.total.data
db.session.commit()
flash('Your account has been updated!', 'success')
return render_template('betaone.html', form=form)
HTML:
<div class="row">
<p class="col-12 font100" id="streakcounter">{{ form.streak }}</p>
<button id="betabuttonplus" onclick="addStreak()"><i class="fa fa-plus"></i></button>
</div>
<form method="POST" action="">
<div class="form-group">
{{ form.submit(class="my-button btn btn-outline-info") }}
</div>
</form>
JS
function addStreak() {
var streak = document.getElementById("streakcounter").innerHTML;
streak++;
document.getElementById("streakcounter").innerHTML = streak;
}

The problem here is in javascript:
document.getElementById("streakcounter").innerHTML
retrieves the entire input element, but we only want to update its value attribute. This function will update the value correctly:
function addStreak() {
document.getElementById("streak").value++;
}
It's possible to avoid having to use javascript to update the form by using an html5 type="number" input; modern browsers will automatically provide up and down arrows ("spinners") to update the value. WTForms provides these inputs in its html5 modules.
from wtforms import Form
from wtforms.fields import html5 as h5fields
from wtforms.widgets import html5 as h5widgets
class MyForm(Form):
foo = h5fields.IntegerField('foo')
bar = h5fields.IntegerField('bar', widget=h5widgets.NumberInput(min=1, max=1000, step=5))
form = MyForm()
for f in form:print(f)
<input id="foo" name="foo" step="1" type="number" value="">
<input id="bar" max="1000" min="1" name="bar" step="5" type="number" value="">

Related

Reset (reset to previous value) only the form fields that are changed

I need to reset only the form fields that are changed (reset to previous value).
I tried to use the reset but it completely resets the entire form and I don't need this.
How can I do this?
function clearResult() {
document.getElementById("save").reset();
}
<div class = "container">
<form method="post" id="save" onload="onLoad()">
<div class="field">
<label for="id"> ID:</label>
<input type="number" id="id" name="id" />
</div>
<div class="field">
<label for="type"> Fragment Type: </label>
<input type="text" id="type" name="type" />
</div>
<div class="button">
<button type="submit" class="full">Save changes</button>
<input type="button" value="Cancel" onclick="clearResult()" />
</div>
</form>
</div>
First of all you should to store the predefined values of form elements to set them back when you want to reset them back.
Then you can use this globally defined initial values to set them back whnever reset event occurs.
var id, type;
const form = document.getElementById('save');
document.onload = (event) => {
id = form.id.value;
type = form.type.value;
};
function clearResult() {
form.id.value = id;
form.type.value = type;
};
It was simple. When page load just get values from that fields.
Make with document.onload:
var firstValue = document.getElementById("yourFieldId").value;
After form submit get values like below:
var currentValue = document.getElementById("yourFieldId").value;
And after submit in reset check if CURRENT VALUES equal with VALUES FROM FIRST TIME
Example
if(firstValue != currentValue){
document.getElementById("yourFieldId").value = firstValue;
}

Can't get my simple JavaScript Event Handler working

I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.
One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.
var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>

How to access form data nested inside divs (TypeScript)

In a following code I want to access user data written in a form each time user presses an enter key after typing some text data inside an input field in chat-form. Do you have any idea how can I access the following text-data using TypeScript? I have already tried with jQuery but none of the tested code seems to work. I am new to web-dev but very eager to learn new things.
<div id="chat-container">
<div id="search-container">
<input type="text" placeholder="search" />
</div>
<div id="conversation-list">
</div>
<div id="new-message-container">
+
</div>
<div id="chat-title">
</div>
<div id="chat-message-title">
</div>
<div id="chat-form">
<input id="chat-form" type="text" placeholder="Type a message!" />
</div>
</div>
first, you should use a semantic HTML by using form tag instead of div so u can use enter key to handle the submit action. second, it is not an appropriate way to duplicate an id for two different elements because id is a unique identifier for the element. finally here is a simple form and it might be helpful.
HTML:
<form id="my-form">
<input type="text" id="my-input" />
<button type="submit" id="submit-btn">send</button>
</form>
JS:
const formEl = document.getElementById("my-form") as HTMLFormElement;
const inputEl = formEl.querySelector("my-input") as HTMLInputElement;
const submitBtnEl = formEl.querySelector("submit-btn") as HTMLButtonElement;
formEl.addEventListener("submit", e => {
e.preventDefault();
// do what you want
});
inputEl.addEventListener("change", (e:Event|any) => {
console.log(e.target.value)
// do what you want
})
Before the answer: you have duplicated id="chat-form"
<div id="chat-form">
<input id="chat-form"type="text" placeholder="Type a message!"/>
</div>
Example
// select element
const elInput: HTMLInputElement = document.querySelector(`#chat-form-input`)
// add onkeypress listener
document.onkeypress = function (e: any) {
// use e.keyCode
if (e.key === 'Enter') {
// code for enter
console.log(elInput)
console.log(elInput.value)
}
}
<body>
<div id="chat-container">
<div id="search-container">
<input type="text" placeholder="search"/>
</div>
<div id="conversation-list">
</div>
<div id="new-message-container">
+
</div>
<div id="chat-title">
</div>
<div id="chat-message-title">
</div>
<div id="chat-form-container">
<input id="chat-form-input" type="text" placeholder="Type a message!"/>
</div>
</div>
</body>
You should try using a combination of JQuery.
Using this, you should put an id on the input element like so:
<input type="text" id="inputField" placeholder="search"/>
Then query the input field with JQuery. Best practice would suggest to store it in a local variable as well.
let inputFieldText = $("#inputField");
Then test for the value in the text field object as returned from JQuery.
if(inputFieldText.val()){
console.log(inputFieldText.val())
}
For reference, there is also a way to do so with document.getElementById("inputField"). Just link this function to a button that runs on pressing it (such as a "submit" button). Hope this helps!

onclick function getInc not defined

I am creating my first web app and have run in to an issue pretty early on!
I have created a function which extracts the information that the user keys into the HTML input field. The way it should work is that when the user enters their income and clicks the submit button, the income is stored in a variable for me to use throughout the rest of my JavaScript code.
Looking at the console log, the function is coming up as 'not defined'.
I appreciate the code is probably not very clean but I just want to get it working as it's my first small project!
Any ideas where I am going wrong?
Here's the HTML:
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit" onclick="getInc();">
</div>
Here's the JavaScript:
function getInc() {
var inc = document.getElementById("Ann-Sal");
}
I remove semiclon from onclick end and it works
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit" onclick="getInc()">
</div>
<script>
function getInc() {
console.log('works');
var inc = document.getElementById("Ann-Sal");
}
</script>
<script>
function getInc() {
console.log('works');
var inc = document.getElementById("Ann-Sal");
}
</script>
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit" onclick="getInc()">
</div>
First of all make sure you have your <script> after the body (ie: put it after the last closing <div>), secondly if you want to what the user typed in you should get the elements value. When you set inc equal to document.getElementById("Ann-Sal"); you are giving it the DOM element instead of the it's value instead you should put:
function getInc() {
var inc = document.getElementById("Ann-Sal");
}
Then you will get the value the user inputted to the code.
Also, a tip use addEventListener() instead of the onclick attribute, it's better practice.
Ok, so I tried to fix it myself using some of Tom O's code above here:
var buttonEl = document.querySelector('input[type="button"]');
var inputEl = document.getElementById("Ann-Sal");
var annInc;
function clickHandler() {
annInc = parseFloat(inputEl.value);
console.log(annInc);
}
buttonEl.addEventListener('click', clickHandler);
HTML:
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit">
</div>
This didn't work. There was no error message but nothing was logged to the console when submitting an income into the input field.
I then reconfigured the Javascript code to this:
var buttonEl = document.querySelector('input[type="button"]');
var inputEl = document.getElementById("Ann-Sal");
var annInc;
function clickHandler() {
if (!inputEl.value.length) {
console.error('A salary is required!');
return;
}
annInc = parseFloat(inputEl.value);
console.log(annInc);
}
buttonEl.addEventListener('click', clickHandler);
This then worked. I didn't use the if statement to validate the users input previously because I used 'required' in the input element within my HTML code which basically does the same thing right? So i'm guessing the reason why the code wasn't working because the 'return' statement wasn't used?
Would someone be kind enough to explain to me why the return statement enabled this to work?
I'm sure for some of you experienced guys, my lack of understanding must be painful for you! I am super determined to get my head around this though.
Many thanks
Besides the other answers, I just wanna point it out that is missing the .value in your function, otherwise, you won't get the value.
function getInc() {
var inc = document.getElementById("Ann-Sal").value
}

Forward GET parameter to next URL

I am building a form with HTML consisting of multiple pages, one per question (due to layout reasons). I use the 'GET' method to pass the parameters of the form input to next page, like this:
<form action="example.html" method="GET">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
This works fine and leads me to the URL
/example1.html?Machine=Input
On the next page, I use the same code as mentioned above (only different name and id for the input), but when I submit that page the parameters from the first page won't be redirected (of course). So the URL looks somewhat like this:
/example2.html?Amount=Input
I would need to have the parameters of the first page, too though. Basically looking like this
/example2.html?Machine=Input&Amount=Input
Is there a simple way for doing this with little Javascript or even without it? Thanks for your help
You could try adding hidden input elements to your form dynamically with javascript, created with name and value pairs from the GET parameters in document.location.search.
Click Run code snippet below to see a working example.
Instead of passing your results and going to the next step, you can just hide and reveal portions (steps) of the form using JavaScript.
A framework like AngularJS would make this extremely simple to do using declarative directive. But a plain old JavaScript will suffice.
The other advantage to this approach is that you can then POST your form to the web server.
function goTo(step) {
var steps = document.querySelectorAll('[step]'),
formStep,
formStepNo,
i;
for (i = 0; i < steps.length; i++) {
formStep = steps[i];
formStepNo = formStep.getAttribute('step');
if (step == formStepNo) {
formStep.style.display = 'block';
} else {
formStep.style.display = 'none';
}
}
}
var step = 1;
goTo(step);
function nextStep() {
step++;
goTo(step);
}
function backStep() {
step--;
goTo(step);
}
<form action="example.html" method="POST">
<div step="1">
<p>Step 1</p>
<input type="number" name="Machine" id="Machine" placeholder="Machine" />
<button onclick="nextStep()" type="button">Forward</button>
</div>
<div step="2">
<p>Step 2</p>
<input type="string" name="foo" placeholder="foo"/>
<button type="button" onclick="backStep()">Back</button>
<button type="button" onclick="nextStep()">Forward</button>
</div>
<div step="3">
<p>Step 3</p>
<input type="string" name="bar" placeholder="bar"/>
<button type="button" onclick="backStep()">Back</button>
<button type="submit">Submit</button>
</div>
</form>
Use this bit to get the parameters
How can I get query string values in JavaScript?
then this bit to add in the hidden form fields to the the form to pass along on the next submit
Create a hidden field in JavaScript
so something like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var Amount= getParameterByName('Amount');
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "Amount");
input.setAttribute("value", Amount);
document.getElementById("example2").appendChild(input);
<form action="example1.html" method="GET" id="example1">
<input type="number" step="0.1" name="Amount" id="Amount" placeholder="Amount">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
<form action="example2.html" method="GET" id="example2">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>

Categories

Resources