How to make add a median function to a calculator? - javascript

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;
}
}

Related

registration form validation using javascript

Im partly there but it would be helpful if any of you guys could send the entire code .
1) Create a form with the below given fields and validate the same using javascript or jquery.
Name : Text box- mandatory
Gender : Radio Button
Age : Text box - Accept Number only - (check for valid Age criteria)
Email : Text box -  should be in format example#gmail.com
Website : Text box -  should be in format http://www.example.com
Country : Select box with 10 countries
Mobile :  Text box - should be a 10 digit number - Display this field only after the user selects a country
Social Media Accounts : Facebook, Google, Twitter (3 checkboxes) - Display Social media section only if selected Country is India
I agree the Terms and Conditions - Checkbox
All fields are mandatory and show error messages for all fields(if not valid)
Only allow to submit form after checking the 'I agree' checkbox.
<!DOCTYPE html>
<html>
<head>
<title>Get Values Of Form Elements Using jQuery</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="form_value.css"/>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="form_value.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#social").hide() ;
// $("#hide").click(function(){
// $("social").hide();
// });
// var country = document.getElementByName("country")[0].value;
// if (country.value == "India") {
// $("#show").click(function(){
//     $("social").show();
// });
// }
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.email_id.value)) {
alert("You have entered an invalid email address!")
return (false)
}
});
</script>
</head>
<body onload="disableSubmit()">
<div class="container">
<div class="main">
<h2>Get Values Of Form Elements Using jQuery</h2>
<form action="">
<!-- Text -->
<br>
<br>
<label>Name :</label>
<input type="text" id="text" name="name" value=""required/><br>
<!-- Radio Button -->
<br><br><br>
<label>Gender:</label>
<input type="radio" name="male" value="Male">Male
<input type="radio" name="female" value="Female">Female
<br><br>
<!-- Textarea -->
<label>Email :</label>
<input type="text" id="Email" value="" id="Email"/>
<br>
<br><br>
Age: <input type="text" id="Age" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<br><br>
<label> Website:</label>
<input type="text" id="text" value="" name = "Website" id="website" />
<script type="text/javascript">
function validate() {
if(Website.value.length==0)
{
document.getElementById("Website").innerHTML="Should be in the format http://www.example.com ";
}
}
</script>
<br><br>
<label>Country:</label>
<select class="country" id = "country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="uae">United Arab Emirates</option>
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="netherlands">Netherlands</option>
<option value="yemen">Yemen</option>
<option value="pakistan">Pakistan</option>
<option value="russia">Russia</option>
</select>
<br><br>
<label>Mobile:</label>
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
<script type="text/javascript">
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
<br><br>
<div id = "social" >
<p>Social Media Accounts.</p> <input type="checkbox" id="Facebook" value="Facebook"><label for="Facebook"> Facebook</label><br> <input type="checkbox" id="Google" value="Google"><label for="Google"> CSS</label><br> <input type="checkbox" id="Twitter" value="Twitter"><label for="Twitter"> Twitter</label><br>
</div>
<br>
<br>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)"> I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</script>
</form>
</div>
</body>
</html>
this is my js page content form_value.js
$(document).ready(function() {
// Function to get input value.
$('#text_value').click(function() {
var text_value = $("#text").val();
if(text_value=='') {
alert("Enter Some Text In Input Field");
}else{
alert(text_value);
}
});
// Funtion to get checked radio's value.
$('#gender_value').click(function() {
$('#result').empty();
var value = $("form input[type='gender']:checked").val();
if($("form input[type='gender']").is(':checked')) {
$('#result').append("Checked Radio Button Value is :<span> "+ value +" </span>");
}else{
alert(" Please Select any Option ");
}
});
// Get value Onchange radio function.
$('input:gender').change(function(){
var value = $("form input[type='gender']:checked").val();
alert("Value of Changed Radio is : " +value);
});
// Funtion to reset or clear selection.
$('#radio_reset').click(function() {
$('#result').empty();
$("input:radio").attr("checked", false);
});
$('#Email').click(function() {
function validate(Email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za- z]{2,4})$/;
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Should be in the format example#gmail.com');
return (false);
}
}
});
});
$("#Age").click(function() {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
});
</script>
<!DOCTYPE html> <html> <head> <script> function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var gender = document.forms["myForm"]["gender"].value;
var age = document.forms["myForm"]["age"].value;
var a = parseInt(age);
var email = document.forms["myForm"]["email"].value;
var url = document.forms["myForm"]["website"].value;
var country = document.forms["myForm"]["country"].value;
var mobileCountry = document.forms["myForm"]["mobileCountry"].value;
var mcLength = mobileCountry.length;
if (name == "") {
alert("Name Field is mandatory");
return false;
}
if (gender != "male" && gender != "female") {
alert("Atleast one Gender has to be chosen");
return false;
}
if(isNaN(a)){
alert("Age is compulsory and must be a number");
return false;
}
if(email == ""){
alert("Email address is required");
}
else if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
} else{
alert("Email address entered is invalid");
return false;
}
if(/^(ftp|http|https):\/\/[^ "]+$/.test(url)){
} else{
alert("Website url entered is invalid");
return false;
}
if(country != "choose"){
document.getElementById("mc").style.display = "block";
} else{
document.getElementById("mc").style.display = "none";
}
if(mcLength != 10){
alert("Number must be ten digits");
return false;
}
} function displaySocial(){ var social =
document.getElementById("social");
var mc = document.getElementById("mobileCountry");
var country = document.getElementById("country");
var selectedValue = country.options[country.selectedIndex].value;
if (selectedValue != "choose") {
if(selectedValue == "india"){
if(social.style.display = "none"){
social.style.display = "block";
} else{
social.style.display = "none";
} } else{
social.style.display = "none"; }
if(mc.style.display = "none"){
mc.style.display = "block";
} else{
mc.style.display = "none"; } } else{
mc.style.display = "none"; }
} </script> </head> <body> <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"><br> Gender: <input type="radio" name="gender" value="male"> Male <input type="radio" value="female" name="gender"> Female <br> age: <input type="text" name="age"><br> email: <input type="text" name="email"><br> website: <input type="text" name="website"><br> country: <select type="text" name="country" id="country" onclick="displaySocial()"><option value="choose">--choose--</option><option value="usa">USA</option><option value="uk">UK</option><option value="ng">Nigeria</option><option value="india">India</option></select><br> <span id="mobileCountry" style="display: none;">mobile country: <input type="text" name="mobileCountry"><br></span> <span id="social" style="display: none;">Social Media: <input type="radio" name="gender"> Facebook <input type="radio" name="gender"> Google <input type="radio" name="gender"> Twitter</span> <br> <p> <input type="submit" value="Submit"> </form> <p id="error"></p> </body> </html>

jQuery iterate through input fields and disable

I have a question I'm trying to figure out...
I have a lot of inputs in a form, but I only need to iterate through the ones in the div with player class.
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
What I need is to iterate through them all once an input field has been modified and calculate how many of the input fields have 0 in them and if its 1 or more than 4 disable submit button.
I've been trying like this but it doesn't seem to work
$(document).ready(function()
{
$(function()
{
var $sum = parseInt($("#sum").text(), 10);
var $num = 0;
if(($sum == 0))
{
$("button[name=submit2]").attr("disabled", "disabled");
}
$(".player input[type=text]").bind("DOMSubtreeModified", function()
{
$.each($("input[type=text]"),function(){
if (!isNaN(+this.value))
{
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
});
})
});
I've also tried
$(document).ready(function(){
$(".unit").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".unit").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Try changing
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
with
if($(this).val() != "" && $(this).val() !=0) {
++$num;
}
to be more jQuery style
I guess this is what you want :
// control function
function checkInputs() {
var num = 0;
// foreach inputs
$(".player input").each(function(i,item) {
var value = $(this).val();
if (value.trim() === "0") {
num++;
}
});
if (num === 1 || num > 4) {
$("#myForm input[type='submit']").attr("disabled", "true");
} else {
$("#myForm input[type='submit']").removeAttr("disabled");
}
}
// if you want a first check after loading the page :
checkInputs();
$(".player input").change(
// This function will be called each time an input change in the player div
checkInputs
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myForm">
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
<input type="submit"/>
</form>
I am not sure why are you checking the length? this.value.length!=0
I tweaked your code, here is the fiddle link : http://jsfiddle.net/bLa6evpg/
Hope this help!
I couldn't follow your function, but I believe your problem is that you are running it on page load, and not on the onchange of your input boxes. I achieved the desired functionality by doing that in this codepen
html:
<div class="player">
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number"/>
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
</div>
<button name="submit2">Click</button>
JS:
function validateChanges() {
var playerDiv = document.getElementsByClassName("player")[0];
var inputs = playerDiv.getElementsByTagName("input");
var total = 0;
for(var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if(total == 1 || total > 4) { // IF total is 1 or more then 4
document.getElementsByTagName("button")[0].disabled = true;
} else {
document.getElementsByTagName("button")[0].disabled = false;
}
}
looks like i was almost right just messed up a bit Silent_coder fixed this +i added some tricks i saw here
$(document).ready(function(){
CheckNull();
$(".player input").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".player input").each(function() {
if(this.value != 0 ) {
$num++;
}
});
if (($num > 4) || ($num <= 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Works like i charm for me ^^
Here is a JsFiddle example
$(function () {
$('.unit').on('change', function () {
var units = 0;
$('.unit').each(function (index, value) {
var unit = parseInt($(value).val(),10);
units += unit;
if(units >= 4 || units === 1) {
$('form > button').prop('disabled', true);
} else {
$('form > button').prop('disabled', false);
}
});
});
});

How to show 0 when variable is negative

I have a simple calculator. What I want to get is to show 0 value when calculations value is negative.
Here is the code:
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
});
$("#sum").val(total.toFixed(2))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Amount
<input type="text" class="amount" />
<br>
<select class="multiply">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>Sum 1
<input type="text" class="summable" />
<br>Sum 2
<input type="text" class="summable" />
<br>Minus 1
<input type="text" class="minusable" />
<br>Minus 2
<input type="text" class="minusable" />
<br>
<input id="sum" type="text" />
<button id="button">Click Me</button>
Simply enter Minus values greater than Amount and Sum. You will get negative value as a result. Please point me how to show "0" when the result value is negative.
Thanks in advance.
You can also use Math.max(), it'll return 0 if the other value is negative:
$("#sum").val( Math.max( total, 0 ).toFixed(2) );
Just add another small thing:
if (total.toFixed(2) > 0)
$("#sum").val(total.toFixed(2));
else
$("#sum").val("0");
Snippet:
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
});
if (total.toFixed(2) > 0)
$("#sum").val(total.toFixed(2));
else
$("#sum").val("0");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Amount
<input type="text" class="amount" />
<br>
<select class="multiply">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>Sum 1
<input type="text" class="summable" />
<br>Sum 2
<input type="text" class="summable" />
<br>Minus 1
<input type="text" class="minusable" />
<br>Minus 2
<input type="text" class="minusable" />
<br>
<input id="sum" type="text" />
<button id="button">Click Me</button>
This will check if the value is positive, if not then use 0.
$("#sum").val(total > 0 ? total.toFixed(2) : 0);
Ternary Operator
Just check in an if if the total is less than 0 if so set the total to 0.
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
if(total<0)
total=0;
});
$("#sum").val(total.toFixed(2))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Amount
<input type="text" class="amount" />
<br>
<select class="multiply">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>Sum 1
<input type="text" class="summable" />
<br>Sum 2
<input type="text" class="summable" />
<br>Minus 1
<input type="text" class="minusable" />
<br>Minus 2
<input type="text" class="minusable" />
<br>
<input id="sum" type="text" />
<button id="button">Click Me</button>
$("#button").click(function() {
var total = 0.0;
$.each($(".amount"), function() {
var amount = parseFloat($(this).val() || 0);
var multiply = parseFloat($(".multiply").val());
if (amount && multiply)
total += amount * multiply;
});
$.each($(".summable"), function() {
total += parseInt($(this).val() || 0);
});
$.each($(".minusable"), function() {
total -= parseInt($(this).val() || 0);
});
if(total < 0){
total = 0;
}
$("#sum").val(total.toFixed(2))
});

Adding input values and default values

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>

Enable a button if value is entered in a textbox of selected radio button

I have three radio buttons which are three options, on selecting, their sub-options will be displayed. The next button should be enabled when some text is entered in the currently selected option's sub-option text box. Entering all sub-options under an option is a must. So i want to enable the next button if values are entered in all text boxes under a selected option and are of some minimum defined length. How can i do this?
Here is the jsfiddle link: http://jsfiddle.net/yYJQY/2/
My code:
<div>
<input type="radio" value="1" name="options" />Option1
<input type="radio" value="2" name="options" />Option2
<input type="radio" value="3" name="options" />Option3
</div>
<div id="option1" style="display: none;">
<label>Enter Value:</label><input type="text" name="value_option1" />
</div>
<div id="option2" style="display: none;">
<label>Enter value1:</label><input type="text" name="value_option2_1" /><br />
<label>Enter value2:</label><input type="text" name="value_option2_2" />
</div>
<div id="option3" style="display: none;">
<label>Select a number:</label>
<select name="quantity" id="number">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select> <br />
<input type="text" id="val1" /> <br />
<input type="text" id="val2" /> <br />
<input type="text" id="val3" /> <br />
</div>
<button disabled>NEXT</button>
My Script:
$(document).ready(function () {
$('input[name=options]').bind('change' ,function() {
if($(this).val() == '1') {
$('#option1').show();
$('#option2').hide();
$('#option3').hide();
}
if($(this).val() == '2') {
$('#option2').show();
$('#option1').hide();
$('#option3').hide();
}
if($(this).val() == '3') {
$('#option2').hide();
$('#option1').hide();
$('#option3').show();
}
})
$('#val2').hide();
$('#val3').hide();
$('#number').bind('change', function() {
if($(this).val() == '1') {
$('#val1').show();
$('#val2').hide();
$('#val3').hide();
}
if($(this).val() == '2') {
$('#val1').show();
$('#val2').show();
$('#val3').hide();
}
if($(this).val() == '3') {
$('#val1').show();
$('#val2').show();
$('#val3').show();
}
})
})
Any help is appreciated. Thank you!!
Try
$(document).ready(function () {
$('input[name=options]').bind('change' ,function() {
$('button').prop('disabled', true)
if($(this).val() == '1') {
$('#option1').show();
$('#option2').hide();
$('#option3').hide();
}
if($(this).val() == '2') {
$('#option2').show();
$('#option1').hide();
$('#option3').hide();
}
if($(this).val() == '3') {
$('#option2').hide();
$('#option1').hide();
$('#option3').show();
}
})
$('#val2').hide();
$('#val3').hide();
$('#number').bind('change', function() {
if($(this).val() == '1') {
$('#val1').show();
$('#val2').hide();
$('#val3').hide();
}
if($(this).val() == '2') {
$('#val1').show();
$('#val2').show();
$('#val3').hide();
}
if($(this).val() == '3') {
$('#val1').show();
$('#val2').show();
$('#val3').show();
}
testButton(this)
});
function testButton(el){
var inputs = $(el).closest('div[id^="option"]').find('input:text:visible');
var flag = true;
inputs.each(function(){
if(!$(this).val()){
flag = false;
return false;
}
});
$('button').prop('disabled', !flag)
}
$('input:text').on('change', function(){
testButton(this)
})
})
Demo: Fiddle

Categories