complex if statement runs code regardless of condition output - javascript

JS
if (isNaN(BDyear) == true || isNaN(BDmonth) == true ||
isNaN(BDday) == true || BDday.length != 2 ||
BDmonth.length != 2 || BDyear.length != 4)
{
document.getElementById("BDyear").value = ''
document.getElementById("BDmonth").value = ''
document.getElementById("BDday").value = ''
document.getElementById("bderror").style.display = "inline"
BDstate = false BDcheck = false
}
HTML
<tr>
<td>שנת לידה</td>
<td>
<input class="text" id="BDyear" maxlength="4" style="width:8%" />&nbsp/&nbsp
<input class="text" id="BDmonth" maxlength="2" style="width:5%" />&nbsp/&nbsp
<input class="text" id="BDday" maxlength="2" style="width:5%" />
<br />
<p id="bderror" style="position:absolute; top:70%; color:red; font:65% arial; display:none">תאריך לידה לא תקין</p>
<p id="bderroryoung" style="position:absolute; top:70%; color:red; font:65% arial; display:none">חובה להיות מעל גיל 13</p>
</td>
</tr>
the script part runs regardless whether i put in the inputs a number or words, with any length and i don't understand why is it running, but i'm suspecting it's the "isNaN" function that is not working correctly from different tries and setups. it's supposed to find out if the content entered is only a numric value that is in the proper length for dd/mm/yyyy and if it's all false it's supposed to leave everything as is and BDcheck var to be true so the next if statement will run
Any suggestions?

Make sure BDyear, BDday and BDmonth actually contain values; you may need to use document.getElementById("BDyear").value inside the isNaN functions. The value is also probably a string, so you may want to try first casting it to a number before checking isNaN like this: isNaN(Number(document.getElementById("BDyear").value)).
Also, isNaN returns a Boolean, so comparing it to true is redundant. You can just write it like if (isNaN(BDyear) || isNaN(BDmonth) || isNaN(BDday) || BDday.length != 2 || BDmonth.length != 2 || BDyear.length != 4), possibly with the changes I just suggested.
Ultimately, the code could look like this:
//assuming BDstate and BDcheck variables are already defined
var year = document.getElementById("BDyear");
var month = document.getElementById("BDmonth");
var day = document.getElementById("BDday");
if (isNaN(Number(year.value)) || isNaN(Number(month.value) || isNaN(Number(day.value)) || day.value.length != 2 || month.value.length != 2 || year.value.length != 4)
{
year.value = ''
month.value = ''
day.value = ''
document.getElementById("bderror").style.display = "inline"
BDstate = false
BDcheck = false
}
Also, instead of checking that the string length of month is 2 characters, you may want to check whether the numeric value is between a valid range. For example, a user would currently have to enter "06" (without an leading or trailing spaces, btw) in order for the check to succeed, whereas they could enter " 6 " if you were actually checking that the numeric value is within a valid range like (Number(month.value) >= 1 && Number(month.value) <= 12). The same goes for the day and year.

Related

why I can not use && in javascript for not blank and not space

I want to check the value is not blank or one empty space so I wrote a code
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>
You can update your condition as below.
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() == "") {
alert("empty");
}
If you want to get alert if OccLocation is not empty then :
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() != "") {
alert("not empty");
}
Your condition is wrong.
You have to use == instead of !=.
If you use && then both condition should be true to return true, which is ultimately impossible at the same time in this case. Use || instead, this will be evaluated as true if any of the condition is true.
The condition should be:
if (OccLocation.value ==" " || OccLocation.value == "")
Even you can simplify the condition by using String.prototype.trim()
:
The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
Try
if (OccLocation.value.trim() == "")
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim()== ""){
alert ("empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass" />
You are checking that it is not empty, then alerting that it is empty. I think you mean to check that it is empty. Change your JS to the following:
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value === " " || OccLocation.value === "")
{
alert ("empty");
}
Your code runs immediately, and the value="" sets it to empty.
Here, I set the value in the markup so it has some, thus it alerts.
var OccLocation = document.getElementById("HdnOccLocation");
console.log(OccLocation.value)
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="dd" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>

Input box validation when there is no input

I am trying to make a simple calculator. You enter one number, you enter the second one, press PLUS and get alert with an answer. I need to show alert('no data') if you click on PLUS when input fields are not touched.
function num1() {
nm = document.getElementById('nsum1').value;
}
function num2() {
mn = document.getElementById('nsum2').value;
}
function plus() {
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
} else {
alert(sum);
}
}
<input onchange="num1()" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input onchange="num2()" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
So far I have tried if(sum == undefined)/if(sum == null)/if(sum == false)/if(isNaN(sum))/if(sum == "") and nothing seems to work.
If you haven't touched the input field and get the value, then the result would be ""
You need a condition like
if (nm == "" || mn == "") {
alert('no data');
}
And also you should do operation after validations. You are doing operation and then validating.
Fixed other issues aswell.
function plus() {
mn = document.getElementById('nsum2').value;
nm = document.getElementById('nsum1').value;
if (nm == "" || mn == "") {
alert('no data');
} else {
sum = +nm + +mn;
alert(sum);
}
}
<input id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
You can do it much easier
function plus(num1, num2) {
alert(isNaN(num1) || isNaN(num2) ? 'No data' : num1 + num2);
}
function getNumber(id) {
return parseFloat(document.getElementById(id).value);
}
<input id="nsum1" type="number" placeholder="number" maxlength="6" />
<span onclick="plus(getNumber('nsum1'), getNumber('nsum2'))" id="sum">PLUS</span>
<input id="nsum2" type="number" placeholder="number" maxlength="6" />
I've made some changes to your code to make it more robust. See the inline comments for a description.
Declare variables
It is important to declare your variables, when you don't all the variables you are using will wind up in the global scope. When you Google this you will find many articles like this one: https://gist.github.com/hallettj/64478.
Prevent polluting the global scope. In a small website this may not be much of an issue but when working on larger project or with third party code, this is a must. The link above also explains this to some extend.
Use a button If you want something to be interactive, use an HTML element that was meant for it. The button element should be used, it has all sorts of accessibility features the span doesn't have. For instance, by default it will receive focus when navigating your website with the tab key.
Use descriptive variable names nm and mn may mean something to you now but in 6 months it will be a complete mystery. It also makes the code more readable and thus easier to maintain.
Attach event listeners in JS In general it is a bad idea to assign event listeners through the HTML attribute onXXX="". It is more error prone and a lot more time intensive when you want to change something.
// Wrap your code in a closure to prevent poluting the global scope.
(function() {
// Always declare your variables. These variables are no longer scoped to the window object but are no scoped to the function we're in.
var
valueA = null,
valueB = null;
/**
* To check if your input is a valid number requires a couple of checks.
* It is best to place these into their own method so you're other
* method is more readable.
*/
function isNumber(value) {
if (
// == null checks for undefined and null
value == null ||
value === '' ||
isNaN(value)
) {
return false;
}
return true;
}
function onChangeHandler(event) {
var
// Get the element that dispatched the event.
target = event.target;
// Check if the target has the class we've assigned to the inputs, of not you can ignore the event.
if (!target.classList.contains('js-input')) {
return;
}
// Based on the ID of the target, assign the value to one of the variables for the values.
switch(target.id) {
case 'nsum1':
valueA = parseFloat(target.value);
break;
case 'nsum2':
valueB = parseFloat(target.value);
break;
}
}
function onSumTriggerClicked(event) {
// Check if there are numbers to work with
if (
!isNumber(valueA) ||
!isNumber(valueB)
) {
// If not alert the user
alert('no data');
return;
}
sum = valueA + valueB;
alert(sum);
}
function init() {
var
// Get the calculator element.
calculator = document.getElementById('calculator'),
// Get the button to sum up the value.
sumButton = document.getElementById('sum-trigger');
// Add an event listener for the change event.
calculator.addEventListener('change', onChangeHandler);
// Add an event listener for the click event.
sumButton.addEventListener('click', onSumTriggerClicked);
}
// Call the init method.
init();
})();
<div id="calculator">
<input class="js-input" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<button type="button" id="sum-trigger" id="sum">PLUS</button>
<input class="js-input" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
</div>
Try to track it via Inspector, maybe log the values of nm and mn before anything else and correct your condition accordingly(as the sample).
function plus() {
console.log(nm);
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
}
It will most likely just be blank. So in this case you can modify your condition into:
if (nm === '' || mn === '') {...}
Hope it will help
Please use this as reference.
I've fixed your code.
if ( num1 === '' && num2 === '' ) {
alert('no data');
} else {
alert( parseInt(num1) + parseInt(num2) );
}

Getting function to run as user types

I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>

Javascript Keyboard Event change marked text

I have an input field which looks like this:
<input type="text" name="definemonth" value="'.$monthStart.'" class="form-control"
onkeypress="return isNumberKey(event, this.value);" />
To allow only numbers between 1 and 28 (each included) I wrote this piece of JS code:
var input = event.key;
var newValue = value + input;
if(input == "ArrowLeft" || input == "ArrowRight" || input == "ArrowUp" ||
input == "ArrowDown" || input == "Backspace" || input == "Delete" || input == "Enter")
{
return true;
}
if (!input.match("^[0-9]$") || newValue > 28 || newValue < 1)
{
return false;
}
return true;
It works mostly as I want it to. I want to be able to use the Arrow Keys, the backspace and delete button which works all just fine. But the issue is that I can not mark the text and then add a new number. With marking I mean this kind of marking:
The marking works fine but any key stroke does not change anything at all.
I tried to detect with
console.log(input);
what happens there but I do not get any output in the console at all.
My question is then how do I have to change my code to be able to enter a new value when the text is marked and I type 1 for example.
You should clear selected text before checking new value for allowability.
Like this:
var clearValue = element.value;
clearValue = clearValue.slice(0, element.selectionStart) + clearValue.slice(element.selectionEnd);
var newValue = clearValue + input;
jsfiddle

adding text to a only numeric text field for usability?

OK so i have this task that im not sure how to achieve. I have a text field that is only allowing the users to enter numeric values....I am validating on keypress to make sure that only numeric numbers are allowed
That works well
My problem is that the client wants text after the numbers to say " Miles" so if the user enters 100 they see "100 Miles"
I guess for usability. Does anyone know a good technique or jquery plugin to do this
In addition to a javascript solution, you may also want to look into the HTML 5 pattern attribute for <input>. For example, in modern browsers you could do something like:
<input name="miles" pattern="^\d+\s?[Mm]iles$" required>
Which requires no javascript at all :) Here's the relevant spec.
How about this:
$('input').keypress(function(e) {
if (e.which < 48 || e.which > 57) {
// not a number
return false;
}
// gets current entered numer
var number = this.value.split(' ')[0];
// adds new number
number = '' + number + String.fromCharCode(e.which);
this.value = number + ' miles';
return false;
})
It would be easier and I think clearer to do this in some sort of tag just outside of the textbox. Have a span directly below or something then update it on your keypress.
$('#textBox').keydown(function(){
// Validation code
$('#someSpan').html($(this).val() + " Miles");
});
How about this http://jsfiddle.net/TmxSN/1/
$(function(){
var timerOutId;
$('#inp').keypress(function(e) {
var key = e.which;
clearTimeout(timerOutId);
try{
if(this.value){
this.value = $.trim(this.value.match(/\d+/g)[0]);
}
}catch(e){}
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
}).keyup(function(e) {
var textBox = this;
if(this.value){
timerOutId = setTimeout(function(){
textBox.value = $.trim(textBox.value.match(/\d+/g)[0]) + " Miles";
}, 2000);
}
})
});
My problem is that the client wants text after the numbers to say "
Miles" so if the user enters 100 they see "100 Miles"
Then you can handle it in the onfocus and onblur event of your input type="text" like this.
Try this
<input type="text" min="0" max="1000" step="1" id="distance" placeholder="Enter the value in miles"/>
And Script
$(document).ready(function() {
//$("#distance").keypress(PassNumbersOnly);
$("#distance").focus(OnFocus);
$("#distance").blur(OnBlur);
});
function OnFocus() {
var $this = $(this);
if ($this.val().indexOf("Miles") != -1) {
$this.val($this.val().split(" ")[0]);
}
}
function OnBlur() {
var $this = $(this);
if ($.trim($this.val()) != "") {
$this.val($this.val() + " Miles");
}
}
Demo here: http://jsfiddle.net/naveen/EQEMr/
Tell your client that anyone with enough intelligence to use the web can understand:
<label for="distance">Distance in miles:
<input type="text" name="distance" id="distance"></label>
and that doing anything else is:
confusing for users
problematic as javascript may or may not be enabled/available
of zero practical use for the business as the value must be validated on the server anyway
the value requires additional processing at the server to remove the appended characters

Categories