How to increment the two text box values when button is clicked? - javascript

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

Related

I want to combine 2 different java scripts

I have 2 java script codes, one work as a search suggestion and second is for adding another form fields dynamically and this second script also calculate values given in input fields, but both scripts have this 'ADD MORE PRODUCT' feature. What i want is; i want to combine both 'ADD more" feature, because 1st script works on id="" tag to identify field to show search result but second script not do it.
Fetching details in first row is successful, but when i click ADD more button populated by second script, it does not work
//Script to fetch details based on search box :
$(document).ready(function() {
$(document).on('keydown', '.prname', function() {
var id = this.id;
var splitid1 = id.split('_');
var index1 = splitid1[1];
$('#' + id).autocomplete({
source: function(request, response) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,
request: 3
},
success: function(data) {
response(data);
}
});
},
select: function(event, ui) {
$(this).val(ui.item.label); // display the selected text
var prid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {
prid: prid,
request: 4
},
dataType: 'json',
success: function(response) {
var len = response.length;
if (len > 0) {
var id = response[0]['id'];
var fprice = response[0]['fprice'];
var packing = response[0]['packing'];
var pweight = response[0]['pweight'];
document.getElementById('fprice_' + index1).value = fprice;
document.getElementById('packing_' + index1).value = packing;
document.getElementById('pweight_' + index1).value = pweight;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function() {
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='name' id='name_" + index + "' placeholder='Enter name'></td><td><input type='text' class='phone' id='phone_" + index + "' ></td><td><input type='text' class='address' id='address_" + index + "' ></td><td><input type='text' class='custid' id='custid_" + index + "' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
// Second script to do calculation :
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
b = i - 1;
$('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
calc();
});
$('#tab_logic tbody').on('keyup change', function() {
calc();
});
$('#tax').on('keyup change', function() {
calc_total();
});
});
function calc() {
$('#tab_logic tbody tr').each(function(i, element) {
var html = $(this).html();
if (html != '') {
var qty = $(this).find('.qty').val();
var price = $(this).find('.fprice').val();
var discount = $(this).find('.discount').val();
$(this).find('.total').val((qty * price) - discount);
calc_total();
}
});
}
function calc_total() {
total = 0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('#sub_total').val(total.toFixed(2));
tax_sum = total / 100 * $('#tax').val();
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum + total).toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table class="table table-bordered table-hover" style='border-collapse: collapse;' id="tab_logic">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center"> Product </th>
<th width="190px" class="text-center"> Price </th>
<th width="30px" class="text-center"> Price for </th>
<th width="100px" class="text-center"> Packing </th>
<th width="80px" class="text-center"> Qty </th>
<th width="100px" class="text-center"> Discount </th>
<th width="150px" class="text-center"> Total </th>
</tr>
</thead>
<tbody>
<tr class='tr_input' id='addr0'>
<td>1</td>
<td><input type="text" name='product[]' id="prname_1" class="prname form-control" /></td>
<td>
<input type="number" name='price[]' id='fprice_1' class="form-control fprice price" step="0.00" min="0" />
</td>
<td><input style="width:70px" type="text" class="pweight input-group-text" id="pweight_1"></td>
<td><input type="text" name='pack[]' class="form-control packing" id='packing_1' step="0" min="0" /></td>
<td><input type="text" name='qty[]' class="form-control qty" id="qty_1" step="0" min="0" /></td>
<td><input type="text" name='discount[]' class="form-control discount" id="discount_1" step="0.00" min="0" /></td>
<td><input type="number" name='total[]' class="form-control total" id="total_1" readonly/></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>

Search box for table

Given this table:
<table class="tbllist searchtbl" cellpadding=2 cellspacing=0 style="width: 70%">
<tr>
<th class="hidden">ID</th>
<th>Number Plate</th>
<th>Chassis Number</th>
<th>Trailer Make</th>
<th>Year</th>
<th>Axles</th>
<th></th>
</tr>
<tr class='tbl'>
<td class='hidden'>3</td>
<td>
<input type=text style = 'width: 75px' class='centered' id='trnumberplate_3' name='trnumberplate_3' value='T212ABS' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trnumberplate", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trchassisnumber_3' name='trchassisnumber_3' value='AJSDGASJH' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trchassisnumber", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trmake_3' name='trmake_3' value='LOW LOADER' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trmake", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 50px' class='centered' id='tryear_3' name='tryear_3' value='2009' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","tryear", this.value ,"trid","3","1","",this, "false")'>
</td>
<td>
<input type=text style = 'width: 25px' class='centered' id='traxles_3' name='traxles_3' value='3' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","traxles", this.value ,"trid","3","1","",this, "false")'>
</td>
<td class='delbtn'>
<button id='trailers_3' title='DELETE THIS ITEM (3)?' onclick='event.preventDefault(); delitem("trailers","trid","3","trailers.php","#workspace")'><img src='/icons/delete.png' ></button>
</td>
</tr>
</table>
I have the following search function:
function searchbox() {
// text input search for tables (such as trip history etc)
$("#search").keyup(function () {
//split the current value of searchInput
var data = this.value.toUpperCase().split(" ");
//create a jquery object of the rows
var jo = $(".tbllist").find("tr").not("tr:first"); // exclude headers
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
})
It will loop through table td's to check if the searched value is available and filter rows. It is not filtering if the td contains an input text element with the searched value.
Update:
if ($t.find("input").val().toUpperCase().indexOf(data[d]) > 0) {
return true;
}
Now works but will only matches the first column of the table.
JSFiddle: https://jsfiddle.net/fabriziomazzoni79/30d52c9z/
Change jo.filter() like this:
jo.filter(function (i, v) {
var txt = '';
$(v).find("input").each(function(n,e){
txt += e.value;
});
for(var d=0; d<data.length; d++){
if (txt.search(data[d])>=0) {
return true;
}
}
return false;
})
Fiddle here.

Minor change required with this Javascript Code

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

Trouble taking two user chosen inputs and doing calculation

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>

jQuery put content of textbox inside a div

This is the html markup
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js">
</script>
<style type="text/css">
div{ padding:4px; }
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(
function() {
var counter = 2;
$('a.add').live('click', function() {
if (counter > 5) {
alert("Only 5 textboxes allowed");
return false;
}
var newRow =
$(this).closest('tr').clone().appendTo('#gridInAnswers').find('input').val('');
var i = 0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
$(this).text('Remove').removeClass('add').addClass('remove');
counter++;
});
$('a.remove').live('click', function() {
$(this).closest('tr').remove();
counter--;
var i=0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
});
$("#getButtonValue").click(function() {
var test='';
for(var i=0;i<5;i++){
var minValue = $('#Col'+(i++)).val().trim();
var maxValue = $('#Col'+i).val().trim();
if((minValue=='' && maxValue !='')||(minValue!='' && maxValue !='' && minValue > maxValue)){
alert('Alerting...');
}
}
var gridInAnswerValuesHtml = "";
$(".grdAns").each(function() {
//ansString += this.value+",";
gridInAnswerValuesHtml += "<input type = \"hidden\" name = \"gridInAnswers\" value = \"";
gridInAnswerValuesHtml += this.value;
gridInAnswerValuesHtml += "\">";
});
alert(gridInAnswerValuesHtml);
});
});
</script>
</head>
<body>
<div id="blankDiv"></div>
<table id="gridInAnswers">
<tr>
<th>
Min Value
</th>
<th>
Max Value
</th>
</tr>
<tr>
<td>
<input type="text" name="col1" id="Col0" class="grdAns" />
</td>
<td>
<input type="text" name="col1" id="Col1" class="grdAns" />
</td>
<td>
Add
</td>
</tr>
<tr>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</tr>
</table>
</body>
on click of the add button I want to remove the textbox but its contents should get displayed say inside a div. i.e. I want to stop user from modifying this but disabling the textbox is not an option. How do I achieve this ?
Basically what you need to do is to do the replacement as soon as you click on the add link. The replacement is really simple.
// Do the magic here (Kuroir)
$(this).parent().parent().find('input').each(function(){
$(this).replaceWith('<div class="inactive">' + $(this).val() + '</div>');
});
Basically, you're going back to the tr level, then finding the input and doing the replacement for that row.
Working Solution: http://jsfiddle.net/kuroir/SXppg/
To get content from an <input> and place it in a <div>, you want something like:
$('#target-div-id').text(
$('#Col0').val()
);
I'm reasonably sure that's what you're trying to do.

Categories