Hi friends in my coding i'm using getJSON method to auto fill the text box when the user types the code in one text box, the description of the particular code will be displayed on the other textbox. I'm using more than 20 textboxes in my coding so the getJSON method has to be called 20 times, so i'm typing the code for 20 times is there is any other alternate way to optimize the code my is below .
function getCodeDetails1() {
$.getJSON("ieCodedetails.jsp", {
codeid: $("#txtIEcode1").val()
}, displayResult1);
}
function displayResult(data) {
if (data.error) { // emp not found
$("#txtIEdesc1").val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$("#txtIEdesc1").val(data.name);
}
}
function getCodeDetails2() {
$.getJSON("ieCodedetails.jsp", {
codeid: $("#txtIEcode2").val()
}, displayResult2);
}
function displayResult2(data) {
if (data.error) { // emp not found
$("#txtIEdesc2").val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$("#txtIEdesc2").val(data.name);
}
}
function getCodeDetails3() {
$.getJSON("ieCodedetails.jsp", {
codeid: $("#txtIEcode3").val()
}, displayResult3);
}
function displayResult3(data) {
if (data.error) { // emp not found
$("#txtIEdesc3").val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$("#txtIEdesc3").val(data.name);
}
}
<td><input type="text" name="txtIEcode1" id="txtIEcode1" onchange="getCodeDetails1()" style="width:60px;"></td>
<td><input type="text" id="txtIEdesc1" name="txtIEdesc1" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode2" id="txtIEcode2" onchange="getCodeDetails2()" style="width:60px;"></td>
<td><input type="text" id="txtIEdesc2" name="txtIEdesc2" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode3" id="txtIEcode3" onchange="getCodeDetails3()" style="width:60px;"></td>
<td><input type="text" id="txtIEdesc3" name="txtIEdesc1" style="width:220px;" readonly></td>
You could try to link your logic to some class instead of multiple ids:
<td><input type="text" name="txtIEcode1" class="txtIEcode" style="width:60px;"></td>
<td><input type="text" name="txtIEdesc1" class="txtIEdesc" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode2" class="txtIEcode" style="width:60px;"></td>
<td><input type="text" name="txtIEdesc2" class="txtIEdesc" style="width:220px;" readonly></td>
<td><input type="text" name="txtIEcode3" class="txtIEcode" style="width:60px;"></td>
<td><input type="text" name="txtIEdesc3" class="txtIEdesc" style="width:220px;" readonly></td>
Then in your js:
$(".txtIEcode").each(function(i, el) {
var $el = $(el),
$desc = $el.parent().next('td').find(".txtIEdesc");
$el.on('change', function(){
$.getJSON("ieCodedetails.jsp", {
codeid: $el.val()
}, displayResult);
function displayResult(data) {
if (data.error) { // emp not found
$desc.val(""); // clear fields
alert(data.error);
}
else { // Found employee. Display details
$desc.val(data.name);
}
}
})
});
You have store the file name in variable and passed to arg
var pageName="ieCodedetails.jsp";
var textBoxId=$("#txtIEcode1");
getCodeDetails1(pageName,textBoxId);
function getCodeDetails1(pageName,textBoxId) {
$.getJSON(pageName, {
codeid: textBoxId.val()
}, displayResult1);
}
Related
I am trying to write a function to analyze the users input before calling Onkeyup. I am not sure where to write this if statement, or if I have the correct syntax. I wrote the if statement inside the asset-tag class. This is my code:
const getAssetInfo = (assetTag, index) => {
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
});
};
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input
class="asset-tag" id='asset_tag_no${count}' type='text'
if (input.length >= 4){
console.log('not enough characters to call API endpoint');
}
else{
onkeyup = "getAssetInfo(this.value,${count})";
}
bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required readonly/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required readonly description></textarea></td>
<td><input id='cost${count}' type='value' bottom require readonly/></td>
<td><input id='po_no${count}' type='text' bottom require readonly/></td>
<td><textarea id='remarks${count}' type='text' bottom remarks></textarea></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});
I want this error in the console log to only execute when a certain amount of characters are in the box instead of each time a character is inputted.
I created a discount function for my order page where I have an issue that is , on my order page by default when product quantity is 1 then discounted rate show correctly in Final textbox but when I change the Quantity, like 1 to 2,3,4,5.. then my code not works and the amount show without discount rate.
I try to fix this but I not understand where is mistake and how I fix that.
Below is my code which I am using please help and tell me how I make this correct.
Your help will be really appreciate.
Thank you!
function getTotal(row = null) {
if(row) {
var disc = $('#dis_1').val();//
var dec = (disc/100).toFixed(2); //
var total = Number($("#rate_value_"+row).val()) * Number($("#qty_"+row).val()) * dec;
//total = total.toFixed(2);
var rate = Number($("#rate_value_"+row))-total;
total = total.toFixed(2);
$("#amount_"+row).val(total);
$("#amount_value_"+row).val(total);
subAmount();
} else {
alert('no row !! please refresh the page');
}
}
//**---**/
//*---*//
// get the product information from the server
function getProductData(row_id)
{
var product_id = $("#product_"+row_id).val();
if(product_id == "") {
$("#rate_"+row_id).val("");
$("#rate_value_"+row_id).val("");
$("#qty_"+row_id).val("");
$("#amount_"+row_id).val("");
$("#amount_value_"+row_id).val("");
} else {
$.ajax({
url: base_url + 'orders/getProductValueById',
type: 'post',
data: {product_id : product_id},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#rate_"+row_id).val(response.price);
$("#rate_value_"+row_id).val(response.price);
$("#dis_"+row_id).val(response.discount);
$("#dis_value_"+row_id).val(response.discount);
$("#qty_"+row_id).val(1);
$("#qty_value_"+row_id).val(1);
//DISCOUNT
var disc = $('#dis_1').val();
var dec = (disc/100).toFixed(2);
var total = Number(response.price) * dec;
var rate = Number(response.price)-total;
total = rate.toFixed(2);
$("#amount_"+row_id).val(total);
$("#amount_value_"+row_id).val(total);
subAmount();
} // /success
}); // /ajax function to fetch the product data
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
<td>
<input type="text" name="rate[]" id="rate_1" class="form-control" autocomplete="off" placeholder="Rate">
</td>
<td>
<input type="text" placeholder="Discount" name="dis[]" id="dis_1" class="form-control" autocomplete="off">
</td>
<td>
<input type="text" placeholder="Total Price" name="amount[]" id="amount_1" class="form-control" autocomplete="off">
</td>
I am using my database to fetch the amount like product real rate, discounts.
In your line of HTML
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
you are always calling getTotal with a value of 1, I think you want to instead get the value of the text box when the getTotal function is called and use that as your row value. In jquery you can get the value of the box by
row = $("#qty").val()
I am newbie to Angular js.'this' operator will be helpful, but no idea how to use it.
On Each First Column, user will input the data, and corresponding that data should be fetched. Now data is fetched from php to Angular js, but how to push the data from angular js to that text box using "this" operator.
For eg: If 'Y' is entered then, X and Z should be push to textbox
If 'Q' is entered then, P and R should be push to textbox.
HTML:
<tr>
<td><input type="text" ng-model="bot.Wo_Id" /></td>
<td><input type="text" ng-click="acc1()" ng-value="b_code" /</td>
<td><input type="text" ng-value="Pre_req" /></td>
<td><a href ng-click="remove_bottle(bottle)">Remove</a></td>
</tr>
<tr>
<td><a href ng-click="add_bottle()">Add</a></td>
</tr>
Angular Js:
$scope.acc1 = function () {
$http.get("machin.php", {
params: {
"W_id": this.bot.Wo_Id,
"MC": "Machine"
}
})
.success(function (response) {
var values = response.split("#");
$scope.b_code = ?
$scope.Pre_req = ? // what should be code here
});
};
machin.php
echo X."#".Z //for input Y
echo P."#".R //for input Q
I am unable to sort this problem.Please help me.Thanks in advance.
This should do the trick:
Don't use this, use $scope.
Change ng-value to ng-model
HTML
<tr>
<td><input type="text" ng-model="bot.Wo_Id" /></td>
<td><input type="text" ng-click="acc1()" ng-model="b_code" /</td>
<td><input type="text" ng-model="Pre_req" /></td>
<td><a href ng-click="remove_bottle(bottle)">Remove</a></td>
</tr>
<tr>
<td><a href ng-click="add_bottle()">Add</a></td>
</tr>
Angular:
$scope.acc1 = function () {
$http.get("machin.php", {
params: {
"W_id": $scope.bot.Wo_Id,
"MC": "Machine"
}
})
.success(function (response) {
var values = response.split("#");
$scope.b_code = values[0];
$scope.Pre_req = values[1];
});
};
Here's a plunker with example. I can't do the http request so I just resolve the promise.
https://plnkr.co/edit/f6EzxBlaFInJghNwsXaU?p=preview
i wrote a program which converts lbs to kg, it works fine. how would i ask the user to enter the conversion. for example, i have the weight set at 0.4536, but if i wanted it to be whatever the user wants how do i do that? i know in reality it would not change, but i'm thinking about future programs - possibly currency conversions where the rates change and i want the user to enter it easily.
Javascript
function onlyNumber(fld) {
if(fld.value.match(/[^0-9.]/)) {
fld.value=fld.value.replace(/[^0-9.]/g,'');
}
}
function convertUnit(lbs, kilo) {
retValue = 0;
if (isNaN (kilo)) { alert ('Non-numeric value'); return 0; }
kilo = parseFloat (kilo);
var factor = 0.4536;
if (lbs == 'kg2lb') {
retValue = kilo/factor;
}
else if (lbs == 'lb2kg') {
retValue = kilo*factor;
}
return retValue;
}
HTML
<form>
<table>
<tr>
<td>LB<td>
<input type="text" name="lb" id="lb" onblur="this.form.kg.value=convertUnit('lb2kg',this.value);" onkeyup="onlyNumber(this);">
</tr>
<tr>
<td>KG<td>
<input type="text" name="kg" id="kg" onblur="this.form.lb.value=convertUnit('kg2lb',this.value);" onkeyup="onlyNumber(this);">
</tr>
</table>
</form>
Add another input field or prompt the user.
<form>
<table>
<tr>
<td>LB<td>
<input type="text" name="lb" id="lb" onblur="this.form.kg.value=convertUnit('lb2kg',this.value);" onkeyup="onlyNumber(this);">
</tr>
<tr>
<td>KG<td>
<input type="text" name="kg" id="kg" onblur="this.form.lb.value=convertUnit('kg2lb',this.value);" onkeyup="onlyNumber(this);">
</tr>
<tr>
<td>Ratio<td>
<input type="text" name="r" id="r" onkeyup="onlyNumber(this); window.ratio = this.value;">
</tr>
</table>
</form>
window.ratio = undefined;
function convertUnit(lbs, kilo) {
retValue = 0;
if (isNaN (kilo)) { alert ('Non-numeric value'); return 0; }
kilo = parseFloat (kilo);
if (lbs == 'kg2lb') {
retValue = kilo/window.ratio;
}
else if (lbs == 'lb2kg') {
retValue = kilo*window.ratio;
}
return retValue;
}
Or with a prompt
window.ratio = prompt("Which ratio to use ?"); // add validation
i want to make one common function in javascript for validation of my fields like name,city and state.
which can be also applicable for all three fields
1) Name
2) City
3) State
Here is the code of html
<form name="addcust" method="POST" action="insrtCustomer.php" id="form1">
<table>
<tr>
<td>Customer Name</td>
<td><input type="text" name="name" id="name"><label id="message"></label></td>
<td>City</td><td><input type="text" name="city" maxlength="25"></td>
</tr>
<tr>
<td>State</td><td><input type="text" name="state" maxlength="25"></td>
</tr>
</table>
I want to make one function which i can use it for real time validation and can be applicable for more than one form.
As all you guys know that all forms in website has different name. So how it can be used, Please give your ideas here to do this and you all knows this can be usefull for other guys aso. So please help
you can try this and customize accordingly | Demo
Just you have to pass the form (this) in validate function and it will check for all text boxes for empty, you can modify it according to your use
<form name="addcust" method="POST" action="insrtCustomer.php" id="form1" onsubmit="return validate(this)">
<table>
<tr>
<td>Customer Name</td>
<td><input type="text" name="name" id="name"><label id="message"></label></td>
<td>City</td><td><input type="text" name="city" maxlength="25"></td>
</tr>
<tr>
<td>State</td><td><input type="text" name="state" maxlength="25"></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
Javascript
function validate(dis)
{
var ele = dis.getElementsByTagName("input");
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute("type") == "text")
{
if(ele[i].value == "")
{
alert(ele[i].getAttribute('name')+" is required feild");
ele[i].focus();
return false;
}
}
// you can check for radio and checkboxes
//eg : if(ele[i].getAttribute("type") == "radio")
// {
// Your code here
// }
}
return true; // to prevent from form submission use false
}
If you want to check for special characters
function validate(dis)
{
var filter = /^[A-Za-z0-9]+$/;
var ele = dis.getElementsByTagName("input");
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute("type") == "text")
{
if(ele[i].value == "")
{
alert(ele[i].getAttribute('name')+" is required feild");
ele[i].focus();
return false;
}
else if(!filter.test(ele[i].value))
{
alert(ele[i].getAttribute('name')+" requires letters and numbers only");
ele[i].focus();
return false;
}else;
}
// you can check for radio and checkboxes
//eg : if(ele[i].getAttribute("type") == "radio")
// {
// Your code here
// }
}
return true; // to prevent from form submission use false
}
You can try this example JQuery Validation
Include your jquery validation file in html page after jquery file
$('#yourFormId').validate({
rules:{
name: {
required: true
},
city: {
required:true
},
state: {
required:true
}
},
messages: {
name:{
required: 'required msg'
},
city:{
required: 'required msg'
}, state:{
required: 'required msg'
}
},
submitHandler: function(form){
}
});
hope this will work...