I want to validate user input so he only provides numbers from a certain range with 0,5 steps. But I want my website to do it every time user swaps to another input form, not after he sends the data to my view. Can you give a hint of how should it be done? I don't know Javascript but I know there is onfocusout DOM event. Is it correct approach to use it, check whether or not value is valid and display an alarm based on that?
In general, there's no problem using onfocusevent.
Here's a hint on how to do this:
Create the input field
Add the onfocusout event handler and assign it a JavaScript function
Define the JavaScript function responsible for the validation process (which is, the same function we talked about in step 2)
This function takes the value inside the field and compares it, if it's not inside the range you desire then you can show an alarm or something like this.
I made a demo that doesn't involve alarming the user but instead it colors the border with either green or red, when you get desperate pay it a visit:
<input type="number" id="field1" onfocusout="validateField(0, 100, 'field1')"/><br/><br/>
<input type="number" id="field2" onfocusout="validateField(200, 300, 'field2')"/><br/><br/>
<input type="number" id="field3" onfocusout="validateField(400, 500, 'field3')"/><br/><br/>
<script>
function validateField(min, max, id) {
const value = document.getElementById(id).value;
if (value < min || value > max) {
document.getElementById(id).style.borderColor = "red";
}
else {
document.getElementById(id).style.borderColor = "lime";
}
}
</script>
Related
I have three user inputs which take any number. If a user leaves an input empty then clicks the submit button I would like that input to return 0.
What would be the best way to handle this?
I have created an if statement that individually looks for if input 1 or input 2 or input 3 is empty, but what if input 1 and 2 are empty or if input 3 and 1 are empty, this will lead to quite a long if statement
I wanted to know what would be the best way to go about solving this?
*.js
If( hours === 0 ){
hours = 0
}else if ( minutes === 0 ){
minutes = 0
}else if ( seconds === 0 ){
seconds = 0
}
// more if statement with different combination of minutes seconds and hours being 0
Create a function that does that work and then pass the input value to the function. Call the function for each input.
function checkInput(input){
if(!input.value){
input.value = 0;
}
}
// Find all the <input> elements and loop thorugh them
document.querySelectorAll("input").forEach(function(element){
checkInput(element); // Call the checkInput function and pass the current input
});
<input>
<input>
<input>
You can also avoid the JavaScript completely by using more precise HTML:
<input type="number" required value="0">
<input type="number" required value="0">
<input type="number" required value="0">
First off, You can make sure the user enters a value in the input using the required attribute.
<input type="text" required>
Also If it's inserting into the database, you just need to change the column data type which the value is inserting, to a data type of INT. That way the default is always going to be zero.
But if you still need to check...
if(#inputid.value === ""){
#inputid.value = 0;}
Also remember to get all the inputid using querySelectorAll("#inputid")
Then make it an array using var id = Array.from();
Then loop through id using foreach to check the if statement.
I try to do simple code for guessing notes by ear. I have tabs with several empty input fields and you need to put right numbers in these fields according to certain melody (for guitar fretboard) . One button shows first note, another button checks whether you put right or wrong number and depend on it approves or erase your number.
I know how to check every input field using its id's but can i do it such way that when i push 2nd button it get value from selected input and compare it to its placeholder or value attribute?
It is my codepen
https://codepen.io/fukenist/pen/BxJRwW
Script part
function showfirst() {
document.getElementById("fst").value = "12"
}
function show1other() {
var snote = document.getElementById("scnd").value;
if (snote == 9 ){
document.getElementById("scnd").value = "9";
}
else {
document.getElementById("scnd").value = "";
}
}
You can use document.querySelectorAll() to get all your inputs and loop over them.
Sample:
// Get all inputs as an array (actually NodeList, to be precise; but it behaves similar to an array for this use case)
var inputs = document.querySelectorAll('input');
// Function to reveal the first input's value
function showFirst(){
inputs[0].value = inputs[0].dataset.v;
}
// Function to check all values and clear input if wrong
function checkAll(){
inputs.forEach(function(input){
if(input.dataset.v !== input.value){
// Wrong answer, clear input
input.value = '';
}
});
}
<input data-v="12" size="2" value=""/>
<input data-v="9" size="2" value=""/>
<input data-v="8" size="2" value=""/>
<br/>
<button onclick="showFirst()">Show First</button>
<button onclick="checkAll()">Check All</button>
Notes:
I have used data-v to store the correct answer instead of placeholder as that attribute has a semantically different meaning
It may be out of turn but my two cents: Writing out entire songs like this by hand may become tedious. Consider using a JSON string or something similar to map out the tabs and use a templating framework to align them.. Some things you may need to look out for while designing something like this : Alignment of notes (successive notes, simultaneous notes), timing of the song, special moves like slide, hammer on etc.
It may be a better idea to make the Guitar Strings be a background element (either as a background-image or as absolutely positioned overlapping divs) (so You don't have to worry about the lines going out of alignment)
Reference:
HTMLElement.dataset
document.querySelectorAll
I am using a range slider with text box, so whenever I slide the range, the value gets updated in the textbox. Also whenever I change the value in the textbox, the slider will move accordingly.
Here is the code I am using:
$('input[type="range"]').on('input change', function() {
$('#LoanAmntText').val($(this).val());
});
$('#LoanAmntText').keyup(function(e) {
var val = $(this).val().replace(/[^\d\+]/g, ""); // check only for digits
$('#LoanAmntRange').val(val).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" min="0" max="20000000" step="100000" value="4000000" id="LoanAmntRange" class="LoanAmntRange">
<input type="text" id="LoanAmntText" />
The slider's min, max and step values are used in a way that it will cover most common values while using the range slider. But when I use the textbox to enter the value, I would like to use any number starting from 0( for ex:I need to enter 2450003).But with current code, it's not allowing me to do so.
What will be the best way to achieve this?
Fiddle:https://jsfiddle.net/anoopcr/cy14pu1L/11/
Your keyup event will trigger after every key press. Since your slider has a step size of 100000 no one digit will able to comply with that. Either change your step size to 1 or use the change event instead.
Beginner level with Javascript and have a question regarding the input type color.
I am trying to make the user choose the color black before proceeding with next page of the form. The default color is yellow.
Could someone please help me with this and explain where I have gone wrong or missing something?
And have done research to try figure it out myself but stuck, probably the simplest thing as per normal. Thanks
Here is a snippet:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.style.backgroundColor =='rgb(255, 153, 153)') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
}
function spamCheck() {
//alert("Spam Check Working.......");
var color = document.getElementById("color").value;
if (!color == "#000000") {
alert("Please enter the color black to proceed.");
color.focus;
return false;
}
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<button type="submit" onClick="validate(), spamCheck()">Continue → </button>
</span>
</form>
There a couple of things to be improved here as the logic does not really add up. Heres your code, amended and annotated with comments:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
// When using the `not equal` operator, use it _in the operator_.
// Putting a `!` in front of a variable will change the variable first
// before comparing. This can cause unexpected issues!
// Also added a type check as the button does not have a value of
// '#000000', so the alert would _always_ show. This prevents that.
if (element.type === 'color' && element.value !== '#000000') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
function spamCheck() {
// As you want to focus on this element later, store the element
// NOT the value.
var color = document.getElementById("color");
// This is the point where the placement of the `!` is changed
// Because if you invert the value of a string, you might get
// unexpected results!
if (color.value !== "#000000") {
alert("Please enter the color black to proceed.");
// Focus is a _method_ of an <input> node,
// not a property, so call it with ().
// Also, because you originally set color to the _value_,
// it is only a string and not the <node>
color.focus();
return false;
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<!-- To prevent submission, your onclick is changed -->
<button type="submit" onClick="return (validate() && spamCheck())">Continue → </button>
</span>
</form>
Please note that your validate() will always throw an alert as your button does not have a value of #000000, which is also considered an element. Therefor not all elements pass your test. However, I have amended this by checking if the elements type is that of color, and only then checking for that value and alerting.
But here's the main issue: how do you do this properly? Well, javascript uses event listeners for that, and it could greatly improve your code. I have added my suggestion to the snippet below. Keep in mind that attaching events to HTML elements using onSomething attributes on elements is considered bad practise. That's mostly because it makes your code too tightly coupled together, meaning that if you have to amend it later it will be a mix of JS, HTML and other elements thrown in and it will become confusing.
Event Listeners solve that issue for you, you can attach them to the element using only javascript, but that does mean that your form can be subm,itted without javascript. That's technically what you want - but keep in mind that SPAM bots usually disable javascript anyhow, so nothing of what you do has any affect unless you write your form using only javascript.
Now, onto an improved version of the provided code that is not as tightly coupled. I added some properties to your HTML (and removed other just to make it simpler but you can keep the spans, for example). These properties are not tightly coupled to JS. They are there for JS to read, but make no difference otherwise. It also means someone who only knows HTML can edit the messages.
The checkColor is now also rolled into your validation function, as is validation to anything. Now even better would be to check using regex patterns, but that's beyond the scope of this question.
var form = document.getElementById('myForm');
// Only run this function when a submit button is clicked and the form is
// considered to be submitted. Pass the function an event as well.
form.addEventListener('submit', function(event){
// Lets assume the form is valid
var isValid = true;
// Lets use a standard for loop, it's easier to read
for(var i = 0, element; element = form.elements[i]; i++){
// I;ve added two data-properties in your HTML, one that tells us what
// value your are looking for and another that provides the hint
// you want to show people
var match = element.getAttribute('data-match');
var hint = element.getAttribute('data-hint');
// If there is something to match and it does not match the value provided
// then set isValid to false and alert the hint (if there is one);
if(match && match !== element.value){
isValid = false;
if(hint) alert(hint);
}
}
// If one element has set the isValid to false, then we want to prevent
// the form from actually submitting. Heres were the event comes into play:
// event.preventDefault() will stop the form from actually submitting.
if(!isValid) event.preventDefault();
});
<form id="myForm">
<input name="color" id="color" data-hint="Enter the color black in HEX to proceed." data-match="#000000" type="color" placeholder="#000000" />
<input type="submit" value="Continue →" />
</form>
Just use change the if statement to look like this if (color !== "#000000")in the spamCheck functtion now we can check if the color is the correct value.
here is an example try to change the color to black and the alert will change.
I'm working on this eCommerce project where I need to calculate "shipping costs" if a particular checkbox is checked.
Here's the code for the checkbox :-
<div class="alert alert-info">
<p>Shipping Outside Lagos (N2, 000)</p>
<input type="checkbox" name="shipping" id="shipping">
</div>
How can I write the jQuery function, so that when the input is checked..I can get the value in a variable. Suppose the default value is 2000, how would I be able to get $amount=2000 (if checked) and $amount remains 0 if unchecked.
Due to my limited knowledge in jQuery / JavaScript, I'm unable to find a solution for it.
Search didn't help either.
Any suggestions are welcome.
var amount = $('#shipping').is(':checked') ? 2000 : 0;
$('#shipping').on('change', function() {
amount = this.checked ? 2000 : 0;
});
// use amount
You can do:
var shippingAmt = 0;
$("#shipping").change(function() {
shippingAmt = this.checked ? 2000 : 0;
});
I'd suggest using a function to determine the cost of items. You could have an abstract of determining costs which would run through a few or several conditions to calculate 'add ons' so to speak.
So you'd have your initial total of say $500.99, then run that value through something like calculateTotalValue(value)
It would check if any add-ons were checked in the form, and add their values to the initial value.
This would allow you to have any number of extras, like shipping, or even add-ons/upgrades for the product itself, and you'd be able to fetch the total without fail in each case. You could have a generic way of stipulating that a field is an 'add on' so you wouldn't need to maintain a list, like so:
<input type="checkbox" rel="add-on" data-add-on-type="shipping" value="500">
Then in your function,
calculateTotalValue(value) {
$.each($('input[rel="add-on"]'), function(i) {
// You probably want some error checking here
value += this.val();
});
return value;
}
If necessary you could use data-add-on-type to keep track of where costs comes from to output a list for the user, as well.