User Input not found in Database error message - javascript

I am trying to set up an error message for the console to print when the user inputs a value not found in the database. I believe the syntax should be printed within the .fail(() => { section. I know my logic should be; if assetTag is not in the database, console.log an error message. The issue I have is it still prints the GET request with each valued typed. I believe the Onkeyup is also an issue. Here is a screenshot of the console:
How can I get the error message to always display Unable to locate ID in database once the user inputs the first key until something valid is found, eliminating the numerous GET requests? Here is my Javascript:
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(() => {
if (`#asset_tag_no` != assetTag ){
console.log('Unable to locate ID in database');
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
}
// });
else {
console.log('not enough characters to call API endpoint');
};
});
};
$('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'
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++;
});

Related

How to create a function for Onkeyup

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.

Onkeyup to fire a get request after only a few charcters

I am using Onkeyup to fire when a user inputs a certain ID into the search box. One problem I am trying to fix is having the function run only after 4 or more characters are in the submission box. For example, the ID number 0949 is fired when the user types out each digit, returning a GET request error each time when it should only fire at the end of the 4 digit submission. Here is a screenshot from the console log:
Ive tried including a .length to my onkeyup function as well as a fail catch to try but nothing works and it still fires after every single input. Here is my JavaScript 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'
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++;
});
What is the most optimal way to ensure that only 4 or more digits can be entered into the search box, before it sends a GET request?
You should be able to wrap your getAssetInfo function with an if statement checking the amount of characters in the searchbar. Try rewriting the getAssetInfo function like this:
const getAssetInfo = (assetTag, index) => {
if (assetTag.length >= 4){
// 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("");
});
} else {
console.log('not enough characters to call API endpoint');
}
};
In this if statement, I'm checking if the search bar has 4 or more characters before making the API call.

jquery: how to update input value using onchange?

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

Retrieving values from input elements in a table in HTML

I have a table set up as such:
<table id="mantab" style="cursor:pointer;" onkeypress="scan(event)">
<tr>
<td><input type='text' placeholder="Term" id='inp1' class="inp1" /></td>
<td><input type='text' placeholder="Definition" id='inp2' class="inp2" /></td>
</tr>
</table>
An action can be taken to add a row to this table, which is done by inserting a cell via the insertCell method and setting that cell's innerHTML appropriately.
What I've been trying to do is iterate through the first column of the table and add up all the values from inputs in each cell (after they've been entered) in a comma separated string. This process should be repeated for the second column.
The problem:
Everything I attempt to read is undefined
I've tried the following approaches to retrieving the contents of a cell:
document.getElementById("id").value,
document.getElementByClassName("classname").value,
table.rows[0].cells[0].value,
table.rows[0].cells[0].val(),
table.rows[0].cells[0].innerHTML,
table.rows[0].cells[0].children[0].val()
None work, some return blank, most undefined. The innerHTML one returns the input element inside the cell, but there is no actual text input data.
If a clearer picture of what I'm looking at is needed, see the following:
This should return one variable containing a string: "KeyA,KeyB,KeyC" and another with: "ValueA,ValueB,ValueC"
I'm somewhat new to javascript, but I have a basic knowledge of a couple other languages. I'm not sure why iterating through a table is posing such a challenge. Any help clarifying how I can extract these "invisible" values would be appreciated. Thanks.
Here is one of many approaches that isn't working for me:
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(j == 0) { //if first column
words += col.getElementsByClassName("inp1").value + ","; //inp1 refers to first column input class name
} else {
defs += col.getElementsByClassName("inp2").value + ","; //inp2 refers to second column input class name
}
}
}
In this example, words is analagous to the first variable from the image above, and defs to the second.
Update: logging the values and the element responsible for providing the values resulted in this:
The first log is blank, and the second has no value assigned, even though I typed in something.
You can do something like this using jQuery selectors
$("#bt").click(function()
{
var keys = [], values = [];
$('table tr input').each(function(i,e){
//access the input's value like this:
var $e = $(e);
if($e.hasClass('key')){
keys.push($e.val());
}else{
values.push($e.val());
}
});
keys = keys.join(',');
values = values.join(',');
console.log(keys);
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mantab" style="cursor:pointer;">
<tr>
<td><input type='text' placeholder="Term" id='inp1' class="key" /></td>
<td><input type='text' placeholder="Definition" id='inp2' class="value" /></td>
</tr>
<tr>
<td><input type='text' placeholder="Term" id='inp1' class="key" /></td>
<td><input type='text' placeholder="Definition" id='inp2' class="value" /></td>
</tr>
</table>
<button id="bt">
Get Value
</button>
what about using jQuery and finding all inputs in a table:
$('table input').each(function(i,e){
//access the input's value like this:
console.log($(e).val());
});

Change value of disabled checkbox

So I've run across a little snag. I have a page where I have a checkbox being displayed but is disabled (the user can't change it's value due that it's DB driven). Below this checkbox, I have an autocomplete field. Should an item from the autocomplete come back, I need to be able to toggle the value of the disabled checkbox. However, I'm unable to do so at this moment.
Here is my code so far.
View
...
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.IsSpecialOrder):
</td>
<td class="adminData">
#Html.DisplayFor(model => model.IsSpecialOrder)
#Html.HiddenFor(model => model.IsSpecialOrder)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.ItemNumber):
</td>
<td class="adminData">
#if (Model.Id > 0)
{
#Html.DisplayFor(model => model.ItemNumber)
}
else
{
#Html.EditorFor(model => model.ItemNumber)
}
</td>
</tr>
...
<script type="text/javascript">
...
$("#ItemNumber").autocomplete({
minLength: 2,
source: function (request, response) {
var itemNumber = $("#ItemNumber").val();
//Get available Products based on search parameter and map data
$.getJSON('#Url.Action("GetProductsByItemNumber", "PurchaseOrder")', { searchProduct: itemNumber }, function (data) {
for (var i = 0; i < data.length; i++) {
productData.push({ 'Id': data[i].Id, 'Name': data[i].Name, 'ItemNumber': data[i].ItemNumber, 'Description': data[i].Description,
'IsSpecialOrder': data[i].IsSpecialOrder
});
}
response($.map(data, function (item) {
return {
value: item.ItemNumber,
id: item.Id
};
}));
})
},
select: function (event, ui) {
if (ui.item.id == 0) {
//Do some house cleaning and alert user to mistake
alert("You must retry your search for a Product");
$("#Name").val("");
$("#ItemNumber").val("");
$(".ProductDescription").html("");
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").checked = false;
//$("#IsSpecialOrder").prop("checked", false);
return false;
}
//Record ProductId
$("#ProductId").val(ui.item.id);
//Fill RequestorExt with correct data
var description = GetData(productData, ui.item.id, "desc");
var name = GetData(productData, ui.item.id, "name");
var isSpecialOrder = GetData(productData, ui.item.id, "is");
$(".ProductDescription").html(description);
$("#Name").val(name);
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").checked = isSpecialOrder;
//$("#IsSpecialOrder").prop("checked", isSpecialOrder);
}
});
...
</script>
From what I've been reading, disabled fields cannot be changed without enabling. I'm guessing that is the only way to fix this but wanted to make sure first. Any ideas?
From what I've been reading, disabled fields cannot be changed without
enabling. I'm guessing that is the only way to fix this but wanted to
make sure first. Any ideas?
Disabled fields can sure be changed see this fiddle. Double check that you have the right value in your js code.
For reference (same code that's on fiddle):
<input type="checkbox" disabled="disabled" checked="checked" id="chkbox"/>
<input type="button" value="Toggle" id="toggle"/>
var chkBox = $("#chkbox");
$("#toggle").click(function(){
if (chkBox.is(':checked')) {
chkBox.prop('checked', false);
}
else {
chkBox.prop('checked', true);
}
});
It does not matter if checkbox is enabled or disabled. You should remove checked attribute from checkbox instead of setting it's checked property to false, otherwise it will remain checked:
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").removeAttribute('checked');
Example: http://jsbin.com/izonur/2/edit
disabled items are not submited by the form http://www.w3.org/TR/html401/interact/forms.html#h-17.12
you can have readonly items that are submited with the form (exactly the opposite of what you want)
I guess you are submitting form via a javascript somehow not properly. You must EXCLUDE disabled items from form when submitting, so it will work accordingly.

Categories

Resources