Trouble with clearing other text boxes when value is backspaced - javascript

I am a beginner at Javascript, this is my first Javascript that isn't just 'cut/paste/hack'. I created an calculator that updates the output as input is typed, I can get all my 'answerboxes' to clear when the input box is blurred then focused, but if I backspace the value out of the input box the 'answerboxes' still show the 'answers' based on the last char. value that was backspaced.
In my 'validiateTheInput' funct. I can declare an 'if = "3"' to clear them and it works when a '3' is the value (which would not work in the end :) ), but I can't seem to catch it if the field appears blank do to user backspacing the value from the box.
Am I obsessing over something stupid, or am I just missing something?
Heres the whole thing (with some basic HTML ommitted):
There is also a bit of overkill in the validation function because I was experimenting with trying to catch the 'blank input' do to backspacing.
//jQuery keyup to grab input
$(document).ready(function() {
$('#totalFeet').keyup(function() {
validiateTheInput();
});
});
//clear calculated values
function clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField) {
answerbox.value = "";
answerbox1.value = "";
answerbox2.value = "";
totalFeetField.value = "";
};
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = document.getElementById('totalFeet');
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
// feel like I should be able to catch it here with the length prop.
if (totalFeetField.value.length == 0) {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// if input is usable, do the good stuff...
if (totalFeetField.value != "" && !isNaN(totalFeetField.value)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField.value)) {
alert("The Total Sq. Footage Value must be a number!")
document.getElementById('totalFeet').value = "";
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField.value == '3') {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField.value == 'undefined' || totalFeetField.value === null || totalFeetField.value === '') clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 5.95; // set multiplier
document.getElementById('answerbox').value = answer.toFixed(2);
}
// calc the second box
function calcSecondBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 18.95; // set multiplier
document.getElementById('answerbox1').value = answer.toFixed(2);
}
// calc the third box
function calcThirdBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 25.95; // set multiplier
document.getElementById('answerbox2').value = answer.toFixed(2);
}
HTML:
<div id="calculator">
<form name="calculate">
<label for="total">Total Value to Calculate:</label> &nbsp&nbsp&nbsp&nbsp
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes(totalFeet, answerbox, answerbox1, answerbox2);"><br /><br />
<label for="answerbox">Total Value X $5.95:&nbsp&nbsp&nbsp&nbsp$</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"><br /><br />
<label for="answerbox1">Total Value X $18.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"><br /><br />
<label for="answerbox2">Total Value X $25.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15">
</form>
</div>

The problem is that you're not storing the element objects in variables - you're storing their values:
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
...so later, when you call the following function, passing these variables as an argument:
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
...you're not passing the elements. You can fix it by removing .value off each line in your variable assignments.
Working demo: http://jsfiddle.net/AndyE/Mq6uN/
Side note and shameless plug: if you want something a little more robust than keyup for detecting input, check out this blog post.

You are passing the value of answerbox, answerbox1 etc to the clearBoxes function, not the elements themselves.

Here's a full jQuery approach:
//jQuery keyup to grab input
$(document).ready(function () {
$('input[id$=totalFeet]').keyup(function () {
validiateTheInput();
});
function clearBoxes() {
$('input[id$=answerbox]').val("");
$('input[id$=answerbox1]').val("");
$('input[id$=answerbox2]').val("");
}
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answerbox = $('input[id$=answerbox]').val();
var answerbox1 = $('input[id$=answerbox1]').val();
var answerbox2 = $('input[id$=answerbox2]').val();
// feel like I should be able to catch it here with the length prop.
if (totalFeetField == "") {
clearBoxes();
}
// if input is usable, do the good stuff...
if (totalFeetField != "" && !isNaN(totalFeetField)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField)) {
alert("The Total Sq. Footage Value must be a number!")
$('input[id$=totalFeet]').val("");
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField == '3') {
clearBoxes();
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField == 'undefined' || totalFeetField === null || totalFeetField === '')
clearBoxes();
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 5.95; // set multiplier
$('input[id$=answerbox]').val(answer.toFixed(2));
}
// calc the second box
function calcSecondBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 18.95; // set multiplier
$('input[id$=answerbox1]').val(answer.toFixed(2));
}
// calc the third box
function calcThirdBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 25.95; // set multiplier
$('input[id$=answerbox2]').val(answer.toFixed(2));
}
});
Also, here's the HTML
<form name="calculate" action="">
<label for="total">Total Value to Calculate:</label> &nbsp&nbsp&nbsp&nbsp
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes();"/><br /><br />
<label for="answerbox">Total Value X $5.95:&nbsp&nbsp&nbsp&nbsp$</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"/><br /><br />
<label for="answerbox1">Total Value X $18.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"/><br /><br />
<label for="answerbox2">Total Value X $25.95:&nbsp&nbsp&nbsp$</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15"/>
</form>
Sometimes mixing jQuery and plain javascript doesn't work too well. This code should work in clearing your textboxes when the first textbox is empty. It also works on number validation.

Related

How to add more than 2 conditions in an If/Else statement in Javascript?

Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).

Coding beginner needing assistance

I'm brand new to coding. I've created a form with three fields- two with "number" types and one with radio button selection. I'm trying to utilize "try catch throw" to validate these fields and have error messages echoed onto the screen (not as an alert). I know that there is a lot of code in here, but I am really lost with this. Here is my HTML and js:
HTML:
<form>
<fieldset>
<label for="hshld" class="formhdr">Total number of people in your household:</label>
<input type="number" id="hshld" name="hshld" min="1">
</fieldset>
<fieldset>
<label for="hrrisk" class="formhdr">Number of high-risk people in your household:</label>
<input type="number" id="hrrisk" name="hrrisk" min="0">
</fieldset>
<fieldset>
<legend class="formhdr">Number of weeks in isolation:</legend>
<input type="radio" id="countone" name="headcount">
<label for="countone" class="numweeks">1</label>
<input type="radio" id="counttwo" name="headcount">
<label for="counttwo" class="numweeks">2</label>
<input type="radio" id="countthree" name="headcount">
<label for="countthree" class="numweeks">3</label>
<input type="radio" id="countfour" name="headcount">
<label for="countfour" class="numweeks">4+</label>
</fieldset>
<input type="submit" value="Submit" id="submit">
</form>
and my .js:
//Global variables
var hshld = document.getElementById("hshld");
var mysubmit = document.getElementById("submit");
var radioError = document.getElementById("radioError");
var weekCount;
//this function checks to see if the user entered a number into the field
function validatehshld() {
try {
if (hshld.value == "") {
throw "Enter a number!";
}
hshld.style.outline = "none";
// clear input box
}
catch (hshldError) {
hshld.style.outline = "2.5px dashed red";
hshld.placeholder = hshldError;
return false;
}
}
// makes sure that the radio button is selected. If not, throws an error message into the "radioError" paragraph at under the form.
function validatewkCount() {
try {
if (weekCount == 0) {
throw document.getElementById('radioError').innerHTML = "Select a number!";
}
// clear input box
hshld.style.outline = "none";
}
catch (weekCountError) {
radioError.style.outline = "2.5px dashed red";
radioError.placeholder = radioError;
return false;
}
}
// stop the form from submitting if a field needs attention
function endEvent() {
return event.preventDefault();
}
function validateSubmit() {
if(validatehshld() === false && validatewkCount() === false) {
endEvent();
}
}
// EventListeners, includes IE8 compatibility
if (hshld.addEventListener) {
hshld.addEventListener("focusout", validatehshld, false);
} else if (hshld.attachEvent) {
hshld.attachEvent("onclick", validatehshld);
}
// runs validateSubmit() function when the user clicks the submit button
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", validateSubmit, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", validateSubmit);
}
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", numBottles, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", numBottles);
}
// this function gets called via the onclick attribute (line 44)
function numBottles() {
// takes the current value of the input field from id "hshld"
var people = document.getElementById("hshld").value;
var hrrisk = document.getElementById("hrrisk").value;
// this variable represents the number of gallons a single person should have for one week of isolation- 1 gallon per day
var weekWater = 7;
// this variable will hold the number of weeks selected from the radio buttons
var weekCount;
// this code determines which radio button is selected and assigns a value to the variable depending on which radio button is selected
if (document.getElementById('countone').checked) {
var weekCount = 1;
} else if (document.getElementById('counttwo').checked) {
var weekCount = 2;
} else if (document.getElementById('countthree').checked) {
var weekCount = 3;
} else if (document.getElementById('countfour').checked) {
var weekCount = 4;
} else if (isNaN(weekCount) === true) {
var weekCount = 0;
}
// echo out the calculation (people X weekWater) to the span object with id=bottles
document.getElementById("bottles").innerHTML = (people * weekWater * weekCount) + (hrrisk * weekCount);
}
Try not to use try, catch, or throw here, instead create your error message in a new element and place it in the html somewhere you think it looks nice.
I would just use:
if (typeof hshld.value !== 'number') { // if a wrong data type was entered
document.getElementById("error-zone").innerHTML += "<div>Enter a number!</div"
} else {
// continue calculating answer
}
for the quick and dirty method.

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Pasting multiple numbers over multiple input fields

I've got a form on my site using 6 input fields. The site visitor simply enters a 6 digit code into these 6 boxes. The thing is that they'll get the 6 digit code and it would be ideal to allow them to simply copy the 6 digit code we send them into these input fields by simply putting pasting into the first input field and having the remaining 5 digits go into the remaining 5 input fields. It would just make it much easier than having to manually enter each digit into each input field.
Here's the code we're currently using, but it can easily be changed to accomplish what is described above:
<input type="text" maxlength="1" class="def-txt-input" name="chars[1]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[2]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[3]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[4]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[5]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[6]">
I saw a posting similar to this here: Pasting of serialnumber over multiple textfields
But it doesn't have the solution I'm looking for. Ideally this could be pulled off using jQuery or plain JavaScript.
Edit
I didn't like the timer solution I used in the paste event and the complexity of just using the input or paste event.
After looking at this for a while I added a solution which uses a hybrid between the 2.
The code seems to do all that is required now.
The Script:
var $inputs = $(".def-txt-input");
var intRegex = /^\d+$/;
// Prevents user from manually entering non-digits.
$inputs.on("input.fromManual", function(){
if(!intRegex.test($(this).val())){
$(this).val("");
}
});
// Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
$inputs.on("paste", function() {
var $this = $(this);
var originalValue = $this.val();
$this.val("");
$this.one("input.fromPaste", function(){
$currentInputBox = $(this);
var pastedValue = $currentInputBox.val();
if (pastedValue.length == 6 && intRegex.test(pastedValue)) {
pasteValues(pastedValue);
}
else {
$this.val(originalValue);
}
$inputs.attr("maxlength", 1);
});
$inputs.attr("maxlength", 6);
});
// Parses the individual digits into the individual boxes.
function pasteValues(element) {
var values = element.split("");
$(values).each(function(index) {
var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
$inputBox.val(values[index])
});
};​
See DEMO
Here is an example of a jquery plugin that does the same thing as the original answer only generalized.
I went to great lengths to modify the original answer ( http://jsfiddle.net/D7jVR/ ) to a jquery plugin and the source code is here: https://github.com/relipse/jquery-pastehopacross/blob/master/jquery.pastehopacross.js
An example of this on jsfiddle is here:
http://jsfiddle.net/D7jVR/111/
The source as of 4-Apr-2013 is below:
/**
* PasteHopAcross jquery plugin
* Paste across multiple inputs plugin,
* inspired by http://jsfiddle.net/D7jVR/
*/
(function ($) {
jQuery.fn.pastehopacross = function(opts){
if (!opts){ opts = {} }
if (!opts.regexRemove){
opts.regexRemove = false;
}
if (!opts.inputs){
opts.inputs = [];
}
if (opts.inputs.length == 0){
//return
return $(this);
}
if (!opts.first_maxlength){
opts.first_maxlength = $(this).attr('maxlength');
if (!opts.first_maxlength){
return $(this);
}
}
$(this).on('paste', function(){
//remove maxlength attribute
$(this).removeAttr('maxlength');
$(this).one("input.fromPaste", function(){
var $firstBox = $(this);
var pastedValue = $(this).val();
if (opts.regexRemove){
pastedValue = pastedValue.replace(opts.regexRemove, "");
}
var str_pv = pastedValue;
$(opts.inputs).each(function(){
var pv = str_pv.split('');
var maxlength;
if ($firstBox.get(0) == this){
maxlength = opts.first_maxlength;
}else{
maxlength = $(this).attr('maxlength');
}
if (maxlength == undefined){
//paste them all!
maxlength = pv.length;
}
//clear the value
$(this).val('');
var nwval = '';
for (var i = 0; i < maxlength; ++i){
if (typeof(pv[i]) != 'undefined'){
nwval += pv[i];
}
}
$(this).val(nwval);
//remove everything from earlier
str_pv = str_pv.substring(maxlength);
});
//restore maxlength attribute
$(this).attr('maxlength', opts.first_maxlength);
});
});
return $(this);
}
})(jQuery);
This shouldn't be too difficult ... add a handler for the paste event on the first input, and then process per the requirement.
Edit
Actually this is much trickier than I thought, because it seems there's no way to get what text was pasted. You might have to kind of hack this functionality in, using something like this (semi-working)... (see the JSFiddle).
$(document).on("input", "input[name^=chars]", function(e) {
// get the text entered
var text = $(this).val();
// if 6 characters were entered, place one in each of the input textboxes
if (text.length == 6) {
for (i=1 ; i<=text.length ; i++) {
$("input[name^=chars]").eq(i-1).val(text[i-1]);
}
}
// otherwise, make sure a maximum of 1 character can be entered
else if (text.length > 1) {
$(this).val(text[0]);
}
});
HTML
<input id="input-1" maxlength="1" type="number" />
<input id="input-2" maxlength="1" type="number" />
<input id="input-3" maxlength="1" type="number" />
<input id="input-4" maxlength="1" type="number" />
jQuery
$("input").bind("paste", function(e){
var pastedData = e.originalEvent.clipboardData.getData('text');
var num_array = [];
num_array = pastedData.toString(10).replace(/\D/g, '0').split('').map(Number); // creates array of numbers
for(var a = 0; a < 4; a++) { // Since I have 4 input boxes to fill in
var pos = a+1;
event.preventDefault();
$('#input-'+pos).val(num_array[a]);
}
});
You're going to have to right some custom code. You may have to remove the maxlength property and use javascript to enforce the limit of one number per input.
As dbasemane suggests, you can listen for a paste event. You can listen to keyup events too to allow the user to type out numbers without having to switch to the next input.
Here is one possible solution:
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.def-txt-input[name="chars['+ (index + 1) +']"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup paste', handleCharacter)
.on('keydown', handleBackspace);
I have this code set up on jsfiddle, so you can take a look at how it runs: http://jsfiddle.net/hallettj/Kcyna/

Categories

Resources