Parsing Strings and Integers in JavaScript - javascript

I am new to JavaScript and HTML and am hoping someone can notice what I am doing wrong (I'm sure it is probably something small that I am just missing). I have been looking at this for a while, and I cannot seem to figure it out.
The problem is that branch #2 (identified in the comment within the code) is returning NaN for the houseVal which is supposed to return either sf for single-family or tw for townhouse/condo.
I have a JavaScript form I am making. Here it is:
function getPrice() {
var form = document.getElementById("calc");
var out = form.elements["z"];
//get numbers
var sqftVal = parseInt(form.elements["sqft"].value);
var bathsVal = parseInt(form.elements["baths"].value);
var builtVal = parseInt(form.elements["built"].value);
var lotVal = parseInt(form.elements["lot"].value);
for (i = 0; i < document.forms[0].zipcode.length; i++) {
if (document.forms[0].zipcode[i].checked) {
var zipVal = parseInt(document.forms[0].zipcode[i].value);
}
}
for (i = 0; i < document.forms[0].gar.length; i++) {
if (document.forms[0].gar[i].checked) {
var garageVal = parseInt(document.forms[0].gar[i].value);
}
}
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = parseInt(document.forms[0].housetype[i].value);
}
}
if (zipVal == "47") {
if (garageVal == "2") {
if (houseVal == "sf") {
out.value = 1;
}
else { //townhouse
out.value = houseVal; // <------ PROBLEM: returns NaN <------------
}
}
else { //garage == 3
if (houseVal == "sf") {
out.value = 3;
}
else { //townhouse
out.value = 4;
}
}
}
else { //zip == 20148
if (garageVal == "2") {
if (houseVal == "sf") {
out.value = 5;
}
else { //townhouse
out.value = 6;
}
}
else { //garage == 3
if (houseVal == "sf") {
out.value = 7;
}
else { //townhouse
out.value = 8;
}
}
}
}
</script>
and here is the Home Type (e.g., Single Family or Townhouse/Condo) part of the form.
...
<fieldset>
<legend>House Type</legend>
<div>
<input type="radio" id="sf" name="housetype" value="sf" />
<label for="sf">Single Family</label>
</div>
<div>
<input type="radio" id="tw" name="housetype" value="tw" />
<label for="tw">Townhouse/Condo</label>
</div>
</fieldset>
...

It looks like in your javascript code you are trying to convert the houseVal to an integer though it's only ever "sf" or "tw"
If you change the following block:
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = parseInt(document.forms[0].housetype[i].value);
}
}
To:
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = document.forms[0].housetype[i].value;
}
}
You should be good

Your value attributes for each radio button are letter based strings. You cannot feasibly use parseInt on letter-based strings .
var houseVal = parseInt(document.forms[0].housetype[i].value);
This is going to cause you issues.

Related

Type range not working in IE11 while using jQuery

I have 3 similar type range sliders on my page that work in browsers such as Chrome, Opera and Firefox. But when I try and use the slider in IE11 and below or Edge it doesn't want to slide.
HTML:
<div class="filterItem">
<section id="preperation" class="range-slider">
<p class="sliderText">Preperation Time (minutes)</p>
<span class="rangeValues"></span>
<inputclass="minSlider" value="0" min="0" max="61" step="1" type="range"
onchange="filter()">
<inputclass="maxSlider" value="61" min="0" max="61" step="1" type="range"
onchange="filter()">
</section>
</div>
jQuery:
function getVals() {
// Get slider values
console.log("values")
var parent = this.parentNode;
var slides = parent.getElementsByTagName("input");
var slide1 = parseFloat(slides[0].value);
var slide2 = parseFloat(slides[1].value);
// Neither slider will clip the other, so make sure we determine which is larger
if (slide1 > slide2) {
var tmp = slide2;
slide2 = slide1;
slide1 = tmp;
}
var slider = parent.getElementsByClassName('sliderText')[0].innerHTML;
var displayElement = parent.getElementsByClassName("rangeValues")[0];
var max = 0
if (slider == 'Preperation Time (minutes)') {
max = 60;
} else if (slider == 'Cooking Time (minutes)') {
max = 90;
} else {
max = 99999999
}
if (slide2 > max) {
slide2 = String(max) + '+';
}
displayElement.innerHTML = slide1 + " - " + slide2;
}
This is some more jQuery that loads the sliders in onload.
window.onload = function() {
// Set the sliders for the current values in the URL
if (location.search) {
var urlParams = new URLSearchParams(window.location.search);
var entries = urlParams.entries();
for (pair of entries) {
if (pair[0] == 'q') {
document.querySelector('input#searchBarMain').value = pair[1]
document.querySelector('input#filterSearch').value = pair[1]
}
if (pair[0] == 'min_cook_time') {
document.querySelector('#cooking>input.minSlider').value = pair[1]
}
if (pair[0] == 'max_cook_time') {
document.querySelector('#cooking>input.maxSlider').value = pair[1]
}
if (pair[0] == 'min_prep_time') {
document.querySelector('#preperation>input.minSlider').value = pair[1]
}
if (pair[0] == 'max_prep_time') {
document.querySelector('#preperation>input.maxSlider').value = pair[1]
}
if (pair[0] == 'min_servings') {
document.querySelector('#servings>input.minSlider').value = pair[1]
}
if (pair[0] == 'max_servings') {
document.querySelector('#servings>input.maxSlider').value = pair[1]
}
}
}
// Initialize Sliders
var sliderSections = document.getElementsByClassName("range-slider");
for (var x = 0; x < sliderSections.length; x++) {
var sliders = sliderSections[x].getElementsByTagName("input");
for (var y = 0; y < sliders.length; y++) {
if (sliders[y].type === "range") {
sliders[y].oninput = getVals;
// Manually trigger event first time to display values
sliders[y].oninput();
}
}
}
}
Have tried looking at other similar questions on Stack Overflow and they don't work.

Onclick event in JS shows results for a second before automatically resetting form

This is a simple quiz/questionnaire, that'll display results of the quiz on submission. It shows the results, but only for about half a second before resetting the page. I would also like for the page to show an alert if the user says they're under 18 when the quiz is submitted; it wouldn't keep them from seeing the answers, but just giving them a message.
function checkAge() {
if(age<18) {
alert("Always make sure you have adult supervision while caring for and handling any venomous arachnid.");
} }
function generateAnswers() {
var choice1score = 0;
var choice2score = 0;
var choice3score = 0;
var choice4score = 0;
}
var chosenAnswers = document.getElementsByTagName('result');
for (i=0; i<chosenAnswers.length; i++) {
if (chosenAnswers[i].checked) {
// add 1 to that choice's score
if (chosenAnswers[i].value == 'choice1') {
choice1score = choice1score + 1;
}
if (chosenAnswers[i].value == 'choice2') {
choice2score = choice2score + 1;
}
if (chosenAnswers[i].value == 'choice3') {
choice3score = choice3score + 1;
}
if (chosenAnswers[i].value == 'choice4') {
choice4score = choice4score + 1;
}
}
}
var maxscore = Math.max(choice1score,choice2score,choice3score,choice4score);
var resultBox = document.getElementById('result');
if (choice1score == maxscore) {
resultBox.innerHTML = "Asian Forest Scorpion"
}
if (choice2score == maxscore) {
resultBox.innerHTML = "Deathstalker Scorpion"
}
if (choice3score == maxscore) {
resultBox.innerHTML = "Desert Hairy Scorpion"
}
if (choice4score == maxscore) {
resultBox.innerHTML = "Emperor Scorpion"
}
}
This is where I put the code:
https://codepen.io/cryceks/pen/vjgzOZ
Use:
event.preventDefault();
This prevents the webpage from reloading and therefore clearing form data

javascript random gen nr + loops

I'm trying to make an program where it randomly picks 10 questions out of X questions(got 14 random ones written at the moment) without it picking the same questions again but i've been stuck for 4 hours on this junk.
My problem is with "randomNumbers()" function. This function generates random number (which marks the question respectively) and then checks if the numberArray already has generated number. If it doesnt, the number is supposed to be pushed to array.
I think I figured out the problem to be ## VERSION 1 ## for-loops if/else conditions. Any help ? :(
//edit, is while (true) correct way to handle this?
// dont mind ##VERSION 2## it was the first way I tried solving the problem.
(a lot of console logs to determine the bug :P )
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>Testimiskeskkond</title>
<!--<link rel="stylesheet" type="text/css" href="style.css"/> -->
<script src="scripts/jquery-2.1.4.min.js"></script>
<script src="scripts/js.js"></script>
</head>
<body>
<button onclick="startQuiz()">Alusta testimist</button>
<div id="question1"></div>
<div id=questions></div>
</body>
JAVASCRIPT
var amountOfQuestions = 11;
var questionCounter = 0;
var numberArray = new Array();
var questions = new Array();
questions[0] = 'Mitu kassi elab P2rnus?',
questions[1] = 'Mis on kassi nimi?',
questions[2] = 'Mida kass teeb?',
questions[3] = 'Millal kass syndis?',
questions[4] = 'Mitu hammast kassil on?',
questions[5] = 'Mitu kyynt on kassil?',
questions[6] = 'Mitu k6rva on kassil?',
questions[7] = 'Mis v2rvi on kass?',
questions[8] = 'Tooli v2rvus?',
questions[9] = 'Laua suurus?',
questions[10] = 'Lemmik jook?',
questions[11] = 'Lemmik s88k?',
questions[12] = 'Raamatupoe nimi?',
questions[13] = 'Viinapoe nimi?';
function startQuiz() {
var setQuestions = "";
while (questionCounter < amountOfQuestions) {
var random = randomNumbers();
console.log(random + "appppppi");
if (questionCounter < amountOfQuestions) {
setQuestions += questions[random] + "<br>";
questionCounter += 1;
} else {
setQuestions += questions[random];
questionCounter += 1;
}
}
$('#questions').html(setQuestions);
}
function randomNumbers() {
var arrLength = numberArray.length;
while (true) {
console.log(arrLength);
var randomNr = Math.floor(Math.random() * 14);
console.log(randomNr + " tereeeeeeeeee");
/*
######################
########### VERSION 1
######################*/
if (arrLength == 0) {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} else if (arrLength == 1) {
console.log("oooooooooooo");
if (numberArray[0] == randomNr) {
console.log("xxxxxxxxxxxxx");
break;
} else {
console.log("rrrrrrrrrrrrrrr");
numberArray.push(randomNr);
break;
}
} else {
for (var i = 0; i < arrLength-1; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
}
/*
######################
########### VERSION 2
######################
if (arrLength > 0) {
console.log("oooooooooooo");
for (var i = 0; i < arrLength; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
} else {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} */
}
return randomNr;
}
let selectionCount = 10;
let randomQuestions = [];
while(randomQuestions.length < selectionCount) {
let randomNr = Math.floor(Math.random() * questionList.length);
if(!randomQuestions.includes(randomNr)) {
randomQuestions.push(randomNbr);
}
}

Change range element's step depending on it's value

Right now I have this range element:
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>
I want its "step" to change depending on its value. For example, if the value is less than 200000 then step = 5000, if more than 200000 then step= 50000.
How can I do that? Do I create a function with simple "if" statements and make it run onchange of the range?
All example i've seen involve jQuery or something else, can i do this without...that?
See below, change the ranges as needed
function calculate() {
var input = document.getElementById('sumRange');
var val = input.value;
var newStep;
if (val < 100000) {
newStep = 10;
} else if (val < 150000) {
newStep = 20;
} else if (val < 200000) {
newStep = 30;
} else if (val < 250000) {
newStep = 40;
} else {
newStep = 50;
}
input.step = newStep;
}
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>
here is what you can do in your calculate function, using jquery
calculate = function() {
if ($('#sumRange').attr('value') < 200000 ) {
$('#sumRange').attr('step',5000);
} else {
$('#sumRange').attr('step',50000);
}
var sumRange = document.getElementById(“sumRange”);
sumRange.oninput = function(){
var value = this.value;
if (value > 20000) {
this.step = 50000;
} else {
this.step=5000;
}

Js & Jquery:Understanding a search code with JSON request

i have a js search in my page that i don't get perfectly how does work because i don't know 100% js and jquery. As far as i think the code takes the input and search match with a link to a database that returns a JSON value depending on what name you put on the link (?name="the-input-name-here"), then, the code parse the json and determinates if the name of the input it's a valid surname and if it is the check if it has a running page, if it has redirects you to that page. If the input is a valid surname but doesn't have a running page it redirects you to "landing-page-yes.html". If the input isn't a valid surname it redirects you to "landing-page-no.html".
I need help to understand how the code does this in order to make a simplify version. How that call to another url database is parsed by the js ? How can i think something similar with a backend and ajax ? I need to understand 100% what this code does and i'm kinda lost.
THANKS !
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="srchid" width="100" onkeypress="submitonenter(document.getElementById('srchid').value, event, this)" />
<input onclick="nameCheck(document.getElementById('srchid').value);" value="CLICK HERE" type="button" style="background-color:#990033; color:#fff;border-style:outset;">
<div id="nameresults"></div>
<script >
<!--
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
} return false;
}
function cursor_wait() {
document.body.style.cursor = 'wait';
}
// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}
function nameCheck(sName) {
sName = trim(sName);
if(sName == ""){
alert("Please enter a name!");
return false;
}
cursor_wait();
routeToNameLookup(sName);
cursor_clear();
}
function $(id){return document.getElementById(id);}
// Get JSONP
function getJSON(url){
var s = document.createElement('script');
s.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(s);
}
function testcb(data){
//alert(data[0]);
}
function loaded(data) {
var name = document.getElementById('srchid').value;
var xmlhttp2;
//Using innerHTML just once to avoid multi reflow
$("nameresults").innerHTML = data[0];
if($("nameresults").innerHTML == 1){
if(data[1] == 1){
//display name page with content
var sNewName = name.replace (/'/g, ""); //remove any '
sNewName = removeSpaces(sNewName);
sNewName = convertNonAscii(sNewName);
//redirect to name crest
var sUrl = "http://www.heraldicjewelry.com/" + sNewName.toLowerCase() + "-crest-page.html";
//getJSON("http://www.gohapp.com/updatenamesearch.php?id=" + data[2] + "&pageurl=" + sUrl + "&callback=testcb");
//postwith(sUrl,{'pname':name});
window.location=sUrl;
} else {
//post to yes page
//postwith("http://www.heraldicjewelry.com/landing-page-yes.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-yes.html";
}
} else {
//post to no page
//postwith("http://www.heraldicjewelry.com/landing-page-no.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-no.html";
}
$("nameresults").innerHTML = "";
}
function routeToNameLookup(sSrchName) {
var name = document.getElementById('srchid').value;
if(sSrchName==""){
alert("Please enter your family name.");
} else {
var rn=Math.floor(Math.random()*1000000000000001)
getJSON("http://www.gohapp.com/namesearch_new.php?name="+name+"&rec=1&callback=loaded&rn="+rn);
}
}
function trim (sStr) {
var str = sStr.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
function removeSpaces(string) {
return string.split(' ').join('');
}
var PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
var UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// remove accentued from a string and replace with ascii equivalent
function convertNonAscii(s) {
if (s == null)
return null;
var sb = '';
var n = s.length;
for (var i = 0; i < n; i++) {
var c = s.charAt(i);
var pos = UNICODE.indexOf(c);
if (pos > -1) {
sb += PLAIN_ASCII.charAt(pos);
} else {
sb += c;
}
}
return sb;
}
function submitonenter(name, evt,thisObj) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
thisObj.blur();
nameCheck(name);
//alert("looking for " + name);
}
}
}
//-->
</script>

Categories