Onkeyup to fire a get request after only a few charcters - javascript

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.

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.

User Input not found in Database error message

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

How to get value of dynamically generated textbox with same id using AJAX/PHP?

In this webpage I am generating multiple textbox dynamically and each textbox is meant to hold unique value and I want to get that value dynamically.But I'm not being able to catch the value of the textbox according to its position. This code is only working for the firstly generated textbox. I have code like this
<tr>
<td align="center"><input type="text" name="serialNoArray[]" id="serialArray" onChange="checkusername()" ><span id="std_id_status"></span></td>
</tr>
<script>
function checkusername() {
var s = _("serialArray").value;
if(s != "") {
_("std_id_status").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true){
_("std_id_status").innerHTML = ajax.responseText;
}
}
ajax.send("std_id_check="+s);
}
}
</script>
First you should use classes not id, because an element with id must be unique for the entire document.
And since you use onChange you can pass the element using this like that onChange="checkusername(this)" .
I guess you should also change the code of the restrict function onkeyup="restrict('serialArray')" also but i do not see that code so I cannot help you more if you do not provide this code too...
<tr>
<td align="center"><input type="text" name="serialNoArray[]" class="serialArray" onkeyup="restrict('serialArray')" onChange="checkusername(this)" ><span class="std_id_status"></span></td>
</tr>
Then you can get only the value of the element being changed and change the html of the matching span only.(I use jQuery in the example so you should include it in your document.)
<script>
function checkusername(s) {
if (s.value != "") {
$(s).nextAll('.std_id_status').first().html('checking ...');
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
$(s).nextAll('.std_id_status').first().html(ajax.responseText);
}
}
ajax.send("std_id_check=" + s.value);
}
}
</script>
Since i do not have all your javascript code I could not test it but something like this should work.
I have not tested but this should do it
All the dynamically generated textboxes, give them a class
<input type="text" class="tagMe" placeholder="Enter Serial No." onkeypress="return isNumberKey2(event)" onkeyup="restrict('serialArray')" onChange="checkusername()" required autofocus >
Collecting the data
var info= "";
$('.tagMe').each( obj, function( key, value ) {
if(info != "")
info += "^"; // ^ is a delimiter
info += value;
});
Send info to your server, split on ^ and parse data (careful of empty elements)

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.

How to automatically clone <tr> when user finish fill up text input?

I have simple form with 2 textfield Name and Phone and can add new field when click Add new button. You can refer here jsfiddle .
My problem is how to add new textfield without press Add New button? When user fill up Text Input name and Text Input Phone new row <tr class="person"> will automatically added.
My second problem is I'm not sure how to write code for delete.
UPDATE : I also want to set maximum clone, can this be done?
If by "fill up" you mean "when the user enters as many characters as the Phone field allows" then you can add a maxlength="10" attribute to the input (setting the value as appropriate):
<input type="text" name="phone[]" id="phone" maxlength="10"/>
...and add a handler to the keyup event that checks whether the current value has reached the maxlength:
$('input[name="phone\[\]"]').keyup(function() {
if (this===$('input[name="phone\[\]"]').last()[0]
&& this.value.length===+$(this).attr("maxlength")) {
$("#add").click();
}
});
Note that you probably only want to do this test if the user is typing in the last row, hence the first part of the if test above.
Also you probably want the newly cloned fields to be blank, so you can do this within your add function:
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last')
.find("input").val("");
To set a maximum number of rows you can put a test in your add function:
$("#add").click(function() {
var $lastRow = $('#mytable tbody>tr:last');
if ($lastRow.index() < 10) { // set maximum rows here
$lastRow.clone(true).insertAfter($lastRow).find("input").val("");
}
return false;
});
Note also that you don't need to give those inputs an id attribute, but if you do you shouldn't copy it when you clone because id should be unique.
For a delete function, add a delete button to each row:
<td><input type="button" class="deleteRow" value="Delete"/></td>
...and then:
$("#mytable").on("click","input.deleteRow", function(){
if ($("#mytable tr").length > 2) // don't delete the last row
$(this).closest("tr").remove();
});
Demo: http://jsfiddle.net/3J65U/15/
I would expand on enclares - I would use .blur() for each textbox , and each time check and make sure each value is not "" - that would make sure both are filled
Then in jQuery:
$(document).ready(function() {
$(".phone").blur(function() {
var phonetxt = $('.phone'.val();
var nametxt = $('.name').val();
if ( phonetxt != "" && nametxt != "" ){
$(this).closest('tr').clone(true)
.insertAfter('#mytable tr:last')
.find('input').val('').first().focus();
});
}
$(".name").blur(function() {
var phonetxt = $('.phone'.val();
var nametxt = $('.name').val();
if ( phonetxt != "" && nametxt != "" ){
$(this).closest('tr').clone(true)
.insertAfter('#mytable tr:last')
.find('input').val('').first().focus();
});
}
});​
You could do it on blur as well as the add new button. Also be careful with duplicated id's, use classes instead:
<tr class="person">
<td><input type="text" name="name[]" class="name" /></td>
<td><input type="text" name="phone[]" class="phone" /></td>
</tr>
Then in jQuery:
$('.phone').blur(function() {
var ppl = $('.person').length;
if ( this.value && ppl < 5 ) { // Max 5 people
$(this).closest('tr').clone(true)
.insertAfter('#mytable tr:last')
.find('input').val('').first().focus();
$(this).off('blur');
}
});
Demo: http://jsfiddle.net/elclanrs/YEBQt/ (tab from input to input)

Categories

Resources