I am new to javascript and need help with implementing the following function: when the user enters a zipcode, any other entries of the form are erased and the zip code is used to look up an address.
How would I do that? The following is code I am using to get location for near by urgentcare areas:
(
function(){
var $scope, $location;
var urgentCareApp = angular.module('urgentCareApp',['ui.bootstrap']);
urgentCareApp.controller('UrgentCareController',function($scope,$http,$location,anchorSmoothScroll){
$scope.Lang = 'initVal';
$scope.ShowResults = false;
$scope.ShowDesc = true;
$scope.NoResults = false;
$scope.currentPage = 1;
$scope.maxPageNumbersToShow = 10;
$scope.formModel = {};
$scope.searchMode = 0;
$scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
$scope.searchParam = {};
$scope.searchParam.Distance = $scope.miles[0];
console.log($scope.searchParam.Distance);
//$scope.searchParam.Specialty = $scope.Specialties[0];
$scope.GetCurrentZip = function (){
try{
var lon, lat;
console.log('starting geoposition code.');
if("geolocation" in navigator){
window.navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude.toFixed(3);
lon = pos.coords.longitude.toFixed(3);
console.log(lat + ' ' + lon);
$http.get("/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
.success(function(response){
console.log('Response: ' + response);
$scope.searchParam.Zip = response;
console.log('object set');
})
})
}
else{ console.log('No geolocation'); }
}
catch(err) { console.log(err.message); }
}
$scope.GetCityList = function (){
try{
$http.get("/remote/ReturnUrgentCareCityList.cfm")
.success(function(response){
$scope.Cities = response.Cities;
})
}
catch(err){}
}
$scope.SearchUrgentCare = function(searchParam){
try{
$scope.searchMode = 1;
var queryString='';
if($scope.formModel && $scope.formModel !== searchParam){
$scope.resultsCount = 0;
currentPage = 1;
}
if(searchParam){
$scope.formModel = searchParam;
for(var param in searchParam){
console.log(param + ' ' + searchParam.hasOwnProperty(param) + ' ' + searchParam[param]);
if(searchParam.hasOwnProperty(param)){
var paramValue = searchParam[param].value ? searchParam[param].value.trim() : searchParam[param].trim();
if (paramValue.length > 0)
queryString += param + '=' + paramValue + '&';
}
}
}
console.log(queryString);
queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;
$http.get("/remote/ReturnUrgentCareList.cfm" + queryString)
.success(function(response){
$scope.urgentCareCenters = response.UrgentCareCenters;
$scope.resultsCount = response.rowCount;
if (!$scope.urgentCareCenters){
$scope.NoResults = true;
$scope.ShowResults = false;
$scope.ShowDesc = false;
}
else{
$scope.NoResults = false;
$scope.ShowResults = true;
$scope.ShowDesc = false;
}
})
}
catch(err){ alert('No response.: ' + err.message); }
}
$scope.$watchGroup(['currentPage'], function(){
try{
if($scope.searchMode == 1){
$scope.SearchUrgentCare($scope.formModel);
}
}
catch(err){}
});
$scope.GetCityList();
$scope.GetCurrentZip();
$scope.gotoElement = function (eID){
var browserWidth = screen.availWidth;
if (browserWidth < 768)
anchorSmoothScroll.scrollTo(eID);
};
});
urgentCareApp.service('anchorSmoothScroll', function(){
this.scrollTo = function(eID) {
// This scrolling function
// is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};
});
urgentCareApp.directive('allowPattern',[allowPatternDirective]);
function allowPatternDirective(){
return{
restrict: "A",
compile: function(tElement, tAttrs){
return function(scope, element, attrs){
element.bind("keypress", function(event){
var keyCode = event.which || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){
event.preventDefault();
return false;
}
});
}
}
}
}
urgentCareApp.filter('PhoneNumber', function(){
return function(phoneNumber){
var dash = '-';
if(phoneNumber){
var pn = phoneNumber;
pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
pn = [pn.slice(0, 3), dash, pn.slice(3)].join('');
return pn;
}
return phoneNumber;
}
});
})();
The Form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate="" role="form">
<div class="form-group"><input class="form-control" id="urgentcare" ng-model="searchParam.UrgentCareName" placeholder="Urgent Care Name" type="text" /></div>
<div class="form-group"><select class="form-control" id="city" ng-model="searchParam.City" ng-options="City.value for City in Cities"><option disabled="disabled" selected="selected" value="">City</option> </select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group"><select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
</div>
Not sure about what you're trying to do, but for sure you can use ngChange directive, so when the user types anything to Zip you can do what you want in your controller.
See this demo:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope, $http) {
$scope.reset = function() {
// If you just want to clear the fields do it:
var zip = angular.copy($scope.searchParam.Zip);
$scope.searchParam = {};
$scope.searchParam.Zip = zip;
}
});
})();
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate="" role="form">
<div class="form-group">
<input class="form-control" id="urgentcare" ng-model="searchParam.UrgentCareName" placeholder="Urgent Care Name" type="text" />
</div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City" ng-options="City.value for City in Cities">
<option disabled="disabled" selected="selected" value="">City</option>
</select>
</div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding">
<div class="form-group">
<input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" ng-change="reset()" type="text" />
</div>
</div>
</div>
<div class="form-group">
<input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" />
</div>
</form>
</div>
</div>
</body>
</html>
you should either use angular $scope.$watch or ng-change directive
for example if i want do to something when the variable $scope.varA changes
you can use:
$scope.$watch("varA", function(){
//my code
//in your case (type searchParams.Zip where i wrote varA)
var zip = $scope.searchParams.Zip; //keep before cleaning
$scope.searchParams = {};
$scope.searchParams.Zip = zip;
});
or declare a angular function and use ng-change directive on the html input where you used ng-model for the zip code, (add this as attribute: ng-change="clean_form();")
$scope.clean_form = function(){
var zip = $scope.searchParams.Zip;
$scope.searchParams = {};
$scope.searchParams.Zip = zip;
};
the form cleaning code comes from developer033, i just wanted to show you how you could cause that code to happen
Related
I have a small loan investment calculator. I added a keyup event to insert the comma into the 'investment' field, but now there is an error on submitting the form because the comma cannot be used in the calculation.
How can I edit my code so the calculation can still be processed?
I tried adding a deleteThousandSeparator function to escape the comma before it is submitted, but as you can see this does not work.
$(document).ready(function() {
$('.project-selector select').change(function() {
$.ajax({
url: '/project/get-pattern-list?id=' + $(this).val(),
type: 'get',
/*dataType: 'json',*/
success: function(response) {
$('.pattern-selector select').html(response);
if (response.trim() == "") $('.pattern-selector').hide();
else $('.pattern-selector').show();
reload_data();
}
});
});
$('.pattern-selector select').change(function() {
reload_data();
});
function reload_data() {
$.ajax({
url: '/project/get-pattern-info?projectid=' + $('.project-selector select').val() + "&id=" + $('.pattern-selector select').val(),
type: 'get',
dataType: 'json',
success: function(response) {
if (response.length > 0) {
$('.pattern-name').text(response[0].name);
$('.pattern-area').text(response[0].total_area);
$('.pattern-price').text(parseInt(response[0].price) );
} else {
$('.pattern-name').text("-");
$('.pattern-area').text("-");
$('.pattern-price').text("-");
}
}
});
}
function CheckForDigit(checkValue) {
var valid = true;
if (isNaN(checkValue))
valid = false;
if (checkValue == "")
valid = false;
return valid;
}
function FormatNumberToString(nStr) {
//nStr = nStr.toFixed(2);
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function CalculatePMT(pv, rate, years) {
return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1 + rate / 100 / 12) , ( years * 12))));
}
/************** CALCULATE 2 *************/
$("#cal2_btnCalculate").click(Calculate2);
function Calculate2(event) {
var years = $("#cal2_txtTenor").val();
var rate = $("#cal2_txtInterestRate").val();
var pv = $("#cal2_txtLoan").val();
if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
var ir = (rate / 100) * 100; // For LH, add 1 more
var installment = CalculatePMT(pv, ir, years);
$("#cal2_txtInstallment").val(FormatNumberToString(installment));
$("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
} else
alert("processing error");
}
/*****************************************/
});
var cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function deleteThousandSeparator(){
const cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}
</script>
<form onsubmit="return deleteThousandSeparator()">
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
</div>
<div>
<input id="cal2_txtLoan" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="text" placeholder="amount">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtTenor" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="1-30 years">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtInterestRate" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="percent (%)">
</div>
</div>
<div class="row mt20">
<div class="col-md-offset-3 col-md-6 col-sm-offset-0 col-sm-9 col-xs-offset-0 col-xs-9">
<div class="row">
<div class="col-xs-6">
<button type="button" id="cal2_btnCalculate" class="button investment-button">submit</button>
</div>
</div>
</div>
</div>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
<label class="investment-list">Summary of monthly installments</label> <input id="cal2_txtInstallment" class="wpcf7-form-control wpcf7-text form-control investment-class-form" disabled="disabled" type="text"> <span class="investment-list" style="color:red;">* Result is just a guide</span>
</div>
</div>
</form>
Just with replacing comma , globally with empty space, and convert string to a number with +
var pv = +$("#cal2_txtLoan").val().replace(/,/g, '');
$(document).ready(function() {
$('.project-selector select').change(function() {
$.ajax({
url: '/project/get-pattern-list?id=' + $(this).val(),
type: 'get',
/*dataType: 'json',*/
success: function(response) {
$('.pattern-selector select').html(response);
if (response.trim() == "") $('.pattern-selector').hide();
else $('.pattern-selector').show();
reload_data();
}
});
});
$('.pattern-selector select').change(function() {
reload_data();
});
function reload_data() {
$.ajax({
url: '/project/get-pattern-info?projectid=' + $('.project-selector select').val() + "&id=" + $('.pattern-selector select').val(),
type: 'get',
dataType: 'json',
success: function(response) {
if (response.length > 0) {
$('.pattern-name').text(response[0].name);
$('.pattern-area').text(response[0].total_area);
$('.pattern-price').text(parseInt(response[0].price) );
} else {
$('.pattern-name').text("-");
$('.pattern-area').text("-");
$('.pattern-price').text("-");
}
}
});
}
function CheckForDigit(checkValue) {
var valid = true;
if (isNaN(checkValue))
valid = false;
if (checkValue == "")
valid = false;
return valid;
}
function FormatNumberToString(nStr) {
//nStr = nStr.toFixed(2);
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function CalculatePMT(pv, rate, years) {
return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1 + rate / 100 / 12) , ( years * 12))));
}
/************** CALCULATE 2 *************/
$("#cal2_btnCalculate").click(Calculate2);
function Calculate2(event) {
var years = $("#cal2_txtTenor").val()
console.log(years)
var rate = $("#cal2_txtInterestRate").val();
var pv = +$("#cal2_txtLoan").val().replace(/,/g, '');
console.log(pv)
if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
var ir = (rate / 100) * 100; // For LH, add 1 more
var installment = CalculatePMT(pv, ir, years);
$("#cal2_txtInstallment").val(FormatNumberToString(installment));
$("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
} else
alert("processing error");
}
/*****************************************/
});
var cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function deleteThousandSeparator(){
const cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}
</script>
<form onsubmit="return deleteThousandSeparator()">
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
</div>
<div>
<input id="cal2_txtLoan" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="text" placeholder="amount">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtTenor" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="1-30 years">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtInterestRate" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="percent (%)">
</div>
</div>
<div class="row mt20">
<div class="col-md-offset-3 col-md-6 col-sm-offset-0 col-sm-9 col-xs-offset-0 col-xs-9">
<div class="row">
<div class="col-xs-6">
<button type="button" id="cal2_btnCalculate" class="button investment-button">submit</button>
</div>
</div>
</div>
</div>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
<label class="investment-list">Summary of monthly installments</label> <input id="cal2_txtInstallment" class="wpcf7-form-control wpcf7-text form-control investment-class-form" disabled="disabled" type="text"> <span class="investment-list" style="color:red;">* Result is just a guide</span>
</div>
</div>
</form>
You could format the submitted values first before using them to do your calculation
var years = _formatNumber( $( "#cal2_txtTenor" ).val() );
var rate = _formatNumber( $( "#cal2_txtInterestRate" ).val() );
var pv = _formatNumber( $( "#cal2_txtLoan" ).val() );
// your calculation logic here
function _formatNumber( str ){
return str.replace( ',', '' );
}
The working solution below
$(document).ready(function() {
$('.project-selector select').change(function() {
$.ajax({
url: '/project/get-pattern-list?id=' + $(this).val(),
type: 'get',
/*dataType: 'json',*/
success: function(response) {
$('.pattern-selector select').html(response);
if (response.trim() == "") $('.pattern-selector').hide();
else $('.pattern-selector').show();
reload_data();
}
});
});
$('.pattern-selector select').change(function() {
reload_data();
});
function reload_data() {
$.ajax({
url: '/project/get-pattern-info?projectid=' + $('.project-selector select').val() + "&id=" + $('.pattern-selector select').val(),
type: 'get',
dataType: 'json',
success: function(response) {
if (response.length > 0) {
$('.pattern-name').text(response[0].name);
$('.pattern-area').text(response[0].total_area);
$('.pattern-price').text(parseInt(response[0].price) );
} else {
$('.pattern-name').text("-");
$('.pattern-area').text("-");
$('.pattern-price').text("-");
}
}
});
}
function CheckForDigit(checkValue) {
var valid = true;
if (isNaN(checkValue))
valid = false;
if (checkValue == "")
valid = false;
return valid;
}
function FormatNumberToString(nStr) {
//nStr = nStr.toFixed(2);
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function CalculatePMT(pv, rate, years) {
return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1 + rate / 100 / 12) , ( years * 12))));
}
/************** CALCULATE 2 *************/
$("#cal2_btnCalculate").click(Calculate2);
function Calculate2(event) {
var years = _formatNumber( $( "#cal2_txtTenor" ).val() );
var rate = _formatNumber( $( "#cal2_txtInterestRate" ).val() );
var pv = _formatNumber( $( "#cal2_txtLoan" ).val() );
if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
var ir = (rate / 100) * 100; // For LH, add 1 more
var installment = CalculatePMT(pv, ir, years);
$("#cal2_txtInstallment").val(FormatNumberToString(installment));
$("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
} else
alert("processing error");
}
function _formatNumber( str ){
return str.replace( ',', '' );
}
/*****************************************/
});
var cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function deleteThousandSeparator(){
const cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}
</script>
<form onsubmit="return deleteThousandSeparator()">
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
</div>
<div>
<input id="cal2_txtLoan" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="text" placeholder="amount">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtTenor" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="1-30 years">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtInterestRate" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="percent (%)">
</div>
</div>
<div class="row mt20">
<div class="col-md-offset-3 col-md-6 col-sm-offset-0 col-sm-9 col-xs-offset-0 col-xs-9">
<div class="row">
<div class="col-xs-6">
<button type="button" id="cal2_btnCalculate" class="button investment-button">submit</button>
</div>
</div>
</div>
</div>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
<label class="investment-list">Summary of monthly installments</label> <input id="cal2_txtInstallment" class="wpcf7-form-control wpcf7-text form-control investment-class-form" disabled="disabled" type="text"> <span class="investment-list" style="color:red;">* Result is just a guide</span>
</div>
</div>
</form>
You can use replacAll.
replaceAll(",", "")
Basically, you replace the "," with nothing "".
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
I'm trying to build a currency converter. I'm using javascript and I have a good foundation but I want to know how to make the converter update in real-time without having to click a button.
How do I make it so that my converter converts from a base currency of M without needing be be within a select element & how do I make the converter update as the user types the number in, rather than having to click a button?
I've tried removing all of the available options for the .currency-1 class and only leaving M, but that still leaves a drop down menu. I want to convert from M to X (USD, GBP, CAD, EUR, etc.)
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
Any help would be appreciated!
I need the user to be able to input X amount (in currency M, no dropdown), select their native currency & have the page calculate the rate as soon as they type in the number.
Add another eventListner which is keyup so that whenever user types in the required field, it will call the convertCurrency function as below:
amountInput.addEventListener('keyup', convertCurrency);
Edit:
To remove the selection box for M, remove the select element and replace by either <p> or <span> tag. After this, you would have to get the this value by using innerText as var from = baseCurrencyInput.innerText; in the currency converter function.
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
}
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.innerText;
var to = secondCurrencyInput.value;
var result = 0;
try {
if (from == to) {
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch (err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
amountInput.addEventListener('keyup', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<p id="currency-1">M</p>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
$('#amount').keyup(function(event){
convertCurrency(event);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
Currently, you can use the user's final script. This script can modify some previously available variables.
I created a small example in pure javascript I would like to do the same in angular 2+ https://jsfiddle.net/hxs3d0hu/2/
Thank you in advance for your attention
HTML Code
<div class="container">
<form>
<div class="form-group">
<label for="descricao">Nome</label>
<input type="text" id="descricao" name="descricao" class="form-control" />
</div>
<div class="form-group">
<label for="valor">Valor</label>
<input type="text" id="valor" name="valor" value="10" class="form-control" />
</div>
<div class="form-group">
<label for="quantidade">Quantidade</label>
<input type="text" id="quantidade" name="quantidade" value="20" class="form-control" />
</div>
<div class="form-group">
<label for="total">Total</label>
<input type="text" id="total" name="total" class="form-control" />
</div>
<div class="form-group">
<label for="codex">Code</label>
<textarea id="codex" name="codex" rows="10" cols="100" class="form-control">
if (qtde < 15) {
vlr = 10;
}
else
{
vlr = 9;
}
tot = vlr * qtde;
</textarea>
</div>
<button type="button" id="calcular" name="calcular" onclick="calcularx();" class="btn btn-primary">Calcular</button>
</form>
</div>
JavaScript Code
var vlr = 0;
var qtde = 0;
var tot = 0;
function calcularx(){
var valor = document.getElementById("valor");
var quantidade = document.getElementById("quantidade");
var total = document.getElementById("total");
vlr = valor.value;
qtde = quantidade.value;
tot = 0;
tot = qtde * vlr;
total.value = tot;
var codex = document.getElementById("codex").value;
var cst = document.getElementById("customcodescript");
var corpo = "function custom(){ {0} }".replace("{0}", codex);
//cst.innerHTML = corpo;
load_js(cst, corpo);
custom();
valor.value = vlr;
quantidade.value = qtde;
total.value = tot;
console.log(tot);
}
function load_js(cst, corpo)
{
if(cst != null){
cst.remove();
}
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.id = "customcodescript";
script.type= 'text/javascript';
script.innerHTML = corpo;
//script.src= 'source_file.js';
head.appendChild(script);
}
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
Here's a plnkr that would achieve what you're looking for.
http://embed.plnkr.co/w2FVfKlWP72pzXIsfsCU/
You create a function with eval, then call it using the component context. All the function and variable in your component will be available to your textbox code :
The template
Value:
<label>Code:</label>
<textarea [(ngModel)]="code"></textarea> <br>
<button (click)="executeCode(code)">Do it.</button>
The component :
export class HelloWorld {
value = 100;
code = 'this.value = this.value * 100';
executeCode(code){
let fn = eval("(function(){ {0} })".replace("{0}", code));
fn.call(this);
}
}
However, keep in mind that eval is usually evil and that this use case is quite weird. I'm not sure if your user should control the code. Anyhow, that's up to you.
Also, if you want to avoid the "this." in the code text box, you can always use replace on your variable name to add it behind the scene.
jQuery previous button not working as expected.
Basically the best way to explain it is if I'm on question 5 and I click the previous button, it defaults to question 1 rather than going to question 4.
So it's defaulting to question 1... That's a problem.
What to do?
jQuery is in the bottom in script tags.
if (i.Question_Type == "DROPDOWN")
{
<div class="container text-center">
<div class="row idrow" data-questions="#counter">
#{
counter++;
}
<div id="question1" class="form-group">
<label class="lab text-center" for="form-group-select">
#i.Question_Order #Html.Raw(#i.Question)
</label>
<select class="form-control" id="form-group-select">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<option> #i.qOps.options[t]</option>
}
else
{
<option> #x</option>
}
}
</select>
</div>
</div>
</div>
}
if (i.Question_Type == "RADIO")
{
<div class="container">
<div class="row idrow" data-questions="#counter">
#{counter++;
}
<div class="form-group">
<label class="lab" for="questions">
#i.Question_Order #i.Question
</label>
<div class="row">
<div class="col-xs-12">
<div id="question1" class="radio-inline">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<label class="radio-inline"><input type="radio" name="question"> #i.qOps.options[t]</label>
}
else
{
<label class="radio-inline"><input type="radio" min="0" max="#x" name="question"></label>
}
}
</div>
</div>
</div>
</div>
</div>
</div>
}
if (i.Question_Type == "CHECKBOX")
{
for (int y = 1; y <= Convert.ToInt32(i.Question_SubType); y++)
{
#*<div class="container">
<div class="row">
<label>#y</label> <input type="checkbox" name="question">
</div>
</div>*#
}
}
}
<div class="azibsButtons">
<button type="button" id="previous" class="btn btn-primary pull-left">Prev</button>
<button type="button" id="next" class="btn btn-primary pull-right">Next</button>
</div>
<script>
$(document).ready(function () {
$(".idrow").each(function (i) {
var inner = $(this).data('questions');
if (inner == 0) {
$(this).removeClass('hidden');
} else {
$(this).addClass('hidden');
}
});
$("#next").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal++;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
$("#previous").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal--;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
});
});
</script>
Hey guys I got the solution Thanks to Daniel.
The next event closing braces were wrapped around the previous event, which caused the problem to default to question 1 when clicked previous.
$("#next").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal++;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
$("#previous").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal--;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
Only the first element (the first button) will get the remove event from the class "remove-row"
My HTML:
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
My JavaScript/jQuery:
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$(this).parent().remove();
});
});
I hope it's not duplicated because I tried this and some other questions, but without success.
$(document).ready(function () {
$('.remove-row').each(function(index) {
$(this).on('click', function () {
$(this).parent().remove();
});
});
});
Would do it, see this Plunk. Note that you have to click exactly on the (line of the) X to make it work.
$(function () {
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$(this).parent().remove();
});
});
$('.draggable-button').mousedown(function (e) {
if (e.which === 1) {
var button = $(this);
var button_id = button.attr('id');
var parent_height = button.parent().innerHeight();
var top = parseInt(button.css('top'));
var original_ypos = button.position().top; //original ypos
var drag_min_ypos = 0 - original_ypos;
var drag_max_ypos = parent_height - original_ypos - button.outerHeight();
var drag_start_ypos = e.clientY;
var my_ypos = original_ypos;
//Set current order for all
$('.draggable-button').each(function (i) {
$(this).attr('data-order', (i + 1));
});
var prev_button = button.prev('.draggable-button');
var next_button = button.next('.draggable-button');
var prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
var next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
$(window).on('mousemove', function (e) {
//Move and constrain
button.addClass('drag');
var direction = my_ypos > button.position().top ? 'up' : 'down';
var new_top = top + (e.clientY - drag_start_ypos);
my_ypos = button.position().top;
button.css({top: new_top + 'px'});
if (new_top < drag_min_ypos) {
button.css({top: drag_min_ypos + 'px'});
}
if (new_top > drag_max_ypos) {
button.css({top: drag_max_ypos + 'px'});
}
//Check position over others
if (direction == 'down' && next_button_ypos != '') {
if (my_ypos > next_button_ypos) { //crossed next button
next_button.css({top: (parseInt(next_button.css('top')) - next_button.outerHeight(true)) + 'px'}); //up once
var tmp_order = next_button.attr('data-order');
next_button.attr('data-order', button.attr('data-order')); //switch order
button.attr('data-order', tmp_order);
prev_button = next_button;
next_button = next_button.nextAll('.draggable-button:not(.drag)').first();
prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
}
} else if (direction == 'up' && prev_button_ypos != '') {
if (my_ypos < prev_button_ypos) { //crossed prev button
prev_button.css({top: (parseInt(prev_button.css('top')) + prev_button.outerHeight(true)) + 'px'}); //down once
var tmp_order = prev_button.attr('data-order');
prev_button.attr('data-order', button.attr('data-order')); //switch order
button.attr('data-order', tmp_order);
next_button = prev_button;
prev_button = prev_button.prevAll('.draggable-button:not(.drag)').first();
prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
}
}
});
$(window).on('mouseup', function (e) {
if (e.which === 1) {
$('.draggable-button').removeClass('drag');
$(window).off('mouseup mousemove');
//Reorder and reposition all
$('.draggable-button').each(function () {
var this_order = parseInt($(this).attr('data-order'));
var prev_order = $(this).siblings('.draggable-button[data-order="' + (this_order - 1) + '"]');
if (prev_order.length > 0) {
$(this).insertAfter(prev_order);
}
});
$('.draggable-button').css('top', '0');
$('.draggable-button').removeAttr('data-order'); //reset
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
The problem wasn't in the code I posted. I forgot to mention that I made the buttons draggable. For that, I use a plugin, which prevented the click in some way.
Now debugging and trying to fix it, thanks for the help!
Please use it like this:
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$('.remove-row').parent().remove();
});
});