Else If not working in Javascript Conversion app - javascript

So I'm creating a hybrid mobile JS app and everything is working fine so far until this last else if statement. I'm trying to convert inches to yard. I have the right code down, but its still not working. I only get the same number I type back in the results. What am I doing wrong? I am using Jquery and Jquery Mobile in the app as well.
Heres the HTML bit:
<form>
<div class="ui-field-contain">
<select name="select-native-3" id="distance" data-iconpos="left">
<option value="inch">Inch</option>
<option value="foot">Foot</option>
<option value="yard">Yard</option>
<option value="mile">Mile</option>
<option value="mm">Millimeter</option>
<option value="m">Meter</option>
<option value="km">Kilometer</option>
</select>
</div>
<h4>Convert To:</h4>
<div class="ui-field-contain">
<select name="select-native-3" id="distanceToo" data-iconpos="left">
<option value="1">Inches</option>
<option value="2">Feet</option>
<option value="3">Yards</option>
<option value="4">Miles</option>
<option value="5">Millimeters</option>
<option value="6">Meters</option>
<option value="7">Kilometers</option>
</select>
</div>
</form>
Now the JavaScript part:
$("#calcD").on("tap", function() {
var dist = document.getElementById("inpD").value;
var answerAreaD = document.getElementById("ansD");
var select = document.getElementById("distance");
var selectToo = document.getElementById("distanceToo");
if(select.value == "inch" && selectToo.value == "1") {
answerAreaD.value = dist;
}
else if(select.value == "foot" && selectToo.value == "2") {
answerAreaD.value = dist;
}
else if(select.value = "yard" && selectToo.value == "3") {
answerAreaD.value = dist;
}
else if(select.value = "mile" && selectToo.value == "4") {
answerAreaD.value = dist;
}
else if(select.value == "mm" && selectToo.value == "5") {
answerAreaD.value = dist;
}
else if(select.value == "m" && selectToo.value == "6") {
answerAreaD.value = dist;
}
else if(select.value == "km" && selectToo.value == "7") {
answerAreaD.value = dist;
}
else if(select.value == "inch" && selectToo.value == "2") {
var distInchFeet = dist / 12;
answerAreaD.value = distInchFeet;
}
else if(select.value == "inch" && selectToo.value == "3") {
var distInchYard = dist * 0.0277777777778;
answerAreaD.value = distInchYard;
}
});

In all of your else if statements you need to have the comparison operator == or ===. For mile and yard you have =, which is assigning the value rather than comparing it.

Related

Need help using document.getElementById with <form> tag [duplicate]

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 10 months ago.
I'm trying to use a form tag with document.getElementById, but I am having issues with having the Javascript retrieve the values from my inputs. Or maybe something else is completely wrong and I'm just stupid.
HTML:
<form onsubmit="testMonth();">
<label>Month:
<input id="month" list="months" name="Months"></label>
<datalist id="months">
<option value="May">
<option value="June">
<option value="July">
<option value="August">
<option value="September">
<option value="October">
</datalist>
<label for="age">Age:</label>
<input type="text" id="age" name="age">
<label for="coupon">Coupon Code:</label>
<input type="text" id="coupon" name="coupon">
<input type="submit" name="submit">
</form>
JS:
function testMonth() {
var month = document.getElememtById('month').value;
if(month == July || month == August) {
document.getElementById('price').innerHTML = "$150";
}
else {
if(month == null) {
alert('Please fill out the month field');
}
else {
testAge();
}
}
}
function testAge() {
var age = document.getElementById('age').value;
if(age == null) {
alert('Please fill out the age field');
}
else {
if(age < 5 || age > 90) {
alert('Visiters must be between the ages of 5 and 90');
}
else {
if (age == 10 || age == 90) {
testCoupon();
}
else {
if (age < 18 || age == 18) {
document.getElementById('price').innerHTML = "$50";
}
else {
document.getElementById('price').innerHTML = "$150";
}
}
}
}
}
function testCoupon() {
var coupon = document.getElementById('coupon').value;
if (coupon == "YEET") {
document.getElementById('price').innerHTML = "$0";
}
else {
if (document.getElementById('age').value == 10) {
document.getElementById('price').innerHTML = "$50";
}
else {
document.getElementById('price').innerHTML = "$150";
}
}
}
When I fill out the fields on the website and hit sumbit, the site just refreshes, which makes me think that the submit button/form syntax is wrong. However, the issue could also be that I have written the JS wrong, and it's not retrieving the value of the form inputs.
I found 3 bugs in your code. First you should use
event.preventDefault()
as second in your first if statement inside testMonth function you are checking July and August but you do not have that variables. You should check as string or create variable for them and last one you have typo in getElementById again in first part of testMonth function
function testMonth() {
event.preventDefault()
var month = document.getElementById('month').value;
if(month == 'July' || month == 'August') {
document.getElementById('price').innerHTML = "$150";
}
else {
if(month == null) {
alert('Please fill out the month field');
}
else {
testAge();
}
}
}
function testAge() {
var age = document.getElementById('age').value;
if(age == null) {
alert('Please fill out the age field');
}
else {
if(age < 5 || age > 90) {
alert('Visiters must be between the ages of 5 and 90');
}
else {
if (age == 10 || age == 90) {
testCoupon();
}
else {
if (age < 18 || age == 18) {
document.getElementById('price').innerHTML = "$50";
}
else {
document.getElementById('price').innerHTML = "$150";
}
}
}
}
}
function testCoupon() {
var coupon = document.getElementById('coupon').value;
if (coupon == "YEET") {
document.getElementById('price').innerHTML = "$0";
}
else {
if (document.getElementById('age').value == 10) {
document.getElementById('price').innerHTML = "$50";
}
else {
document.getElementById('price').innerHTML = "$150";
}
}
}
<form onsubmit="testMonth();">
<label>Month:
<input id="month" list="months" name="Months"></label>
<datalist id="months">
<option value="May">
<option value="June">
<option value="July">
<option value="August">
<option value="September">
<option value="October">
</datalist>
<label for="age">Age:</label>
<input type="text" id="age" name="age">
<label for="coupon">Coupon Code:</label>
<input type="text" id="coupon" name="coupon">
<input type="text" id="price" name="price">
<input type="submit" name="submit">
</form>

Open JavaScipt URL in new window

Wondering if anyone can help. I've created some code that depending on what option the user picks, they get taken to a specific URL. I have it all working fine, however, the URL won't open in a new window.
Any help would be brilliant.
This is the code:
$(document).ready(function() {
var selectVal1 = $("#selectBox1").val();
var selectVal2 = $("#selectBox2").val();
$("#selectBox1").change(function() {
selectVal1 = $("#selectBox1 option:selected").val();
});
$("#selectBox2").change(function() {
selectVal2 = $("#selectBox2 option:selected").val();
});
$("#click").click(function() {
if(selectVal1 == 'A' && selectVal2 == 'A'){
location = "https://www.google.com/animalmanagement-25thaug", '_blank';}
else if(selectVal1 == 'A' && selectVal2 == 'B'){
location = "https://www.google.com/animalmanagement-26thaug", '_blank';}
if(selectVal1 == 'B' && selectVal2 == 'A'){
location = "https://www.google.com/artdesign-25thaug", '_blank';}
else if(selectVal1 == 'B' && selectVal2 == 'B'){
location = "https://www.google.com/artdesign-26thaug", '_blank';}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.sthelens.ac.uk/book-slot/book-enrolment.js"></script>
<h3>Book Your Enrolment Slot</h3>
<select id="selectBox1">
<option value="">Select which subject you would like to study?</option>
<option value="A">Animal Management</option>
<option value="B">Art & Design</option>
</select>
<select id="selectBox2">
<option value="">Select what date you would like to come in and enrol</option>
<option value="A">Tuesday 25th August 2020</option>
<option value="B">Wednesday 26th August 2020</option>
</select>
<input id="click" type="button" value="Book Now" class="button">
window.open might help
window.open(<url>);
Or
window.open(<url>, "_blank"); // opens in new tab
You can use window.open(your url) ..
Or you can refer this doc.
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
You can use code below
$("#click").click(function() {
if(selectVal1 == 'A' && selectVal2 == 'A'){
var location = "https://www.google.com/animalmanagement-25thaug";
} else if (selectVal1 == 'A' && selectVal2 == 'B'){
var location = "https://www.google.com/animalmanagement-26thaug";
} else if (selectVal1 == 'B' && selectVal2 == 'A'){
var location = "https://www.google.com/artdesign-25thaug";
} else if (selectVal1 == 'B' && selectVal2 == 'B'){
var location = "https://www.google.com/artdesign-26thaug";
}
var wind = window.open(location, '_blank');
//wind.focus(); // If required
});

Alternative to a lot of if statements jquery

I'm trying to validate my form using jquery before submission. The user needs to fill up the Task accordingly, they cannot submit the form with fill-up Task 2 and missing Task 1. And also the Task cannot be duplicated with other Task. I'm wondering if there any better way to compare all of this, in a simple method.
The Javascript currently I'm doing. Still not complete yet because looking for better ways.
$(function() {
$( "#create_model" ).submit(function( event ) {
if(validate_task()){
alert("Check your task.");
event.preventDefault();
} else {
$("#create_model").submit();
}
});
});
function validate_task() {
if ($('#CatTask2ID').val() !== "" && $('#CatTask2ID').val() === "") {
return "Task 1 is empty"; //return FALSE;
} else if ($('#CatTask3ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "") {
return "Task 1 or 2 is empty"; //return FALSE;
} else if ($('#CatTask4ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask1ID').val() === $('#CatTask2ID').val() || $('#CatTask1ID').val() === $('#CatTask3ID').val() .......and others........... ) {
return "Duplicates"; //return FALSE;
}
}
First use classes instead of IDs so you can get a collection of all selects easily, then map each select to its value to get an array of values.
Find the index of the first value which is the empty string. If any values after that one are populated, return an error saying that the index of that empty string is empty.
Otherwise, take the populated values (from indices 0 to the index of the first empty string), and check if the size of a Set of those values is equal to the length of the array:
function validate_task() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex > 0 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
// OK
}
Live demo:
document.addEventListener('change', () => console.log(validateTask()));
function validateTask() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex !== -1 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
return 'OK'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
function validate_task() {
var error_msg = [];
if($('#CatTask1ID').val() === ""){
error_msg.push('1');
}
if($('#CatTask2ID').val() === ""){
error_msg.push('2');
}
if($('#CatTask3ID').val() === ""){
error_msg.push('3');
}
//......
return error_msg;
}
function validate_task_msg() {
var arr = validate_task()
if(arr&& arr.length<=0){
return true;
}else if(arr.length == 10){//more
return "Duplicates";
}else {
var msg = arr.join(',');
return "Task "+ msg + " is empty"
}
}

Changing textfield currency type

<select data-placeholder="Please select a payment method.." style="width:50%;" class="chosen" onchange="currencyChange(this.value)">
<option value=""></option>
<optgroup label="Cash">
<option value="Paypal">Paypal</option>
<option value="Bitcoin">Bitcoin</option>
<option value="Western Union">Western Union</option>
<option value="Delivery">Delivery</option>
</optgroup>
<optgroup label="Ingame Currency">
<option value="RS3 GP">RS3 GP</option>
<option value="OSRS GP">OSRS GP</option>
</optgroup>
</select>
<script type="text/javascript">
var sign = "null";
var placement = "null";
float budget = "null";
function currencyChange(data){
if (data === 'Paypal') {
sign = "$";
placement = "before";
}
if (data === 'Bitcoin') {
sign = "$";
placement = "before";
}
if (data === 'Western Union') {
sign = "$";
placement = "before";
}
if (data === 'Delivery') {
sign = "$";
placement = "before";
}
if (data === 'RS3 GP') {
sign = "M/GP";
placement = "after";
}
if (data === 'OSRS GP') {
sign = "M/GP";
placement = "after";
}
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
}
</script>
I am trying to change the currency type of another textfield id="budget" to add a currency symbol dependent on the choice of payment method..?
But I get no such action when selecting the payment type.
remove this, Its works
float budget = "null";
And,
add below select
<input type="text" id="budget">
Edited
if (placement === 'before') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = sign + toreplace.replace("$","");
}
if (placement === 'after') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = toreplace+ sign;
}
Try this fiddle it will not accepting double sign.
http://jsfiddle.net/pee7d6qr/1/
if (placement === 'before') {
if(document.getElementById("budget").value.indexOf("$") == -1){
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
if (placement === 'after') {
if(document.getElementById("budget").value.indexOf("M/GP") == -1){
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
Remove the float variable in javascript
Budget Input element is missing
<input type="text" name="budget" id="budget" value=>
Use the below code
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value.replace(/[^0-9.]/g,'');
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value.replace(/[^0-9.]/g,'') + sign;
}
Now you need to strip those "$,M/GP" stuff from the string
With little help from stackoverflow:
value = document.getElementById("budget").value;
value = value.replace(/\D/g,''); //strip non-numeric characters from string
Then
if (placement === 'before') {
document.getElementById("budget").value = sign +" "+ value;
}
if (placement === 'after') {
document.getElementById("budget").value = value +" "+ sign;
}
jsFiddle

javascript multiple conditions don't work

I have a dropdown list ,every option of the list have a year and a month .
I want to sort a select options according to year or month or both that are .
so I can display options sorted by year or month or year and month together or show everything .
I have the following event :
$('#years,#months').bind('change', function () {
y = $('#years').val();
m = $('#months').val();
$('#files > option').each(function () {
$(this).show();
});
$('#files > option').each(function () {
string = $(this).text();
//first situation
if (y == 'All' && m == 'All')
$(this).show();
// second situation
else if ((y == 'All') && string.indexOf(m) == -1)
$(this).hide();
//third situation
else if ( string.indexOf(y) == -1 && m == 'All')
$(this).hide();
// fourth situation
else if (string.indexOf(y) == -1 || string.indexOf(m) == -1)
$(this).hide();
});
});
with html code :
<select id='years'>
<option value='All'>All</option>
<option value='2013'>2013</option>
<option value='2012'>2012</option>
</select>
<select id='months'>
<option value='All'>All</option>
<option value='Feb'>Feb</option>
<option value='Jan'>Jan</option>
</select>
<br/>
<br/>
<select id='files' siz='10'>
<option value='0'>sdgsdfsadfsd1-2013-Feb-1212</option>
<option value='1'>fsadfadsfadsfadsf2-2012-Feb-123123</option>
<option value='2'>fsadfadsfadsfadsf3-2012-Jan-123123</option>
<option value='3'>fsadfadsfadsfadsf4-2013-Jan-123123</option>
<option value='4'>fsadfadsfadsfadsf5-2012-Feb-123123</option>
<option value='5'>fsadfadsfadsfadsf6-2013-Feb-123123</option>
<option value='6'>fsadfadsfadsfadsf7-2013-Feb-123123</option>
<option value='7'>fsadfadsfadsfadsf8-2013-Jan-123123</option>
<option value='8'>fsadfadsfadsfadsf9-2012-Jan-123123</option>
<option value='9'>fsadfadsfadsfadsf10-2013-Feb-123123</option>
<option value='10'>fsadfadsfadsfadsf11-2012-Feb-123123</option>
</select>
second and third situations are not working !!
it deals with the two conditions (true && false) , (false && true ) as they are same values ! I have no idea why !
here's a Demo
Your logic is wrong; the last condition is being evaluated when it shouldn't be. (For instance: if y == 'All' and also string.indexOf(m) >= 0). Try this instead:
$('#files > option').each(function () {
var string = $(this).text();
var show;
if (y == 'All') {
show = m == 'All' || string.indexOf(m) >= 0;
} else if (m == 'All') {
show = string.indexOf(y) >= 0;
} else {
show = string.indexOf(y) >= 0 && string.indexOf(m) >= 0;
}
if (show) $(this).show();
else $(this).hide();
});

Categories

Resources