Function is not reading data - javascript

I have an issue with my script. I have an editable field and button next to it. I tried to make a function that will start working after I will press the button and it will read data from my input field, hover it doesn't read any value from my input field and returns that the input is empty. Could you please suggest any possible solutions to it? I cannot change any input or button types to other ones. Full code: https://codesandbox.io/s/cocky-black-7mezc?file=/code.html
const trigger =
document.getElementById("poga1");
trigger.addEventListener("click", next);
function next() {
document.getElementById("input")
// default to no data
let message = "there are no data!";
const output = document.getElementById("output");
// get the value, this will be text - trim all leading and trailing spaces
const value = this.value.trim();
if (value !== "") {
// try to convert it to an integer
const numeric = parseInt(value);
// check if it's a number and if it matches what was entered
if (isNaN(numeric) || numeric != value) {
message = "not a number";
} else
if (numeric >= 1 && numeric <= 3) {
message = "not passed";
} else if (numeric >= 4 && numeric <= 10) {
message = "passed!";
} else {
message = "wrong data";
}
}
output.textContent = message;
};
<span contenteditable="true"><p id="input"></p></span>
<button id="poga1">Check!</button>
<span contenteditable="true"><p id="output">Vispirms ievadi datus!</p></span>

If you are trying to read the content of the element with an id input, then you have to change the line
const value = this.value.trim();
to
const value = input.innerText.trim();

Related

Formatting input type="text" in JS

I have a text field with type='text' and I am trying to format the text with commas. Example: 500000000 would become 500,000,000.
I have the following code:
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
However, it's printing 5,000,0,0,0,000 and the formatting is off for some reason. I also tried .toLocaleString(), but that doesn't seem to work either. What am I doing wrong here?
I was referred to a few other posts on Stack Overflow, but nothing seems to work out.
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g,''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
You can do this by converting the number to a string, then manually iterating over each character and find places where a comma is needed.
function formatNumber(number) {
var str = number.toString();
var offset = str.length % 3;
var newStr = '';
for (var i = 0; i < str.length; i++) {
if (i > 0 && i % 3 === offset) {
newStr += ',';
}
newStr += str[i];
}
console.log(str, '=>', newStr);
}
formatNumber(5);
formatNumber(50);
formatNumber(500);
formatNumber(5000);
formatNumber(50000);
formatNumber(500000);
formatNumber(5000000);
I'd recommend using a change event rather than a keyup event as change will only update the value when the input is no longer the focus. If you use keyup the code will try and reinterpret the new string you add back to the input as a number and throw an error.
Here's the code using toLocaleString (just press tab after adding the number as if to move to the next input box):
const values = document.querySelector('#values');
values.addEventListener('change', handleChange, false);
function handleChange(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
values.value = formatted;
}
<input id="values" type="text">
The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString(). For that reason I added the toNumber() function to be complete. In the example below I preform the following steps:
When user fills in a number in the input field and leaves the input field: Call toString(e) and make from the entered number a formatted string.
If the user again selects the input field, call toNumber(e) and format it back to a number.
This makes sure you won't get NaN when reselecting or will become completely unusable.
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
It is still possible to add text in it, this will result in NaN as text cannot be formatted to a number. This could be filtered out in the toString(e) when necessary. I did this in the example below by adding if (formatted !== 'NaN') {} Only when it's not NaN it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.
const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);
function toNumber(e) {
const value = e.target.value;
const unformatted = value.replace(/\D/g,'');
values.value = unformatted;
}
function toString(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
if (formatted !== 'NaN') {
values.value = formatted;
}
}
<input id="values" type="text">
To fix that, you can also remove my addition and add a filter before the toString(e) does it's thing and filter the dots, text etc. so only the numbers remain.

JavaScript validation not working in installshield

Requirement : To validate password and emailID entered by user.
I have designed a dialog for user to enter there email id and password for creating their new account.
I want the the user input to be validated on the "next" button of the dialog.
I have written a JavaScript for it as shown below and added a custom action in "do action" of my dialog button.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword = "") //if null
return false;
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
}
if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
}
return true;
}
But this JS is not getting executed successfully.
Can someone help me out with this or with some other suggestion?
Your if condition have a syntax mistake.
if(newPassword = "")
= is assigning operator. If you want to check the value you have to use conditional operator == like below.
if(newPassword == "")
Also you have to add all the condition on else part, then only it will check the validation one by one, otherwise at the end it will automatically return the true value. Change your script like below.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword == "" || newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
} else if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
} else {
return true;
}
}

Check If Input is empty JQuery

Hello, There are simple problem in my code, I've put myself as a user, let's assume that if the user click on the space button (in keyboard), So What is the solution.
Here my simple code:
var name = $('input#name').val(); // get the value of the input field
if(name == "" || name == " ") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Use the $.trim function to remove spaces
var name = $.trim( $('input#name').val() ); // get the value of the input field
if(name == "") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}
The .trim function in JavaScript removes leading and trailing spaces/new lines. So, if the user just spams space bar, the name.trim() will remove all leading/trailing spaces, resulting in "" and that equals "". Thus, your error code would show.
var name = $('input#name').val(); // get the value of the input field
if(name.trim() == "") {
$('#err-name').fadeIn('slow'); // show the error message
error = true; // change the error state to true
}

JQuery keypress function not working

I have the following code which checks if a roll number is valid in the database selected by the postname variable. It was working in an earlier version where I hadn't introduced the second variable postname. But at the moment, this code is not working. What's the error here?
$(document).ready(function() { //function to check rollno is valid
$('#roll').keyup(function(event) {
var rolll=$('#roll').val();
var postname=$('#post').val();
$.get('CheckRollValidity',{roll:rolll},{post:postname},function(responseText) {
$('#status1').text(responseText);
});
});
});
Servlet
roll = request.getParameter("roll");
temp = request.getParameter("post");
table1 = "dbo."+post;
table2 = "dbo.user_candidates";
try
{
if (roll.length() < 10 || roll.length() > 10) {
result = "Please enter your " + len + "-digits roll number.";
count1 = 1;
}
else if (!roll.matches("[0-9]*"))
{
result = "Please enter digits only";
count1 = 1;
}
if (count1 == 0)
{
//database work
result="OK";
}
else
{
result = "Error";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(result);
Also, can I do the same via ajax, alternatively? Here I don't want the code working on pressing a submit button. Rather the working is happening on keypress.
You can't send two objects, you'll have to use one object with two values otherwise the second object is seen as the argument which should have been the callback
$.get('CheckRollValidity',{roll:rolll, post:postname},function(responseText) {
$('#status1').text(responseText);
});

javascript: counting digits in a text input

I have a piece of HTML that creates a web form with three text fields (name, group and number), all of which are validated using JavaScript to check that there is data inputted into them. In the last text field, I need to introduce an additional bit of JavaScript to check that the data inputted by the user is also four digits long (for example 2947 or 94Q3). As a complete JavaScript novice, I'm not sure how I would do this! Would I have to create a variable that could take the value of the inputted data, then count the digits of the variable, or could I do it directly from the field? Here is the Javascript section of my code:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
If possible, could you tell me what code I would need to insert? Thank you!
Place this block in your conditions list:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
if (document.Entry.number.value==””) {
msg+=”You must enter the number \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
change this to
if (document.Entry.number.length != 4){
msg+="Number must be exactly 4 characters \n";
document.Entry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}

Categories