how to disable input text on condition - javascript

i would want to disable some input text when a certain condition is met. one input text value will be used as a key of the condition. imagine having 6 input and 2 getting data from table and these getting data from table 1 to store condition value. i want a scenario like, if text2.value is 'test' then text3 and text 4 should be disable.
this is what i have done
am tagging js,jq and hmtl maybe one could provide an assistance
html
<input type="hidden" name="ttype[<?php echo $ix ?>]" value="<?php echo
$rowx['testtype']; ?>"/>
<td colspan="0"> Result <br>
<div>
<select name="negpos[<?php echo $ix ?>]" style='width:50px'>
<option selected value=''> Select One </option>
<option value='Pos'> Positive</option>
<option value='Neg'> Negative</option>
<option value='N/P'> Not Provided</option>
</select>
<span id="sresultInfo">
</span>
</div>
</td>
<td><input type="text" name="WBC[<?php echo $ix ?>]"size ="3" /></td>
<td><input type="text" name="HGB[<?php echo $ix ?>]"size ="3" /></td>
<td> <input type="text" name="RBC[<?php echo $ix ?>]" size ="3" value=""/></td>
<td><input type="text" name="Lymph[<?php echo $ix ?>]"size ="3"/></td>
<td><input type="text" name="MCV[<?php echo $ix ?>]" size ="3"/></td>
<td><input type="text" name="Gran[<?php echo $ix ?>]" size ="3"/></td>
<td> <input type="text" name="MCH[<?php echo $ix ?>]" size ="3"/> </td>
js
$(document).ready(function(){
var ttyp = document.getElementById("ttype").value ;
if (ttyp = "MPP" ){
document.getElementById('WBC').disabled = true;
document.getElementById('HBG').disabled = true;
document.getElementById('RBC').disabled = true;
} else {
document.getElementById('WBC').disabled = false;
document.getElementById('HGB').disabled = false;
document.getElementById('RBC').disabled = false;
}
});

You can do something similar to this. The disabletext represents the text to match to disable and disablefieldids is the list of comma seperated value which contain id of the field to disable.
$('input').on('change', function() {
var conditions = $(this).data();
var inputValue = $(this).val();
if(inputValue == conditions.disabletext) {
conditions.disablefieldids.split(",").map(function(id) {
$('#'+id).attr('disabled', 'disabled');
})
}else {
conditions.disablefieldids.split(",").map(function(id) {
$('#'+id).removeAttr('disabled');
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" data-disabletext="test" data-disablefieldids="HGB,RBC" name="WBC"size ="3" />
</td>
<td><input type="text" id="HGB" name="HGB"size ="3" /></td>
<td> <input type="text" id="RBC" name="RBC" size ="3" value=""/></td>
<td><input type="text" id="Lymph" name="Lymph"size ="3"/></td>
<td><input type="text" id="MCV" name="MCV" size ="3"/></td>
<td><input type="text" id="Gran" name="Gran" size ="3"/></td>
<td> <input type="text" id="MCH" name="MCH" size ="3"/> </td>
</tr>
</table>

Instead of storing disable text and fields to input attributes I would like create one general object so it will give us more usability,
const InputCondition = [
{"disabletext":"Test","disablefieldids":["HGB","RBC"]},
{"disabletext":"ABC","disablefieldids":["MCV","MCV"]}
];
here is the on keyup initialization (change as per your need)
$('#ttype').keyup(function () {
func_makeInputdisable($(this).val());
});
// you can call this onload // pass the text value in param.
function func_makeInputdisable(lookingForText) {
let matches = InputCondition.find(x =>
x.disabletext.toLowerCase() == lookingForText.trim().toLowerCase());
if (typeof (matches) != 'undefined') {
matches = matches.disablefieldids;
//Remove all the disable inputs if in need
$('.AllInputClass').removeAttr('disabled');
if (matches.length > 0) {
$.each(matches, (index, inputID) => {
let $ele = $(`#${inputID}`);
if (typeof ($ele) != 'undefined')
$ele.attr('disabled', 'disabled');
});
}
}
else {
$('.AllInputClass').removeAttr('disabled');
}
}
// To enable textbox just add the same class on each input and use like,
$('.AllInputClass').removeAttr('disabled'); placed in comment above function with class name "AllInputClass"

Related

calculate grand total with javascript

I don't know how to get Grand total value
grand total is sum of all total
here is the code
<?php
$con = mysqli_connect('localhost', 'root', '', 'a.karat');
if(isset($_POST['product_id']))
{
$prno=$_POST['prno'];
$i=1;
$sql = mysqli_query($con,"select * from detail_pr where prNo='$prno'");
while ($r = mysqli_fetch_array($sql)) {
echo
'<tr>
<td><input type="checkbox" name="check[]" id="check'.$i.'" value="'.$i.'"></td>
<td><label for="productCode"></label>
<input type="text" name="productCode'.$i.'" id="productCode'.$i.'" readonly value="'.$r["productCode"].'" size="12" ></td>
<td><label for="productName"></label>
<input type="text" name="productName'.$i.'" id="productName'.$i.'" readonly value="'.$r["productName"].'"size="35" ></td>
<td><label for="qty"></label>
<input type="number" onkeyup="calc(this);" name="qty'.$i.'" id="qty'.$i.'" readonly value="'.$r["qty"].'" size="8" ></td>
<td><input type="number" onkeyup="calc(this);" name="price'.$i.'" id="price'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
<td><input type="number" onkeyup="calc(this);" name="discount'.$i.'" id="discount'.$i.'" size="10" min="0" max="99" onchange="calc(this);"></td>
<td><input type="number" name="total'.$i.'" id="total'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
</tr>';
$i++;
}
}
?>
<table width="400" border="0" align="right">
<tr>
<th scope="row">Grand Total</th>
<td>:</td>
<td><input name="grandtotal" id="grandtotal" type="text"></td>
</tr>
</table>
<script>
function calc(id) {
var row = id.parentNode.parentNode;
var quant = row.cells[3].getElementsByTagName('input')[0].value;
var price = row.cells[4].getElementsByTagName('input')[0].value;
var disc = row.cells[5].getElementsByTagName('input')[0].value;
if (disc == null || disc == '') {
res = parseFloat(quant) * parseFloat(price);
} else {
var res = (parseFloat(quant) * parseFloat(price)) - (parseFloat(quant) * parseFloat(price) * (parseFloat(disc) / 100));
}
row.cells[6].getElementsByTagName('input')[0].value = res;
}
</script>
I have manage to calculate total per row
now I need your help to sum all total and put the value in the grandtotal textbox
I guess on every change of a value of one of your input elements in your form the grand total should be updated, right? I 'd place an event listener on the form tag to keep it simple.
<form id="your-form" method="post" action="">
<!-- All your other inputs here -->
<input type="text" name="grandtotal" id="grandtotal">
</form>
<script>
document.querySelector('#your-form').addEventListener('change', function( event ) {
if (event.target.id && event.target.id !== 'grandtotal') {
var allTotals = document.querySelectorAll('input[name^="total"]'),
allTotalSum = 0;
Array.prototype.forEach.call(allTotals, function( element ) {
if (element.value) {
allTotalSum += parseFloat(element.value);
}
});
document.querySelector('#grandtotal').value = allTotalSum;
}
});
</script>
So on every change of one of your input fields the sum is updated. This code is untested.

Adding to a value declared in another function

It is hard to explain, you can see a DEMO HERE
I have a products table that dynamically creates/deletes new lines of products. I also have a totals table that totals up the totals of each line together.
In that totals box, I have a travel box I want to add to the grand total, but the issue I am having is the travel input is outside the table that is totaling all the values. I can replace the total with a new total, but I can not seem to call the sub total, add the travel and output a grand total.
HTML
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
<td> </td>
</tr>
</tbody>
</table>
<div class="wei-add-service">Add Item</div>
<table class="wei-add-totals">
<tr>
<td width="50%">Sub Total</td>
<td width="50%" class="wie-add-subtotal"> </td>
</tr>
<tr class="alternate travel">
<td>Travel</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field travel" /></td>
</tr>
<tr>
<td>Taxes</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-total-taxes" id="wei-disabled" disabled/> </td>
</tr>
<tr class="alternate total">
<td>Total</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-grand-total" id="wei-disabled" disabled/></td>
</tr>
</table>
Javascript
var counter = 1;
var testArray = [ 2,3,4,5];
jQuery('a.wei-add-service-button').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" class="wei-add-field description ' + counter + '"/></td><td><input type="text" class="wei-add-field quantity ' + counter + '" /></td><td><input type="text" class="wei-add-field unit-price ' + counter + '"/></td><td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total ' + counter + '" id=""/></td><td>X</td></tr>');
jQuery('table.order-details').append(newRow);
});
jQuery('table.order-details').on('click','tr a',function(e){
e.preventDefault();
var table = $(this).closest('table');
jQuery(this).parents('tr').remove();
reCalculate.call( table );
});
jQuery('table.order-details').on("keyup", "tr", reCalculate);
function reCalculate() {
var grandTotal = 0;
jQuery(this).closest('table').find('tr').each(function() {
var row = jQuery(this);
var value = +jQuery( ".unit-price", row ).val();
var value2 = +jQuery( ".quantity", row ).val();
var total = value * value2;
grandTotal += total;
jQuery( ".wei-add-field.price-total", row ).val( '$' + total.toFixed(2) );
});
jQuery(".wie-add-subtotal").text( '$' + grandTotal.toFixed(2));
}
I don't think, given the task of creating this, I would have chosen to do it in the way you did.
However, using your existing code you can bind the Travel value on change, paste, or keyup and run a function on any of those actions. Within that function I have removed the special character ($) from ".wie-grand-total" using a regex and converted the value of ".wie-grand-total" to a float using parseFloat. I also converted the Travel value to a float using parseFloat. I then added them together and made the sum your new value for "wie-grand-total".
/* NEW SINCE COMMENTS */
//Add to your HTML New table
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
/* NEW SINCE COMMENTS*/
<td><input type="text" id="travelHid" value=""></td>
<td> </td>
</tr>
</tbody>
</table>
/* NEW SINCE COMMENTS */
$('#travelHid').hide();
var travelVal = 0;
function updateTravelVal(travelVal){
var travelVal = travelVal;
$('#travelHid').val(travelVal);
};
updateTravelVal();
$("#travelVis").bind("change paste keyup", function() {
var noChars = jQuery(".wie-grand-total").val().replace(/[^0-9.]/g, "");
var newTot = parseFloat(noChars) + parseFloat($(this).val());
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//added error checking
var checkError = jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//if the value that would go in input is NaN then use travelVal
//since there is no value in .wie-grand-total yet
if (typeof checkError !== "string") {
jQuery(".wie-grand-total").val( '$' + travelVal.toFixed(2))
} else if (typeof checkError === "string") {
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2))
}
/* NEW SINCE COMMENTS */
updateTravelVal(travelVal);
});
A fiddle for demonstration (now with hiddenVal per comment)
http://jsfiddle.net/chrislewispac/wed6eog0/3/
Only potential problems here are it only runs when you change, paste, or key up the value in #TravelVis.
/EXPLAINED SINCE COMMENTS/
It the html I added a td with input. Input id="travelHid". I then make that invisible by applying jQuery method .hide(). I then exposed travelVal to global scope an initiated it with a value of zero then created a function to update that value.
Within that function I set the value to the argument travelVal or to 0 if there are no args. I then immediately call it.
Then, I added a call to that function with the arg travelVal from our bind function to update it if a value is present.
And finally:
Just add a row to the table with preset value of Travel and Quant 1.
http://jsfiddle.net/chrislewispac/xntn7p5p/5/

Disabling a textbox if it has value and ignored this disabled value in addition and subtraction in javascript

I want to add id= lr1, lr2 & lr3 total will show in id=tlrr and subtract from id=totalAmt.
HTML CODE.
<tr>
<td width="125"><b>Receiving Quarantine </b></td>
<td>
<input type="textbox" name="rcv_quantity" class="tqty" id="totalAmt" value="<?php echo $row->rcv_quantity; ?>" /> </td>
</tr>
<tr>
<td width="125"><b>Lot Released-1 </b></td>
<td>
<input type="textbox" name="lot_rel1" id="lr1" class="lr" value="<?php echo $row->lot_rel1; ?>" /> </td>
</tr>
<tr>
<td width="125"><b>Lot Released-2 </b></td>
<td>
<input type="textbox" name="lot_rel2" id="lr2" class="lr" value="<?php echo $row->lot_rel2; ?>" /> </td>
</tr>
<tr>
<td width="125"><b>Lot Released-3 </b></td>
<td>
<input type="textbox" name="lot_rel3" id="lr3" class="lr" value="<?php echo $row->lot_rel3; ?>" /> </td>
</tr>
<tr>
<td width="125"><b>Total Lot Released </b></td>
<td>
<input type="textbox" name="total_lot_rel" id="tlrr" class="tlr" value="<?php echo $row->total_lot_rel; ?>" /> </td>
</tr>
Javascript for addition and subtraction:It works nice.
<script>
$(document).ready(function () {
$('.lr').val(0); // reset
$('.lr,#re').keyup(function () {
$('.tqty, #totalAmt').val(<?php echo $row->rcv_quantity; ?>);
$('.tlr,#tlrr').val(<?php echo $row->total_lot_rel; ?>);
// Loop through all inputs and re-calculate the total
var total = parseFloat(totalAmt.value);
var total_lr = parseFloat(tlrr.value);
$('.lr,#re').each(function () {
// the "+" before the variable makes sure it's a number instead of a string
// the "or 0" makes it 0 if it's empty, instead of "undefined"
var number = +$(this).val() || 0;
// console.log(number);
total -= +number; // adds up the numbers
decimal = parseFloat(total).toFixed(2);
// sets the total to 2 decimal places
});
//----------------------------
$('.lr').each(function () {
var number = +$(this).val() || 0;
total_lr += +number;
decimal1 = parseFloat(total_lr).toFixed(2); // sets the total to 2 decimal places
});
//--------------------------------
// Update the total
$('#totalAmt').val(decimal);
$('#tlrr').val(decimal1);
//$('#notRbl1').val(decimal);
});
});
</script>
But not disable those textbox which has value and these textbox also participate addition and subtraction.Javascript textbox disable
window.onload = function() {
if (document.getElementById("lr1").value != null) {
ddocument.getElementById('lr1')
.setAttribute('disabled', 'disabled');
}
else if (document.getElementById("lr2").value != null) {
ddocument.getElementById('lr2')
.setAttribute('disabled', 'disabled');
}
else if (document.getElementById("lr3").value != null) {
ddocument.getElementById('lr3')
.setAttribute('disabled', 'disabled');
}
}
I want this when lr1 is input it will subtract from totalAmt and and lr1 value show in tlrr. Then when I want to input lr2 then lr1 is disable and only lr2 subtract from totalAmt and it will add tlrr.

how can return array values if first element is null in php

I need to insert array values into database.But i can not insert array
values properly when first value of array is null.How can i fix my
problem
<form name=myform action="addcanteen.php" method=post>
<table><tr><td width="11%"> Date:</td><td width="89%"><input type="date" name="cdate" id="cdate"/></td></tr></table>
<table border="1" bgcolor="#F5F9C1">
<tr>
<!--<th>ID</th>-->
<th>Name</th>
<td><!--<input type="text" id="datepicker">-->
<input type="checkbox" id="selectall" name="chk[]"/></td>
<td align="center">coffee</td>
<td align="center">tea</td>
</tr>
<?php while($row=mysql_fetch_array($result))
{
?>
<tr>
<?php /*?><td><?php echo $row['emp_id'];?></td><?php */?>
<td><?php echo $row['emp_name'];?></td>
<td align="center"><input type="checkbox" class="name" name="chk1[]" value="<?php echo $row['emp_name'];?>"/></td>
<td><input type="text" name="coffee[]" id="coffee" value="" /></td>
<td><input type="text" name="tea[]" id="tea" value=""/></td>
</tr>
<?php } ?>
<tr>
<td>
</td>
<td>
</td>
<td align="center">
<input type="submit" class="button" name="submit" id="submit" value="submit"/>
</td>
</tr>
</table>
</form>
above is my form and this is my insertion code.I inserted entire value if it is not null.But if first one is null i can not insert into database
<?php
include(dbcon.php);
date_default_timezone_set('UTC');
$date=date("d");
$month=date("m");
$year=date("Y");
$fd=date("d-m-Y");
if(isset($_POST['submit']))
{
$cdate=$_POST['cdate'];
$checkbox1=$_POST['chk1'];
$tea=$_POST['tea'];
$coffee=$_POST['coffee'];
for ($i=0; $i<sizeof($checkbox1);$i++)
{
$query1="INSERT INTO canteen(name,coffee,tea,date)VALUES('".$checkbox1[$i]."','".$coffee[$i]."','".$tea[$i]."','$cdate')";
$sql1=mysql_query($query1);
}
}
header("location:canteen.php");
?>
This is my java script for the function select the check box
$(function () {
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.name').attr('checked', this.checked);
});
// if all checkbox are selected, then check the select all checkbox
// and viceversa
$(".name").click(function () {
if ($(".name").length == $(".name:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
maybe... try this:
for ($i=0; $i<sizeof($checkbox1);$i++)
{
if($checkbox1[$i] != null && $coffee[$i] != null && $tea[$i] != null) {
$query1="INSERT INTO canteen(name,coffee,tea,date)VALUES('".$checkbox1[$i]."','".$coffee[$i]."','".$tea[$i]."','$cdate')";
$sql1=mysql_query($query1);
}
}

How to get values of dynamically created input fields (Json)

input fields are created via jquery depend on user input
If user type Quantity : 5 then i m created 5 input fields
for example if user give Quantity = 3 then this is how the html created dynamically using Jquery
<tr id = "tr_1">
<td><input type="text" name="cont_no1" id="cont_no1" /><td>
<td><input type="text" name="cont_size1" id="cont_size1" /><td>
<td><input type="text" name="cont_type1" id="cont_type1" /><td>
</tr>
<tr id = "tr_2">
<td><input type="text" name="cont_no2" id="cont_no1" /><td>
<td><input type="text" name="cont_size2" id="cont_size2" /><td>
<td><input type="text" name="cont_type2" id="cont_type2" /><td>
</tr>
<tr id = "tr_3">
<td><input type="text" name="cont_no3" id="cont_no3" /><td>
<td><input type="text" name="cont_size3" id="cont_size3" /><td>
<td><input type="text" name="cont_type3" id="cont_type3" /><td>
</tr>
now i need to store all this input fields values in json.
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
i tried like this but its not working the please someone help me. ThankYou
for your refrence here is full code, var auto_tr value is aligned here(with enter) for your purpose .
$(document).ready(function(){
$( "#cont_qty" ).change(function()
{
var itemCount = 0;
$("#munna").empty();
var cont_qty = this.value;
for(var i=0 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'">
<td>
<input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value="">
</td>
<td>
<select class="input-mini" name="cont_size'+itemCount+'" id="cont_size'+itemCount+'">
<option>20</option>
<option>40</option>
<option>45</option>
</select>
</td>
<td>
<select class="input-mini" name="cont_type'+itemCount+'" id="cont_type'+itemCount+'">
<option>DV</option>
<option>HD</option>
<option>HC</option>
<option>OT</option>
<option>FR</option>
<option>HT</option>
<option>RF</option>
</select>
</td>
<td>
<select class="input-medium" name="cont_tonnage'+itemCount+'" id="cont_tonnage'+itemCount+'">
<option>24000 Kgs</option>
<option>27000 Kgs</option>
<option>30480 Kgs</option>
<option>Super Heavy Duty</option>
</select>
</td>
<td>
<input class="input-medium" type="text" id="cont_tare'+itemCount+'" name="cont_tare'+itemCount+'" value="">
</td>
<td>
<input class="input-medium" name="cont_netweight'+itemCount+'" id="cont_netweight'+itemCount+'" type="text" value="">
</td>
<td>
<input class="input-mini" name="yom'+itemCount+'" id="yom'+itemCount+'" type="text" value=""></td>
<td>
<select class="input-medium" name="cont_condition'+itemCount+'" id="cont_condition'+itemCount+'">
<option>IICL</option>
<option>ASIS</option>
<option>CARGO WORTHY</option>
</select>
</td>
</tr>';
$("#munna").append(auto_tr);
}
});
$("#getButtonValue").click(function ()
{
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty.value; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
alert(jsonObj[0].cont_no[1]);
});
});
did small loop mistake :)
for(var i=1; i<=cont_qty.value; i++)
{
alert(cont_qty.value);
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
in previous one i<cont_qty.value this one used now just changed as i<=cont_qty.value
so the loop ran 3 times when qty is 4. now just added <=
ThankYou for your answers friends
Make sure you call your function after you created the html via jquery.
createHtml(); // function to create the html
storeValuesToArray(); // Your function to store data to array
Also make sure you properly close your tags <tr></tr>. And put <tr> inside a <table> tag.
And make sure your cont_qty is set to a value
After you created the html and added all the fields necessary, you can catch all elements by using a selector like:
var jsonObj= jsonObj || [];
$('[name^="cont_no"]').each(function(){
var i = this.name.split('cont_no')[1];
var item = {};
item['cont_no'] = $(this).val();
item['cont_size'] = $('[name="cont_size'+i+'"]').val();
item['cont_type'] = $('[name="cont_type'+i+'"]').val();
jsonObj.push(item);
});

Categories

Resources