I have this short form that when the user selects the first option in a dropdown menu, three fields will appear. The first field has a default value while the other two should be fill up by the user. Then I need to get the total of the three fields. If the user selcts the second option, the three fields will not appear. As of now, this is what I've got:
HTML
<select id="select1">
<option value="A">New</option>
<option value="B>Satisfied</option>
</select>
<div id="d1>
<label>This is a default value</label><input type="text" id="input1" placeholder="$75,000" style="width: 100px;"/>
<label>Preferred Value:</label><input type="text" id="input2" value="" style="width: 100px;"/>
<label>Number of Contributors:</label><input type="text" id="input3" value="" style="width: 100px;"/>
<label>Total:</label><input type="text" id="txt1" value=""/>
</div>
jquery
$("#select1").change(function(){
if($(event.target).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
}
});
js
function total(){
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var d = parseFloat(a, 10);
var e = parseFloat(a, 10);
var f = parseFloat(a, 10);
total = d + e + f;
$('#txt1').val(total.toFixed(2));$(
}
Try
jQuery(function($) {
$("#select1").change(function() {
$('#d1').toggle($(this).val() == 'A');
});
$('#input1, #input2, #input3').change(total)
function total() {
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var d = parseFloat(a, 10) || 0;
var e = parseFloat(b, 10) || 0;
var f = parseFloat(c, 10) || 0;
total = d + e + f;
$('#txt1').val(total.toFixed(2));
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select1">
<option value="A">New</option>
<option value="B">Satisfied</option>
</select>
<div id="d1">
<label>This is a default value</label>
<input type="text" id="input1" placeholder="$75,000" style="width: 100px;" />
<label>Preferred Value:</label>
<input type="text" id="input2" value="" style="width: 100px;" />
<label>Number of Contributors:</label>
<input type="text" id="input3" value="" style="width: 100px;" />
<label>Total:</label>
<input type="text" id="txt1" value="" />
</div>
As stated, i's not clear what the question is. I'm assuming you're problem is it just doesn't work. Looking at your code it wouldn't. I re-wrote some of your stuff and I think this is what you are looking for
$("#select1").change(function(event){
if($(this).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
}
});
$("input").blur(function(){
total();
});
function total(){
var a,b,c = 0;
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
if(a != ""){
var d = parseFloat(a, 10);
}else{
var d = 0;
}
if(b != ""){
var e = parseFloat(b, 10);
}else{
var e = 0;
}
if(c != ""){
var f = parseFloat(c, 10);
}else{
var f = 0;
}
var calcTotal = d + e + f;
$('#txt1').val(calcTotal.toFixed(2));
}
You're getting NaN cause it's trying to float a number that doesn't exist. You can check to see if that field has a value and if not render 0
FIDDLE
UPDATE
That's simple enough, just reset the values when you hide the div
NEW FIDDLE
Simply copy and paste code. It is same code as yours, I have done some basic modification in Jquery and there was also mistakes in your html.......plz check it, it will work perfectly. thnx
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script >
$(document).ready(function() {
$("#select1").change(function(){
if($(event.target).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
}
});
});
</script>
<script type="text/javascript">
function total(){
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var d = parseFloat(a, 10);
var e = parseFloat(a, 10);
var f = parseFloat(a, 10);
total = d + e + f;
document.getElementById('txt1').value=total;
}
</script>
</head>
<body>
<select id="select1">
<option value="A">New</option>
<option value="B">Satisfied</option>
</select>
<div id="d1">
<label>This is a default value</label><input type="text" id="input1" placeholder="$75,000" style="width: 100px;"/>
<label>Preferred Value:</label><input type="text" id="input2" value="" style="width: 100px;"/>
<label>Number of Contributors:</label><input type="text" id="input3" value="" style="width: 100px;"/>
<label>Total:</label><input type="text" id="txt1" value="" onclick="total();" />
</div>
</body>
</html>
try this: And please do change your html also they have some error like in select for B you have not closed ".
$("#select1").change(function(event){
if($(event.target).val() == 'A'){
$('#d1').show();
}else{
$('#d1').hide();
$('#txt1').val(0);
}
});
$("input").on('blur',function(){
total();
});
function total(){
var a = $("#input1").val();
var b = $("#input2").val();
var c = $("#input3").val();
var total=0;
if(a.length > 0){
var d = parseFloat(a, 10);
total=total+d;
}
if(b.length > 0){
var e = parseFloat(b, 10);
total=total+e;
}
if(c.length > 0){
var f = parseFloat(c, 10);
total=total+f;
}
$('#txt1').val(total.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1">
<option value="A">New</option>
<option value="B">Satisfied</option>
</select>
<div id="d1">
<label>This is a default value</label><input type="text" id="input1" placeholder="$75,000" style="width: 100px;" >
<label>Preferred Value:</label><input type="text" id="input2" value="" style="width: 100px;" />
<label>Number of Contributors:</label><input type="text" id="input3" value="" style="width: 100px;" />
<label>Total:</label><input type="text" id="txt1" value=""/>
</div>
Related
Im trying to do simple calculation for the fee ,but its doesn't work ,there's no error in the code. Did I miss something in the script ?
<script type="text/javascript">
var bwm = 7.9;
var bswk = 14;
var bsbh = 15;
var wm = 2;
var swk = 11;
var sbh = 12;
var kilo, overkilo, f;
var s = document.getElementById('place');
var place = s.options[s.selectedIndex].value;
var k = document.getElementById('kilo').value;
var tot;
function quote() {
f = document.getElementById('theform');
f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
(k * swk) + bswk = tot;
} else if (place == 'sbh') {
(k * sbh) + bsbh = tot;
} else {
(k * wm) + bwm = tot;
}
document.getElementById('tot').value = 'RM ' + parseFloat;
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
The clear works fine ,but the calculate button won't work even i have input the KG and select a option to calculate .
You need to move the definition of the click handler outside of the change handler, unless the click handler would be defined only when an option changes and also it would be defined on every option change which is unnecessary.
Grab all the required values inside the click handler otherwise you would not have the updated values.
And you also need to set the selected index after resetting the form otherwise the change of option would not be visible.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
function quote(e) {
const selIndex = e.target.selectedIndex;
document.getElementById("theform").reset();
document.getElementById("place").selectedIndex = selIndex;
}
document.getElementById("calc").onclick = function () {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * swk + bswk;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
};
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote(event)">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
Instead of resetting the form you could also update the calculated value every time the option changes.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
document.getElementById("calc").onclick = handleClick;
function handleClick() {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * 10 + 10;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
}
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="handleClick()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
I Removed the left-hand side for assignment and set the value.
You defined the var for all instead of that you can use const.
Also form reset not required.
Here is solution of your code
<html>
<script type="text/javascript">
const bwm = 7.9;
const bswk = 14;
const bsbh = 15;
const wm = 2;
const swk = 11;
const sbh = 12;
let kilo, overkilo, f;
var tot;
function quote() {
const s = document.getElementById('place');
const place = s.options[s.selectedIndex].value;
const k = document.getElementById('kilo').value;
f = document.getElementById('theform');
// f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
tot = (k * swk) + bswk;
} else if (place == 'sbh') {
tot = (k * sbh) + bsbh;
} else {
tot = (k * wm) + bwm;
}
document.getElementById('tot').value = 'RM ' + parseFloat(tot);
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="submit" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
</html>
My find matches function does not seem to be working.
I want to get an array ([]) element by id and do comparisons with it.
The function is supposed to go into the array and generate a random person, then display the match in the text area "showmatches".
I am not sure if the random person is being generated nor if the criteria are being matched in the comparison.
<html>
<head>
<script>
var records = [];
function calculateAge()
{
var dob = document.getElementById('dob').value;
var dobInput = new Date(dob);
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate();
var birthyear = dobInput.getFullYear();
var birthmonth = dobInput.getMonth();
var birthday = dobInput.getDate();
var bYear = year - birthyear;
var bMonth = month - birthmonth;
var bDay = day - birthday;
if (bYear < 18 || bYear > 75)
{
alert("Age cannot be less than 18 or greater than 75");
return false;
}else{
document.getElementById("age").value = bYear + "years old";
}
//document.getElementById("age").value = bYear + "years old";
}
function showAll()
{
show = document.getElementById("showallpersons").innerHTML=records;
show.value = records.join("\n");
}
(window.onload = () => {
var findmatches=document.getElementById('findmatches');
if(findmatches){
findmatches.addEventListener('click', findMatches, false);
}
function findMatches(e)
{
e.preventDefault();
for(var counter=0; counter<records.length; counter++)
{
var currposn = records[counter].value;
var show = document.getElementById("showallmatches").innerHTML= currposn.fname + currposn.lname;
show.value = currposn.join("\n");
do
{
//From here
var randpson = Math.random() * records.length;
randpson = Math.floor(randpson); //To here works, I know that for sure
//I'm not sure if the conditions for the if statements are correct
if(((randpson.age - currposn.age) <= 10) || ((randpson.age - currposn.age) >= 20))
{
if(((randpson.height - currposn.height) <= 10) || ((randpson.height - currposn.height) >= 20))
{
var display = document.getElementById("showmatches").innerHTML= "Matched to: " +randpson.fname + randpson.lname;
//display.value = "Matched to: " + randpson.fname + randpson.lname;
break;
}
}
} while(counter < 10){
//var newDisplay = document.getElementById("showallmatches").innerHTML= null;
}
//console.log(findMatches());
}
}
})()
(window.onload = () => {
var submit = document.getElementById('submit');
if(submit){
submit.addEventListener('click', addnew, false);
}
function addnew(event)
{
//Prevents default submit event
event.preventDefault();
//Accept values entered in form
var fname = document.getElementById('fname').value;
var mname = document.getElementById('mname').value;
var lname= document.getElementById('lname').value;
var dob= document.getElementById('dob').value;
var gender = document.forms['Information']['gender'].value;
var age = document.getElementById('age').value;
parseInt(age);
var bodyType = document.getElementById('Body Type').value;
var occu= document.getElementById('occu').value;
var height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert("A first name is required");
return false;
}
if(mname==null || mname=="")
{
alert("A middle initial is required");
return false;
}
if (lname==null || lname=="")
{
alert("A last name is required");
return false;
}
if(dob==null || dob=="")
{
alert("A DOB is required");
return false;
}
if (gender == "")
{
alert("Please select a gender");
return false;
}
if(height <= 170 || height >= 200)
{
alert("A height between 170, not less and 200, not more is required");
return false;
}
if(bodyType==null || bodyType==""){
alert("Please choose a body type");
return false;
}
if(occu==null || occu=="")
{
alert("Please enter an occupation");
return false;
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(gender);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
document.getElementById("Information").reset();
}
})()
</script>
</head>
<body>
<div class="wrapper">
<header class="page-header">
<nav>
<button class="cta-contact">Contact Us</button>
</nav>
</header>
</div>
<div class="space">
<h1>
<marquee behavior="scroll" direction="right">What are you waiting for? Find your "one" now.</marquee>
</h1>
</div>
<div class="container">
<form name="Information" id="Information">
<fieldset>
<legend>Personal Information</legend>
First Name:
<input id="fname" type="text" size=40 placeholder='First Name' minlength=4 maxlength=40 required />
<br/><br/>
Middle Initial:
<input id="mname" type="text" size=3 placeholder='M Intial' maxlength=1 required />
<br/><br/>
Last Name:
<input id="lname" type="text" size='40' placeholder='Last Name' minlength='4' maxlength='40' required />
<br/><br/>
Date of Birth
<input id="dob" type="date" onchange="calculateAge()"/>
<br/><br/>
Gender:
<input id="male" type="radio" value='M' name="gender" required/> Male
<input id="female" type="radio" value='F' name="gender" required/> Female
<br/><br/>
Age: <input type="text" id="age" disabled />
<br/>
Body Type:
<select id="Body Type">
<optgroup label="Female" id="FemaleOpt">
<option value="Apple"> Apple </option>
<option value="Pear"> Pear </option>
<option value="Pencil"> Pencil </option>
<option value="Hourglass"> Hourglass </option>
<option value="Round"> Round </option>
</optgroup>
<optgroup label="Male" id="MaleOpt">
<option value="Oval"> Oval </option>
<option value="Triangle"> Triangle </option>
<option value="Rectangle"> Rectangle </option>
<option value="Rhomboid">Rhomboid </option>
<option value="Inverted">Inverted Triangle</option>
</optgroup>
</select>
<br/><br/>
Occupation:
<input id="occu" type="text" size=30 maxlength=30 required />
<br/><br/>
Height(in cm):
<input id="height" type="number" size="3" min="171" max="199" value="" required /><br>
<br/><br/>
<textarea id="showallpersons" name="Show All Persons" onclick="showAll()" disabled></textarea>
<textarea id="showmatches" name="Show All Matches" onclick="findMatches()" disabled></textarea>
<br/><br/>
<button id="submit" type="submit">Submit</button>
<button id="findmatches" type="button">Find Matches</button>
</fieldset>
</form>
</div>
</body>
</html>
Do these steps. First you have two window.onload = () (As you are not using addEventListener only one event will be attached).
Steps:
Keep everything intact, just remove the window.onload from both places. Keep all code inside load intact.
Move the entire code block just to the bottom of the html above closing tag. (Doing so, will make window.onload redundant.)
Put console.log() in the click handler and see if it's working (it will)
Let us know.
NOTE: On other hand there are better way to code this, for e.g wait for DOMContentLoaded for attaching event etc., but it's too big to discuss here. First make this work, then we can recommend better approaches.
I am trying to validate HTML form. check a field with two other relative range fields. I want to check all variables isset and between the range before submitting form.
I tried this method not giving the expected result.
How can I do it with other easiest method.
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
The hidden input classes for apples should be aFirst and aLast:
Update: I have corrected the following line:
<input type="hidden" class="aLast" value="25">
Update 2: Works when fruit divs are removed. + Cleanup.
$("#form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var apple = $('.apple').val();
var aFirst = $('.aFirst').val();
var aLast = $('.aLast').val();
var banana = $('.banana').val();
var bFirst = $('.bFirst').val();
var bLast = $('.bLast').val();
var orange = $('.orange').val();
var oFirst = $('.oFirst').val();
var oLast = $('.oLast').val();
var a = true;
var b = true;
var o = true;
if (apple == "" || apple < aFirst || apple > aLast) {
a = false;
}
if (banana == "" || banana < bFirst || banana > bLast) {
b = false;
}
if (orange == "" || orange < oFirst || orange > oLast) {
o = false;
}
if (a && b && o) {
alert('success');
//do ajax
} else {
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
There is a typo,
you have a class name as qFirst and qLast in HTML and js you have written .aFirst and .aLast.
Also convert all values to Number.
When you do .val(), it returns string. And Comparing Strings can give unexpected results
$("#form").submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var apple = Number($('.apple').val());
var aFirst = Number($('.aFirst').val());
var aLast = Number($('.aLast').val());
var banana = Number($('.banana').val());
var bFirst = Number($('.bFirst').val());
var bLast = Number($('.bLast').val());
var orange = Number($('.orange').val());
var oFirst = Number($('.oFirst').val());
var oLast = Number($('.oLast').val());
if(apple >= aFirst && apple <= aLast){
var a = 'true';
}else{
var a = 'false';
}
if(banana >= bFirst && banana <= bLast){
var b = 'true';
}else{
var b = 'false';
}
if(orange >= oFirst && orange <= oLast){
var o = 'true';
}else{
var o = 'false';
}
if(a == 'true' && b == 'true' && o == 'true')
{
alert('success');
//do ajax
}else{
alert('error');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="form-group col-md-12">
<label>Apple Price:</label>
<input type="number" class="apple" placeholder="Type between 15-25">
<input type="hidden" class="aFirst" value="10">
<input type="hidden" class="aLast" value="25">
</div>
<div class="form-group col-md-12">
<label>Banana Price:</label>
<input type="number" class="banana" placeholder="Type between 10-20">
<input type="hidden" class="bFirst" value="10">
<input type="hidden" class="bLast" value="20">
</div>
<div class="form-group col-md-12">
<label>Orange Price:</label>
<input type="number" class="orange" placeholder="Type between 10-20">
<input type="hidden" class="oFirst" value="10">
<input type="hidden" class="oLast" value="20">
</div>
<button type="submit" id="submit">Submit</button>
</form>
I am trying to make Decimal to Fraction Calculator like (https://www.decimal-to-fraction.com/). But I am facing some issues.
I think it's a jquery issue.
Console error shows ($ is not a function)
I have tried this:
$(document).ready(function() {
var params = GetURLParams();
if (Object.keys(params).length > 0 && params.x != "") {
document.getElementById("x").value = params.x;
}
});
function GetURLParams() {
var url = window.location.href;
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while (match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
var gcd2 = function(a, b, f) {
if (f) {
if (b <= 1)
return a;
} else {
if (!b)
return a;
}
return gcd2(b, a % b, f);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="x" name="x" class="intext form-control" tabindex="1">
<button type="button" title="Convert" class="btn btn-lg btn-primary" tabindex="2" onclick="convert()"> Convert</button>
<input class="form-control" type="text" id="y" tabindex="5" readonly>
<input class="form-control" type="text" id="n" tabindex="6" readonly>
<canvas id="frac"></canvas>
<input class="form-control" type="text" id="d" tabindex="7" readonly>
<textarea rows="7" id="area" tabindex="8" class="form-control outtext" readonly></textarea>
I got error in console. It says $ is not a function. Please help me to solve this issue.
Please include this line during the HTML Render
function GetURLParams() {
var url = window.location.href;
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while (match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
var gcd2 = function(a, b, f) {
if( f )
{
if ( b<=1 )
return a;
}
else
{
if ( !b )
return a;
}
return gcd2(b, a % b, f);
};
$( document ).ready(function() {
var params = GetURLParams();
if (Object.keys(params).length > 0 && params.x != "") {
document.getElementById("x").value = params.x;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<input type="text" id="x" name="x" class="intext form-control" tabindex="1">
<button type="button" title="Convert" class="btn btn-lg btn-primary" tabindex="2" onclick="convert()"> Convert</button>
<input class="form-control" type="text" id="y" tabindex="5" readonly>
<input class="form-control" type="text" id="n" tabindex="6" readonly>
<canvas id="frac"></canvas>
<input class="form-control" type="text" id="d" tabindex="7" readonly>
<textarea rows="7" id="area" tabindex="8" class="form-control outtext" readonly></textarea>
Once you feel its fixed download the JQuery Package and save in your package
The probably simplest solution uses Fraction.js:
var f = new Fraction(0.182);
console.log(f.n, f.d); // 91, 500
Good evening! I've created a mean calculator and I would also like to add median function to it. I've attempted to create it but it isn't very successful. Please help! Here is the code I have for the average:
"<fieldset id="numbers"><legend>Numbers</legend>
First number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Second number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Third number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fourth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fifth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" />
</fieldset>
<div id="average">Average: --</div>
<script type="text/javascript">
function getTotal() {
var inputs = document.getElementById('numbers').getElementsByTagName('input'),
count = inputs.length, i, total = 0;
for( i=0; i<count; i++) total += parseInt(inputs[i].value || "0",10);
document.getElementById('average').firstChild.nodeValue = "Average: "+(total/count);
}"
Here is all of my code.
<select id="operator">
<option value="-">Subtract</option>
<option value="+">Add</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<h3>Calculator</h3>
1st Number: <input id="x" data-in="" type="text" /><br>2nd Number:
<input id="y" data-in="" type="text" br>
<hr>Answer:
<div id="d"></div>
<SCRIPT language="JavaScript">
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate() {
var operator = document.getElementById('operator').value;
var value = eval(x.value + operator + y.value);
d.innerHTML = value;
}
x.onblur = calculate;
calculate();
</SCRIPT>
<hr>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<h3>Backround Color</h3>
<select runat="server" id="select">
<option value="A" style="background-color: white;">White</option>
<option value="B" style="background-color: black;">Black</option>
<option value="C" style="background-color: yellow;">Yellow</option>
<option value="D" style="background-color: green;">Green</option>
<option value="E" style="background-color: blue;">Blue</option>
<option value="F" style="background-color: red;">Red</option>
<option value="G" style="background-color: purple;">Purple</option>
<option value="H" style="background-color: orange;">Orange</option>
<option value="I" style="background-color: brown;">Brown</option>
<option value="J" style="background-color: pink;">Pink</option>
<option value="K" style="background-color: cyan;">Cyan</option>
<option value="L" style="background-color: gray;">Gray</option>
</select>
<script>
$('#select').change(function(){
if($(this).val() == 'A'){
$("body").css('background-color', 'white');
}
if($(this).val() == 'B'){
$("body").css('background-color', 'black');
}
if($(this).val() == 'C'){
$("body").css('background-color', 'yellow');
}
if($(this).val() == 'D'){
$("body").css('background-color', 'green');
}
if($(this).val() == 'E'){
$("body").css('background-color', 'blue');
}
if($(this).val() == 'F'){
$("body").css('background-color', 'red');
}
if($(this).val() == 'G'){
$("body").css('background-color', 'purple');
}
if($(this).val() == 'H'){
$("body").css('background-color', 'orange');
}
if($(this).val() == 'I'){
$("body").css('background-color', 'brown');
}
if($(this).val() == 'J'){
$("body").css('background-color', 'pink');
}
if($(this).val() == 'K'){
$("body").css('background-color', 'cyan');
}
if($(this).val() == 'L'){
$("body").css('background-color', 'gray');
}
});
</script>
</body>
</html>
<hr>
<fieldset id="numbers"><legend>Numbers</legend>
First number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Second number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Third number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fourth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" /><br/>
Fifth number: <input type="number" onkeyup="getTotal();" onchange="getTotal();" />
</fieldset>
<div id="average">Average: --</div>
<script type="text/javascript">
function getTotal() {
var inputs = document.getElementById('numbers').getElementsByTagName('input'),
count = inputs.length, i, total = 0;
for( i=0; i<count; i++) total += parseInt(inputs[i].value || "0",10);
document.getElementById('average').firstChild.nodeValue = "Average: "+(total/count);
}
</script>
Working JsBin
Function to find the median of an array:
function median(arr) {
arr.sort( function(a,b) {return a - b;} );
var mid = Math.floor(arr.length/2);
if(arr.length % 2) {
return arr[mid];
}
else {
return (arr[mid-1] + arr[mid]) / 2;
}
}