My html code to take two user chosen input numbers and do calculation. Trouble having it actually do calculation after user chooses inputs. When I put in the two numbers and push calculate it doesnt do anything.
function calc(form)
{
if(isNaN(form.resistance.value))
{
alert("Error in input");
return false;
}
if(form.resistance.value.length > 32)
{
alert("Error in input");
return false;
}
function calc(form1)
{
if(isNaN(form1.strain.value))
{
alert("Error in input");
return false;
}
if(form1.strain.value.length > 32)
{
alert("Error in input");
return false;
}
var Rchange = 2 * form1.strain.value * form.resistance.value;
var newResistance =(parseInt(form.resistance.value) + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw)
{
strRaw = raw.toString();
if(strRaw.length - strRaw.indexOf("0") > 4)
strRaw = strRaw.substring(0,strRaw.indexOf("0") + 5);
return strRaw;
}
</script>
</head>
<body>
<table>
<tr><form1><td>Enter Strain: </td><td><input style="text-align:right" type="text" name="strain"></td></tr>
</table>
<table>
<tr><form><td>Enter Resistance: </td><td><input style="text-align:right" type="text" name="resistance"></td></tr>
<tr><td colspan=2 align="center"><input type="button" value="Calculate" onClick="calc(this.form)"></td></form></tr>
<tr><td>New Resistance: </td><td id="newResistance"></td></tr>
</table>
function calc(form)
{
if(isNaN(form.resistance.value))
{
alert("Error in input");
return false;
}
if(form.resistance.value.length > 32)
{
alert("Error in input");
return false;
}
var Rchange = 2 * form.strain.value * form.resistance.value;
var newResistance =(parseInt(form.resistance.value) + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw)
{
strRaw = raw.toString();
if(strRaw.length - strRaw.indexOf("0") > 4)
strRaw = strRaw.substring(0,strRaw.indexOf("0") + 5);
return strRaw;
}
</script>
</head>
<body>
<table>
<tr><form><td>Enter Strain: </td><td><input style="text-align:right" type="text" name="strain"></td></tr>
</table>
<table>
<tr><form><td>Enter Resistance: </td><td><input style="text-align:right" type="text" name="resistance"></td></tr>
<tr><td colspan=2 align="center"><input type="button" value="Calculate" onClick="calc(this.form)"></td></form></tr>
<tr><td>New Resistance: </td><td id="newResistance"></td></tr>
</table>
Related
I cannot figure out how to make this code just calculate the amount column the addrow and deleterow functions work just can figure out who to get this to calculate the total amount on the amount column.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '#ncItems.add', function() {
var row = $(this).parents('tr');
var clone = row.clone();
// clear the values
var tr = clone.closest('tr');
tr.find('input[type=text]').val('');
$(this).closest('tr').after(clone);
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" + total +".00");
});
$(document).on("blur", ".last", function() {
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" +total+".00");
document.getElementById("ntotal").value ="$" +total+".00";
});
$(document).on('focus', ".last", function() {
var $qty = $(this).parents("tr").find("input[name^='quantity']");
var $pr = $(this).parents("tr").find("input[name^='price']");
var $amnt = $(this).parents("tr").find("input[name^='amount']");
var a = 0;
if ($qty.val() == '' || $pr.val() == '') {
console.log("No values found.");
return false;
} else {
console.log("Converting: ", $qty.val(), $pr.val());
var q = parseInt($qty.val());
var p = parseFloat($pr.val());
console.log("Values found: ", q, p);
}
a = q * p;
$amnt.val(Math.round(a * 100) / 100);
});
$(document).on('click', 'ncItems .removeRow', function() {
if ($('#ncItems .add').length > 1) {
$(this).closest('tr').remove();
}
});
});
</script>
<div id="dvncc">
<form id="ncc">
<table id="ncItems" name="ncItems" align="center">
<tr>
<th>Type</th>
<th>Discription</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr>
<td>
<select name="type[]" class="next" required>
<option value=" selected="selected"">Please Select..</option>
<option value="Code">Code</option>
<option value="Regular">Regular</option>
</select>
</td>
<input type="text" name="discription[]" class="next" required />
</td>
<td>
<input type="text" name="amount[]" class="next last" required readonly/>
</td>
<td>
<input type="button" name="addRow[]" class="add" value='+' />
<input type="button" name="addRow[]" class="removeRow" value='-' />
</td>
</tr>
<tr>
<th>Total :</th>
<td id="nctotalPrice"></td>
</tr>
</table>
</form>
</div>
Please try this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Final</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.add', function() {
var row = $(this).parents('tr');
var clone = row.clone();
// clear the values
var tr = clone.closest('tr');
tr.find('input[type=text]').val('');
$(this).closest('tr').after(clone);
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" + total +".00");
});
$(document).on("blur", ".last", function() {
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" +total+".00");
document.getElementById("ntotal").value ="$" +total+".00";
});
$(document).on('focus', ".last", function() {
var $qty = $(this).parents("tr").find("input[name^='quantity']");
var $pr = $(this).parents("tr").find("input[name^='price']");
var $amnt = $(this).parents("tr").find("input[name^='amount']");
var a = 0;
if ($qty.val() == '' || $pr.val() == '') {
console.log("No values found.");
return false;
} else {
console.log("Converting: ", $qty.val(), $pr.val());
var q = parseInt($qty.val());
var p = parseFloat($pr.val());
console.log("Values found: ", q, p);
}
a = q * p;
$amnt.val(Math.round(a * 100) / 100);
});
$(document).on('click', '.removeRow', function() {
if ($('#ncItems .add').length > 1) {
$(this).closest('tr').remove();
}
});
});
</script>
</head>
<body>
<div id="dvncc">
<form id="ncc">
<table id="ncItems" name="ncItems" align="center">
<tr>
<th>Type</th>
<th>Discription</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr>
<td>
<select name="type" class="next" required>
<option value="" selected="selected">Please Select..</option>
<option value="Code">Code</option>
<option value="Regular">Regular</option>
</select>
</td>
<td>
<input type="text" name="discription" class="next" required />
</td>
<td>
<input type="text" name="amount" class="next last" required/>
</td>
<td>
<input type="button" name="addRow" class="add" value='+' />
<input type="button" name="remove" class="removeRow" value='-' />
</td>
</tr>
<tr>
<th>Total :</th>
<td id="nctotalPrice"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
jQuery(document).ready(function() {
// This button will increment the value
$('.qtyplus').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
//alert(fieldName);
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
if (!isNaN(currentVal)) {
$('input[name=' + fieldName + ']').val(currentVal + 1000);
} else {
$('input[name=' + fieldName + ']').val(1000);
}
});
});
function buttonClick() {
//alert("hi");
var n = document.getElementById('rs').value;
alert(n);
var i = 50;
if (i == 50) {
alert(i);
var n = +n + +i;
alert(n);
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<h3> Calculator</h3>
<table style="width: 30%;">
<form name="calc" action="" method="post">
<tr>
</tr>
<tr>
<td>quantity:</td>
<td><input type="text" name="value1" /></td>
</tr>
<tr>
<td>price:</td>
<td>
<input type='text' name='quantity' value='2000' class='qty' />
<input type='button' value='+' class='qtyplus' field='quantity' onclick="buttonClick()" />
</td>
</tr>
<tr>
<td>discount:</td>
<td><input type='text' name='rs' value='500' field='rs' id='rs' class='counter' onclick="buttonClick()" /></td>
</tr>
<tr>
</tr>
</form>
</table>
In above HTML code, when button is clicked, I have to increment the two text box values
For example, click a button, price text box value will be 3000, discount text box value will be 550
price text box value is incremented, but discount value will not be changed.
Second script are run,but the text box value are not changed.
You just forget to change the value of the discount input.
<script type="text/javascript">//second script
function buttonClick() {
//alert("hi");
var n = document.getElementById('rs').value;
alert(n);
var i = 50;
if (i == 50) {
alert(i);
var n = +n + +i;
alert(n);
$("#rs").val(n) // add this line
}
}
</script>
You have not written anything to change value of discount textbox.
you can do as follows:
$('.qtyplus').click(function (e) {
e.preventDefault();
qty = $('.qty').val();
discount = $('#rs').val();
var currentQtyVal = parseInt(qty);
if (!isNaN(currentQtyVal)) {
$('input[name=quantity]').val(currentQtyVal + 1000);
} else {
$('input[name=quantity]').val(1000);
}
var currentDiscountVal = parseInt(discount);
if (!isNaN(currentDiscountVal)) {
$('input[name=rs]').val(currentDiscountVal + 50);
} else {
$('input[name=rs]').val(50);
}
});
How can i add prevent-default() with focus-out() in my form. I face problem when i click the reset button in my form. It show the last focusing input field error message when i click the reset button. Here my code bellow:
$(document).ready(function(){
//error message section:
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
//username validation area:
function checkUsername(){
var name = $("#username").val();
var usernameLength = $("#username").val().length;
if(!name.replace(/\s/g, '').length){
$("#username_error_msg").html("<span class='errorMessage'>Username shouldn't be empty..!</span>").slideDown(500);
}else if(usernameLength < 5 || usernameLength > 20){
$("#username_error_msg").html("<span class='errorMessage'>Username should be between 5-20 characters..!</span>").slideDown(500);
}else{
$("#username_error_msg").slideUp(500);
return true;
}
}
//Gender selection check:
function checkGenderSelection(){
var genderCategory = $('select[name=Gender]').val();
if(genderCategory == 'Select'){
$("#gender_Select_error_msg").html("<span class='errorMessage'>Please select your gender..!</span>").slideDown(500);
}else if((genderCategory == 'Male') || (genderCategory == 'Female')){
$("#gender_Select_error_msg").slideUp(500);
return true;
}
}
//job category check: radiobutton
function checkJobCategorySelection(){
var jobCategory = $('input[name=jobCategory]:checked');
if(jobCategory.length == 0){
$("#jobCategory_error_msg").html("<span class='errorMessage'>No Category Selected..!</span>").slideDown(500);
}else{
$("#jobCategory_error_msg").slideUp(500);
return true;
//By this way we can collect the value from radio button for further action//
//console.log("Selected Item: " + jobCategory.val());
}
}
//programming Experience check: checkbox
function programmingExperienceCheck(){
var experienceList = $('input:checkbox[name=language]:checked');
if(experienceList.length == 0){
$("#experience_sector_error_msg").html("<span class='errorMessage'>No Sector Selected..!</span>").slideDown(500);
}else{
$("#experience_sector_error_msg").slideUp(500);
return true;
}
}
//password validation area:
function checkPassword(){
var pass = $("#password").val();
var passwordLength = $("#password").val().length;
if(!pass.replace(/\s/g, '').length){
$("#password_error_msg").html("<span class='errorMessage'>Please type your password..!</span>").slideDown(500);
}else if(passwordLength < 8){
$("#password_error_msg").html("<span class='errorMessage'>Password should be minimum 8 characters..!<span class='errorMessage'>").slideDown(500);
}else{
$("#password_error_msg").slideUp(500);
return true;
}
}
//retype password validation area:
function checkRetypePassword(){
var pass = $("#password").val();
var retypePass = $("#retype_password").val();
if(!retypePass.replace(/\s/g, '').length){
$("#retype_password_error_msg").html("<span class='errorMessage'>Please give your password again..!</span>").slideDown(500);
}
else if(pass !== retypePass){
$("#retype_password_error_msg").html("<span class='errorMessage'>Password don't match..!</span>").slideDown(500);
}else{
$("#retype_password_error_msg").slideUp(500);
return true;
}
}
//email validation area:
function checkEmail(){
var regularExp = new RegExp(/([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})/);
if(!$("#email").val().replace(/\s/g, '').length){
$("#email_error_msg").html("<span class='errorMessage'>Please give your email id..!</span>").slideDown(500);
}
else if(regularExp.test($("#email").val())){
$("#email_error_msg").slideUp(500);
return true;
}else{
$("#email_error_msg").html("<span class='errorMessage'>Invalid Email..!</span>").slideDown(500);
}
}
//phone number validation area:
function checkPhoneNumber(){
var phone_number = $("#phoneNo").val();
var regularExp = new RegExp(/^(?:\+?88)?01[15-9]\d{8}$/);
if(!phone_number.replace(/\s/g, '').length){
$("#phone_no_error_msg").html("<span class='errorMessage'>Please enter a phone number..!</span>").slideDown(500);
}else if(regularExp.test($("#phoneNo").val())){
$("#phone_no_error_msg").slideUp(500);
return true;
}else{
$("#phone_no_error_msg").html("<span class='errorMessage'>Invalid phone number..!</span>").slideDown(500);
}
}
//short notes validation area:
function checkShortNotes(){
var shortNotes = $("#short_note").val();
var shortNotesLength = $("#short_note").val().length;
if(!shortNotes.replace(/\s/g, '').length){
$("#short_note_error_msg").html("<span class='errorMessage'>You have to write something about you..!</span>").slideDown(500);
}else if(shortNotesLength < 10){
$("#short_note_error_msg").html("<span class='errorMessage'>Your notes is too short..!</span>").slideDown(500);
}else{
$("#short_note_error_msg").slideUp(500);
return true;
}
}
//username focus action:
$("#username").focusout(function(){
if($('input[type=reset]').data('clicked',false)){
checkUsername();
}
});
//gender focus action:
$("#gender").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkGenderSelection();
}
});
//password focus action:
$("#password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPassword();
}
});
//retypePassword focus action:
$("#retype_password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkRetypePassword();
}
});
//email focus action:
$("#email").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkEmail();
}
});
//phone number focus action:
$("#phoneNo").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPhoneNumber();
}
});
//shortNotes focus action:
$("#short_note").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkShortNotes();
}
});
//form submit action:
$("#myForm").submit(function(){
if(checkUsername() && checkGenderSelection() && checkJobCategorySelection() && programmingExperienceCheck() && checkPassword() && checkRetypePassword() && checkEmail() && checkPhoneNumber() && checkShortNotes()){
return true;
}
else{
return false;
}
});
});
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
});
.errorMessage{background-color: darkcyan;color:white; border-radius:2px;font-size: 15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="msg.php" method="post">
<table>
<tr>
<td>Username: </td>
<td><input type="text" id="username"></td>
<td><span id="username_error_msg"></span></td>
</tr>
<tr>
<td>Select Your Gender: </td>
<td>
<select name="Gender" id="gender">
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
<td><span id="gender_Select_error_msg"></span></td>
</tr>
<tr>
<td>Select Job Category: </td>
<td>
<input type="radio" name="jobCategory" value="Part Time"/> Part Time
<input type="radio" name="jobCategory" value="Full Time"/> Full Time
<input type="radio" name="jobCategory" value="Intern"/> Intern
</td>
<td><span id="jobCategory_error_msg"></span></td>
</tr>
<tr>
<td>Select Experience Sector:</td>
<td>
<input type="checkbox" name="language"/> Javascript
<input type="checkbox" name="language"/> PHP
<input type="checkbox" name="language"/> Jquery
</td>
<td><span id="experience_sector_error_msg"></span></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" id="password"></td>
<td><span id="password_error_msg"></span></td>
</tr>
<tr>
<td>Retype Password: </td>
<td><input type="password" id="retype_password"></td>
<td><span id="retype_password_error_msg"></span></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" id="email"></td>
<td><span id="email_error_msg"></span></td>
</tr>
<tr>
<td>Phone No: </td>
<td><input type="text" id="phoneNo"></td>
<td><span id="phone_no_error_msg"></span></td>
</tr>
<tr>
<td>Short Note About You: </td>
<td><textarea id="short_note" cols="22" rows="5"></textarea></td>
<td><span id="short_note_error_msg"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit"/>
<input type="reset" value="Refresh"/>
</td>
<td></td>
</tr>
</table>
</form>
});
How can i stop to seeing any focus-out() action when i click reset button????
When you reset the form, you are hiding all the error messages. Then focus on the first element - username.
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
$('#username').focus();
});
Blur comes before click so you are setting the .html of the error, then the click comes and you hide it but because you use .slide jQuery will then set it visible again as it's sliding in.
The simplest way would be to set the html of the error to an empty string, jQuery can then slide in an empty string:
function removeErrors(){
$("#username_error_msg").html("");
$("#gender_Select_error_msg").html("");
$("#jobCategory_error_msg").html("");
$("#experience_sector_error_msg").html("");
$("#password_error_msg").html("");
$("#retype_password_error_msg").html("");
$("#email_error_msg").html("");
$("#phone_no_error_msg").html("");
$("#short_note_error_msg").html("");
}
//refresh button action:
$('input[type=reset]').click(function(){
removeErrors();
});
i want to show the error messages next to the input element and if there's no error messages then send the data to the server (clear data from form) so fire the function on submit
http://codepen.io/anon/pen/RPNpNw
the problem is the error messages showed and disappeared quickly (blink)
but when change the input type to button
http://codepen.io/anon/pen/EjaZqe
will work but the data will be still in form and not cleared as input type="submit" will do
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<form>
<table style="width:50%;">
<tr>
<td>first name</td>
<td><input type="text" id="txtfname" /></td>
<td><span id="error"></span></td>
</tr>
<tr>
<td>age</td>
<td><input type="number" id="txtage" onblur="checkAge(txtage)" /></td>
<td><span id="errorage"></span></td>
</tr>
<tr>
<td>user name</td>
<td><input type="text" id="txtuser" /></td>
<td><span id="erroruser"></span></td>
</tr>
<tr>
<td>country</td>
<td>
<select onselect="checkSelect(this)" id="slct">
<option selected="selected" value="default">select your country</option>
<option>egypt</option>
<option>usa</option>
</select>
</td>
<td><span id="errorslct"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
</table>
</form>
<script>
function allvalidate() {
validate();
checkAge(txtage);
checkuser(txtuser);
checkSelect(this);
}
function validate() {
var txtf = document.getElementById('txtfname');
if (txtf.value == 0 || txtf.value == null) {
document.getElementById('error').innerText = ('you must enter firstname');
document.getElementById('error').style.color = 'red';
txtf.focus();
return false;
}
else {
document.getElementById('error').innerText = ('');
//return true;
}
}
function checkAge(input) {
if (input.value < 18 || input.value > 70) {
document.getElementById('errorage').innerText = ('age must be from 18 :70');
document.getElementById('errorage').style.color = 'red';
return false;
}
else {
document.getElementById('errorage').innerText = ('');
return true;
}
}
function checkuser(input) {
var pattern = '^[a-zA-Z]+$';
if (input.value.match(pattern)) {
document.getElementById('erroruser').innerText = '';
return true;
}
else {
document.getElementById('erroruser').innerText = ('enter valid email');
document.getElementById('erroruser').style.color = 'red';
return false;
}
}
function checkSelect() {
var select=document.getElementById('slct')
if (select.value=='default') {
document.getElementById('errorslct').innerText = ('you must choose country');
document.getElementById('errorslct').style.color = 'red';
return false;
}
else {
document.getElementById('errorslct').innerText = '';
return true;
}
}
</script>
</body>
</html>
Change
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
To:
<td><input type="submit" value="register" onclick="return allvalidate()" /></td>
Otherwise the boolean value is discarded. You also need to change allvalidate to actually return false if one of the validations fail:
function allvalidate() {
var validated = true;
if (!validate()) validated = false;
if (!checkAge(txtage)) validated = false;
if (!checkuser(txtuser)) validated = false;
if (!checkSelect(this)) validated = false;
return validated;
}
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
well, I'm not expert but what I think is that data is not sending, you need to call the function on onsubmit event, instead of calling it on onclick event. It would send the data as well.
So this is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body{font-family:Arial, Helvetica, sans-serif;font-size:12px;}
table{width:700px;margin:auto;border:solid 5px #cccccc}
table th{border-right:solid 1px #cccccc;border-bottom:solid 1px #000000;padding:5px;}
table th:last-child{border-right:0px;}
table td{border-right:solid 1px #d0d7e5;border-bottom:solid 1px #d0d7e5;}
table td:last-child{border-right:0px;}
table tr:last-child td{border-bottom:0px;}
table td input{padding:5px 0px;margin:auto;white-space:nowrap;overflow:hidden;outline:none;border:solid 1px #ffffff;text-align:center;width:99%;}
table td input.green{background:#00b050;border:solid 1px #00b050;}
table td input.red{background:#ff0000;border:solid 1px #ff0000;}
table td.active input{border:dotted 1px #333333;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var row_template = "<tr><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td></tr>";
var active_row;
var active_col;
// Initialize cell width
//$("table td").each(function()
//{
//var width = $(this).width();
//$(this).find("input").width(width-2);
//});
//----------------------
// Set Focus of cell
$("table").on("focus", "tr td input", function()
{
var row_count = $("table tr").size()-1;
$("table td").removeClass();
active_col = $(this).closest("td").index()+1;
active_row = $(this).closest("tr").index();
$(this).parent().addClass("active");
$(this).val("");
if(active_row == row_count)
{
$("table").append(row_template);
}
});
//------------------
// Set Blue of cell
$("table").on("blur", "tr td input", function(e)
{
var value = $(this).val();
if(isNaN(value) || value == "")
{
value = 0;
}
$(this).val(parseFloat(value).toFixed(2));
format_cell(active_row, active_col);
});
//-----------------
// Enter key on cell
$("table").on("keydown", "tr td input", function(e)
{
var value = $(this).val();
if(e.keyCode == 13)
{
$(this).blur();
if(active_col == 2)
{
$("table tr").eq(active_row).find("td").eq(active_col).find("input").focus();
}
else if(active_col == 3)
{
$("table tr").eq(active_row+1).find("td").eq(active_col-2).find("input").focus();
}
return(false);
}
else
{
if(value.length == 2)
{
$(this).val(value+".");
}
}
});
//------------------
// Download data
$("#btn_download").click(function()
{
var json = "";
var movement;
var pdi;
var ndi;
json += "[";
json += '{"movement":"Movement","pdi":"PDI","ndi":"NDI"},';
$("table tr:gt(0)").each(function(r)
{
movement = $(this).find("td").eq(0).find("input").val();
pdi = $(this).find("td").eq(1).find("input").val();
ndi = $(this).find("td").eq(2).find("input").val();
movement = (movement==0?"0":movement);
pdi = (pdi==0?"0":pdi);
ndi = (ndi==0?"0":ndi);
if(r==0)
{
json += '{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
else
{
json += ',{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
});
json += "]";
var csv = json_to_csv(json);
window.open("data:text/csv;charset=utf-8," + escape(csv));
});
//--------------
});
function format_cell(row, col, pre_value)
{
var pre_value = $("table tr").eq(row-1).find("td").eq(col-1).find("input").val();
var value = $("table tr").eq(row).find("td").eq(col-1).find("input").val();
if(col == 3)
{
if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
else
{
if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
calculate_grid();
}
function calculate_grid()
{
$("table tr:gt(0)").each(function(r)
{
var pdi = $(this).find("td").eq(1).find("input").val();
var ndi = $(this).find("td").eq(2).find("input").val();
var movement = (parseFloat(pdi) - parseFloat(ndi)).toFixed(2);
r=r+1;
$(this).find("td").eq(0).find("input").val(movement);
if(movement > 0)
{
$(this).find("td").eq(0).find("input").removeClass("red").addClass("green");
}
else if(movement < 0)
{
$(this).find("td").eq(0).find("input").removeClass("green").addClass("red");
}
else
{
$(this).find("td").eq(0).find("input").removeClass("green red");
}
});
}
function json_to_csv(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = "";
var line = "";
if($("#labels").is(':checked'))
{
var head = array[0];
if($("#quote").is(':checked'))
{
for(var index in array[0])
{
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[0])
{
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for(var i=0;i<array.length;i++)
{
var line = "";
if ($("#quote").is(':checked'))
{
for (var index in array[i])
{
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[i])
{
line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return(str);
}
</script>
<title>Excel</title>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="30%">Movement Data</th>
<th width="35%">PDI</th>
<th width="35%">NDI</th>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
</table>
<center><input type="button" id="btn_download" value="Download" /></center>
</body>
</html>
I want to change color in the movement cell according to the data. If the the current value is lower than the preceding value I want it to be red and if the current value is more than the preceding value than I want it to be green. I believe it requires a minor change in the "movement function"
Please help.
Here is a jsfiddle for the scenario: Click Here
Is this not what already happens. I have tested the jsfiddle (http://jsfiddle.net/4QBwK/), behaviour seems a little odd, but I think it fits what you have specified.
The only change I think is needed is to remove most of the code from the format_cell() function that seems to randomly light up cells in either red or green. I have commented it out on this jsfiddle: http://jsfiddle.net/4QBwK/1/
So you would just have this instead:
function format_cell(row, col, pre_value)
{
calculate_grid();
}