How to auto format my textbox in license format? - javascript

I tried searching on the internet for answer but the closest I can find is in this jfiddle
What I wanted to do is when the page loads, the textbox is automatically filled with this words Furniture/Chair/Square. In addition, the user can input some text next to the words like this Furniture/Chair/Square/_ _ _/_ _ _. The user cannot erase the automatically filled words.

This is a work around with some reference from jwa's post and RegEx:
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>
How do I include numbers?
Use [^a-z0-9] in this line this.value.replace(/[^a-z]/gi, '')
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z0-9]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>

You can do this by assigning a label to the input field you create. For example...
#text-input {
border: none;
outline: none;
}
label{
border:solid 1px black;
padding-right: 2px;
}
<label for="text-input">
furniture chair square
<input type="text" id="text-input" />
</label>

Use RegExp to solve your problem.
You may add some css or addition text to notice the user error input.
function checkStr(str){
//check pattern
result = str.match(/^Furniture\/Chair\/Square([a-zA-Z\/]+)?/)
if(result == null || result[0].length !== str.length){
//revert the input field to default
document.getElementById('userText').value = "Furniture/Chair/Square"
}
}
<input type="text" value="Furniture/Chair/Square" id="userText" oninput="checkStr(value)"></input>
<p id='asd'></p>

Related

I was trying to make a to-do list using javascript but unable to append the selected option

Aim was to take input and create radio buttons and label dynamically like a list which when checked goes to bottom while label name coming from the input textfield that we write. I was able to do this with the radio button but not with the label. Please help me out I'm new here.
[Fiddle] (http://jsfiddle.net/wju6t7k3/2/)
<div id = "container" >
<div class="row">
<div class="col-12">
<input id = "txt" type = "text" placeholder="Add new.." >
<button id="btn" value = "add" type = "button" onClick = "add()" >
</button>
</div>
<div id="done" class="col-12">
</div>
</div> <!-- row -->
<script>
//js
var j = 0;
var textval="";
function getInputValue(){
// Selecting the input element and get its value
inputVal = document.getElementById("txt").value;
// Displaying the value
alert(inputVal);
}
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval =this.value;
onfocus=this.value='';
}
});
function countChecked(event) {
alert(textval);
alert("balle");
getInputValue();
$(this).parent().parent().append(this).append('<label>textvalh</label>').append('<br>');
}
$("#container").on( "click", "input[type=checkbox]", countChecked );
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
</script>
You have to make a container or a parent element for the checkbox and its label to have more control of it.
and if you want to separate the checkbox that is checked, then make another div element to make a separation.
Here's an example, this is based on your code:
//js
var j = 0;
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<div><input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label></div>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval = this.value;
this.value='';
}
});
function countChecked(event) {
const isChecked = event.currentTarget.checked;
// Get parent of checkbox which is the closest <div> element
const checkbox_parent = $(event.currentTarget).closest('div');
if (isChecked) // Move element to div with ID = selected
checkbox_parent.appendTo('#selected')
else // Move element to div with ID = done
checkbox_parent.appendTo('#done')
}
$('#container').on('change', 'input[type="checkbox"]', countChecked)
input, input:active{
border:none;
cursor: pointer;
outline: none;
}
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: blue;
}
::-moz-placeholder { /* Firefox 19+ */
color: blue;
}
:-ms-input-placeholder { /* IE 10+ */
color: blue;
}
:-moz-placeholder { /* Firefox 18- */
color: blue;
}
button{
display:none;
}
.checkbox-round {
width: 1.3em;
height: 1.3em;
background-color: white;
border-radius: 50%;
vertical-align: middle;
border: 1px solid #ddd;
-webkit-appearance: none;
outline: none;
cursor: pointer;
}
.checkbox-round:checked {
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" >
<div class="row">
<div class="col-12" style="border: dashed red 3px;">
<input id = "txt" type="text" placeholder="Add new.." />
<button id="btn" value="add" type="button" onClick ="add()">Add</button>
<div id="done" class="col-12" style="border: solid purple 3px;">
</div>
<div id="selected" class="col-12" style="border: solid gray 3px;">
</div>
</div>
</div> <!-- row -->
</div>
Happy Coding!

For MM/DD/YYYY text, display only that text which is not entered by user

I have a page like below image
According to my requirement, user is allowed to enter digits from the keypad that is provided on the page only. So input field is readonly.
Now I am trying to get is, when user start entering month then other text should remain in text field until user types that. e.g. 05/DD/YYYY like this. And accordingly that text will be hide.
If I placed placeholder then when user starts entering digits all text gone. I don't want that. So I have taken "MM/DD/YYYY" text in seperate span tag.
var Memory = "0", // initialise memory variable
Current = "", // and value of Display ("current" value)
Operation = 0, // Records code for eg * / etc.
MAXLENGTH = 8; // maximum number of digits before decimal!
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
function AddDigit(dig) { //ADD A DIGIT TO DISPLAY (keep as 'Current')
if (Current.indexOf("!") == -1) { //if not already an error
if ((eval(Current) == undefined) &&
(Current.indexOf(".") == -1)) {
Current = dig;
document.calc.display.focus();
} else {
Current = Current + dig;
document.calc.display.focus();
}
Current = Current.toLowerCase(); //FORCE LOWER CASE
} else {
Current = "Hint! Press 'Clear'"; //Help out, if error present.
}
if (Current.length > 0) {
Current = Current.replace(/\D/g, "");
Current = format(Current, [2, 2, 4], "/");
}
document.calc.display.value = Current.substring(0, 10);
document.getElementById("cursor").style.visibility = "hidden";
}
function Clear() { //CLEAR ENTRY
Current = "";
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 5000);
}
function backspace() {
Current = document.calc.display.value;
var num = Current;
Current = num.slice(0,num.length - 1);
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "hidden";
}
function cursorAnimation() {
$("#cursor").animate({
opacity: 0
}, "fast", "swing").animate({
opacity: 1
}, "fast", "swing");
}
//--------------------------------------------------------------->
$(document).ready(function() {
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 1000);
});
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
.txtplaceholder {
font-family: "Droid Sans Mono";
color: #D7D7D7;
position: relative;
float: left;
left: 219px;
top: 17px;
z-index: 10 !important;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: inline-block;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form Name="calc" method="post">
<div style="position:relative">
<span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span>
<span style="z-index:100">
<input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" readonly>
</span>
<button class="cancel-icon" type="reset" onClick="Clear()"></button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="backspace()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
With the above Html code I am getting below result:
Problems coming are below:
My digits are going below the text "MM/DD/YYYY". I am not getting how should I get my digits above that text
How should I hide the text which is entered by user and display other accordingly e.g. "MM" should hide if user enters 05 and display other text like this "05/DD/YYYY".
Can anyone please help me in this?
NOTE: With input type=date or by any other plugins I can achieve above functionality but my requirement is different. I have to achieve this with HTML, CSS, JS only.
I would use a ready built data picker for this kind of thing as it would have all the error checking in built to ensure you enter a date in the correct format.
The way you are doing it, you are not able to check if the day is valid until you have entered the month, by which time the user will have to backspace and it will be a very slow and clunky process which is not very user friendly.
Anyway, if you persist with a number pad, here is how I would do it.
put the date in a global array
have a global index counter
add and remove values based on the index counter
The following is a very quick example of the above
var dateBits = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
letters = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
input = document.getElementById('pt_dob'),
currentIndex = 0;
function makeDate() {
return dateBits[0] + dateBits[1] + "/" + dateBits[2] + dateBits[3] + "/" + dateBits[4] + dateBits[5] + dateBits[6] + dateBits[7];
}
function AddDigit(number) {
dateBits[currentIndex] = number;
if (currentIndex < 8) {
currentIndex++;
}
input.value = makeDate();
}
function RemoveDigit() {
if (currentIndex > 0) {
currentIndex--;
}
dateBits[currentIndex] = letters[currentIndex];
input.value = makeDate();
}
function Clear() {
for (i = 0; i < letters.length; i++) {
dateBits[i] = letters[i];
}
currentIndex = 0;
input.value = makeDate();
}
input.value = makeDate(); // run this line onload or include this whole script at the bottom of the page to get your input to start with your text
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
.num_keys > span {
display: inline-flex;
width: 2em;
height: 2em;
align-items: center;
justify-content: center;
cursor: pointer;
border: 1px solid black;
}
<form Name="calc" method="post">
<div style="position:relative"><span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span><span style="z-index:100"><input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" autocomplete="off" readonly></span>
<button class="cancel-icon" type="reset" onClick="Clear(); return false;">clear</button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="RemoveDigit()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
var text = "DD/MM/YYYY";
$(".textbox").on("focus blur", function(){
$(".wrapper").toggleClass("focused");
});
$(".wrapper").click(function (e) {
if (e.target == this) {
var b = $(".textbox", this).focus();
}
}).trigger("click");
$(".wrapper > .textbox").on("input", function(){
var ipt = $(this).text().replace(/\u00A0/g, " ");
$(".gray").text(text.substr(ipt.length, text.length));
}).trigger("input");
check this fiddle http://jsfiddle.net/7sD2r/22/
If ive understood all well. I think the one solution is to store user input in hidden field. Then get this input to split digits and return to visible input value that consists of splitted values etc.

How to add data locally and add value by its id?

<!DOCTYPE HTML>
<html>
<head>
<title>HTML5 localStorage (name/value item pairs) demo</title>
<style >
td, th {
font-family: monospace;
padding: 4px;
background-color: #ccc;
}
#hoge {
border: 1px dotted blue;
padding: 6px;
background-color: #ccc;
margin-right: 50%;
}
#items_table {
border: 1px dotted blue;
padding: 6px;
margin-top: 12px;
margin-right: 50%;
}
#items_table h2 {
font-size: 18px;
margin-top: 0px;
font-family: sans-serif;
}
label {
vertical-align: top;
}
</style>
</head>
<body onload="doShowAll()">
<h1>HTML5 localStorage (name/value item pairs) demo</h1>
<form name=editor>
<div id="hoge">
<p>
<label>Value: <textarea name=data cols=41 rows=10></textarea></label>
</p>
<p>
<label>Name: <input name=name></label>
<input type=button value="getItem()" onclick="doGetItem()">
<input type=button value="setItem()" onclick="doSetItem()">
<input type=button value="removeItem()" onclick="doRemoveItem()">
</p>
</div>
<div id="items_table">
<h2>Items</h2>
<table id=pairs></table>
<p>
<label><input type=button value="clear()" onclick="doClear()"> <i>* clear() removes all items</i></label>
</p>
</div>
<script>
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
function doGetItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.getItem(name);
doShowAll();
}
function doRemoveItem() {
var name = document.forms.editor.name.value;
document.forms.editor.data.value = localStorage.removeItem(name);
doShowAll();
}
function doClear() {
localStorage.clear();
doShowAll();
}
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var i=0;
for (i=0; i<=localStorage.length-1; i++) {
key = localStorage.key(i);
pairs += "<tr><td>"+key+"</td>\n<td>"+localStorage.getItem(key)+"</td></tr>\n";
}
if (pairs == "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
</script>
</form>
</body>
</html>
Hi friends,
I wants to locally save the data,now I am able to save the data locally by the code.even if I give the same name the value is getting added and saved locally.but the name should be shown in order of high value to low(example: Ram 20,Renu 18,green 2 like wise...).so how to do this?
function doSetItem() {
var name = document.forms.editor.name.value;
var data = document.forms.editor.data.value;
var origData = localStorage.getItem(name) || 0;
localStorage.setItem(name, parseInt(origData) + parseInt(data));
doShowAll();
}
To display them in descending order:
function doShowAll() {
var key = "";
var pairs = "<tr><th>Name</th><th>Value</th></tr>\n";
var userArray = [];
for (var i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
userArray.push({name:key, value:parseInt(localStorage.getItem(key))});
}
userArray.sort(function(a, b){
return b.value - a.value;
});
userArray.forEach(function(user){
pairs += "<tr><td>" + user.name + "</td>\n<td>" + user.value + "</td></tr>\n";
});
if (pairs === "<tr><th>Name</th><th>Value</th></tr>\n") {
pairs += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('pairs').innerHTML = pairs;
}
For what I can see in your code, you're just replacing the value, you need to get the existent value from the localStorage first, append to it the new one and then asign the result to the localStorage.

Validating function written in javaScript runs only once?

goal : is to validate this form. http://jsbin.com/buwejurexa/1/
Code is below
Show the user all errors at once when he clicks Save Product button and errors at each step also.
What is done:
Wrote a validating function returnVal() which is nested inside another function called displayStorage.
What works :
As the page loads the user clicks the Save Product button and the validating function seems to be working first time. I can see the alert.
The issue starts when:
The user selects the Category and Products and sees Wattage. This
time he decides to click on Save Product. Nothing happens. No
Validations are displayed step by step.
No errors in Console but got a error in JS Bin that (Line 253: Expected a conditional expression and instead saw an assignment.
Line 258: Unreachable 'return' after 'return'.)
My guess :
a) my if and else statement is missing something. I tried calling it from different functions but no luck.
b) The four buttons use Jquery. so I am guessing do I need to call javascript function returnVal() inside Jquery. How do I do that. I did reference the 4 buttons in my validating function.
can some help me get the validations right.
Thanks!!
var wattage = {
'Artic King AEB': 100,
'Artic King ATMA': 200,
'Avanti Compact': 300,
'Bosch SS': 400,
'Bosch - SHXUC': 100,
'Asko DS': 200,
'Blomberg': 300,
'Amana': 400
};
var annualEnergy = 0;
var dailyEnergyConsumed = 0;
function populateProducts(category, products) {
var refrigerators = new Array('Artic King AEB', 'Artic King ATMA', 'Avanti Compact', 'Bosch SS');
var dishWasher = new Array('Bosch - SHXUC', 'Asko DS', 'Blomberg', 'Amana');
switch (category.value) {
case 'refrigerators':
products.options.length = 0;
for (i = 0; i < refrigerators.length; i++) {
createOption(products, refrigerators[i], refrigerators[i]);
}
break;
case 'dishWasher':
products.options.length = 0;
for (i = 0; i < dishWasher.length; i++) {
createOption(products, dishWasher[i], dishWasher[i]);
}
break;
default:
products.options.length = 0;
break;
}
populateWattage(products);
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
function populateWattage(product) {
document.getElementById('wattage').innerText = wattage[product.value];
populateStorage();
}
function setConsumption(hrs) {
setConsumption();
}
dailyEnergyConsumption = function(hrs) {
dailyEnergyConsumed = 0;
dailyEnergyConsumed = parseFloat(hrs * parseInt(document.getElementById('wattage').innerText) / 1000).toFixed(2);
document.getElementById('dailyEnergyConsumptionVal').innerText = dailyEnergyConsumed + " kWh";
populateStorage();
};
annualEnergyConsumption = function(days) {
annualEnergy = 0;
var allYear = document.getElementById('allYear');
var halfYear = document.getElementById('halfYear');
var threeMonths = document.getElementById('threeMonths');
var oneMonth = document.getElementById('oneMonth');
if (allYear || days != 365) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 182 && !halfYear) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 90 && !threeMonths) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 30 && !oneMonth) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
}
populateStorage();
};
// code that shows which button is clicked. Green div below the 4 buttons
$(document).ready(function() {
$("#h1").click(function() {
$("#onesSelected").show();
$("#threeSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h3").click(function() {
$("#threeSelected").show();
$("#onesSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h6").click(function() {
$("#sixSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h24").click(function() {
$("#twentyFourSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#sixSelected").hide();
});
});
function compareSetup() {
var prodName = localStorage.getItem('productKey');
var energyName = parseInt(localStorage.getItem('energyKey'), 10);
var useName = parseInt(localStorage.getItem('estimatedUse'), 10);
return false;
}
function populateStorage() {
var productBox = document.getElementById("products");
var productName = productBox.options[productBox.selectedIndex].text;
localStorage.setItem('productKey', productName);
localStorage.setItem('energyKey', document.getElementById("annualEnergyConsumption").innerHTML);
//localStorage.setItem.querySelector('input[id="usageRadio"]:checked').value;
//localStorage.setItem('usageRadio' + $(this).attr('id'), JSON.stringify({ checked: this.checked }));
//localStorage.setItem('estimatedUse', document.getElementById("usageRadio"));
// do other things if necessary
}
function displayStorage() {
var displayProduct = document.getElementById("displayName");
var displayAnnual = document.getElementById("displayAnnual");
displayProduct.innerHTML = "Selected Product: " + localStorage.getItem('productKey');
displayProduct.style = "display:inline;";
displayAnnual.innerHTML = "Annual Consumption: " + localStorage.getItem('energyKey');
returnVal();
}
//validation code starts here
function returnVal() {
//initialize the form elements starting from form name , category and product dropdown, daily use buttons and finally the radio buttons
var energyForm = document.getElementsByName("energyForm")[0];
// drop downs
var catDropdown = document.getElementById("dd1");
var prodDropdown = document.getElementById("products");
// call the 4 Daily use button
var notLotButton = document.getElementById("h1");
var averageButton = document.getElementById("h3");
var lotButton = document.getElementById("h6");
var alwaysButton = document.getElementById("h24");
// radio button group
var allYearRadio = document.getElementById("allYear");
var halfYearRadio = document.getElementById("halfYear");
var threeMonthsRadio = document.getElementById("threeMonths");
var oneMonthRadio = document.getElementById("oneMonth");
//
var missingFields = false;
var strFields = "";
if (catDropdown.selectedIndex === 0) {
missingFields = true;
strFields += "Select Category and the related Product \n";
catDropdown.focus();
} else {
return true;
}
if ((!notLotButton.clicked) &&
(!averageButton.clicked) &&
(!lotButton.clicked) &&
(!alwaysButton.clicked)) {
missingFields = true;
strFields += "Select atleast one Estimated Daily Use option \n";
} else {
return true;
}
if ((!allYearRadio.checked) &&
(!halfYearRadio.checked) &&
(!threeMonthsRadio.checked) &&
(!oneMonthRadio.checked)) {
missingFields = true;
strFields += "Select atleast one Estimated Yearly Use option \n";
} else {
return true;
}
if (missingFields = true) {
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true;
}
function resetForm() {
document.getElementById("resetButton");
document.getElementById("energyForm").reset();
document.getElementById('products').value = "select";
//document.getElementById('select_value').selectedIndex = 3;
}
#leftColumn {
width: 600px;
float: left;
}
.placeholderText {
font: bold 12px/30px Georgia, serif;
}
body {
padding-left: 45px;
}
#annualEnergyConsumption {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#dailyEnergyConsumptionVal {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#annualCostOperation {
font: bold 40px arial, sans-serif;
color: #00ff00;
}
.dailyButInline {
display: inline;
}
#wattage {
position: absolute;
left: 160px;
top: 130px;
font: bold 25px arial, sans-serif;
color: #00ff00;
}
/* mouse over link */
button:hover {
background-color: #b6b6b6;
}
#onesSelected {
position: absolute;
left: 53px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#threeSelected {
position: absolute;
left: 156px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#sixSelected {
position: absolute;
left: 259px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#twentyFourSelected {
position: absolute;
left: 362px;
top: 246px;
background-color: #00ff00;
display: none;
width: 113px;
height: 5px;
}
#store {
cursor: pointer;
}
<h2>Annual Energy Consumption and Cost Calculator</h2>
<form id="energyForm" onSubmit="return compareSetup()" action="" method="post">
<div id="leftColumn">
<div>
<span class="placeholderText">Choose Category</span>
<span>
<select id="dd1" name="dd1" onchange="populateProducts(this,document.getElementById('products'))" required>
<option value="select">Select-a-Category</option>
<option value="refrigerators">Refrigerators</option>
<option value="dishWasher">DishWasher</option>
</select>
</span>
</br>
<span class="placeholderText">Select a Product</span>
<span>
<select id="products" onchange="populateWattage(this)" required>
<option value="select" selected>--------------------------</option>
</select>
</span>
</div>
<div>
<span class="placeholderText">Wattage</span>
<span id="wattage">0</span>
</br>
</br>
</div>
<div id="buttonBoundary">
<div class="placeholderText">Estimated Daily Use</div>
<div class="dailyButInline">
<button type="button" id="h1" onclick="dailyEnergyConsumption(1)">Not a Lot</br>1 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h3" onclick="dailyEnergyConsumption(3)">Average</br>3 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h6" onclick="dailyEnergyConsumption(6)">A Lot</br>6 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h24" onclick="dailyEnergyConsumption(24)">Always On</br>24 hours per day</button>
</div>
<div id="onesSelected"></div>
<div id="threeSelected"></div>
<div id="sixSelected"></div>
<div id="twentyFourSelected"></div>
</br>
</br>
</div>
<div>
<span class="placeholderText">Daily Energy Consumption</span>
</br>
<div id="dailyEnergyConsumptionVal">---</div>
</br>
</div>
<div>
<span class="placeholderText">Estimated Yearly Use</span>
</br>
<input type="radio" name="usageRadio" value="365" id="allYear" onclick="annualEnergyConsumption(365)" />
<label for="allYear">All year</label>
<input type="radio" name="usageRadio" value="182" id="halfYear" onclick="annualEnergyConsumption(182)" />
<label for="halfYear">6 Months</label>
<input type="radio" name="usageRadio" value="90" id="threeMonths" onclick="annualEnergyConsumption(90)" />
<label for="threeMonths">3 Months</label>
<input type="radio" name="usageRadio" value="30" id="oneMonth" onclick="annualEnergyConsumption(30)" />
<label for="oneMonth">1 Month</label>
<!-- <div id="daysUsed"><input type="number" id="hour" maxlength="2" min="1" onchange="annualEnergyConsumption(this.value)"></br> -->
</div>
</br>
<div>
<span class="placeholderText">Energy Consumption</span>
</br>
<div id="annualEnergyConsumption">---</div>
</br>
</div>
<input type="submit" value="Save Product" onclick="displayStorage()" />
<input type="reset" onclick="resetForm()" id="resetButton" value="Reset" />
</div>
<div id="right">
<div id="displayName">Selected Product:</div>
<div id="displayAnnual">Annual Consumption:</div>
</div>
</form>
In the last statements of your function, there are two mistakes:
if (missingFields = true) { // should be: missingFields == true
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true; // You already returned false; did you mean to return false inside the if?

Calling function from anonymous function in JQuery returns undefined

I'm working with this script which needs to call the external function, but the value returned in the log shows 'undefined'.
I have a checkbox that calls the external function successfully, but the anonymous jQuery function is not successful. Could this be a scope issue of some sort?
Thanks for any help.
css:
div.row {
border: 1px solid blue;
width: 100px;
}
div.child {
border: 1px solid red;
display: inline-block;
}
javascript:
function padZeros(ksa) {
getDigits(ksa);
//alert(s);
//document.getElementById("ksa_padded").value=s
}
function getDigits(MyDigits) {
var ksa = MyDigits;
var re4Digit = /^([0-9])([0-9]?)([k|s|a])([0-9])([0-9]?)([A-z]?)$/;
var first2Digits = ksa.replace(re4Digit, "$1$2");
//alert(first2Digits);
//return first2Digits;
pad(first2Digits, '2');
}
function pad(num, size) {
//var s = num+"";
//alert(num);
s = num + "";
//alert(s);
while (s.length < size) s = "0" + s;
return s;
//alert(s);
}
$("#add").click(function () {
var inserted = false;
var newText = $("#addText").val();
var $newItem = $("<div class='child'>" + newText + "</div>");
$(".row:first .child").each(function () {
//alert($(this).text());
xx = $(this).text();
var compare_a = padZeros(xx);
//alert(compare_a);
console.log(xx);
if ($(this).text() > newText) {
$newItem.insertBefore($(this));
inserted = true;
return false;
}
});
if (inserted == false) {
$newItem.appendTo(".row:first");
}
});
html
<div class="row">
<div class="child">3K1</div>
<div class="child">3K3</div>
<div class="child">3K4</div>
<div class="child">1K1</div>
<div class="child">1K2</div>
</div>
<div class="row">
<div class="child">IS2</div>
<div class="child">IS4</div>
</div>
<div class="row">
<div class="child">IA2</div>
<div class="child">IA4</div>
</div>
<br/>
<input id="addText" type="text" />
<input id="add" type="button" value="Insert Element" />
<br>
<input type="checkbox" onClick="padZeros('1k10s')">
<input type="text" id="ksa_padded">
Try
return getDigits(ksa);
return pad(first2Digits,'2');
You have to return things, otherwise they'll come out as undefined.

Categories

Resources