I want to make a history search based on user text input html, this code below works fine but it duplicates the same input. For instance :
The user type 'abcd' in input text and click the button.
the value 'abcd' store as history search.
When the user try to search the 'abcd' and click the button again, the history search adding 'abcd' as well, so it has 2 'abcd' value.
My js function:
function cek() {
resi_or_code = document.getElementById('code_or_resi').value;
resi = resi_or_code.split(',');
if($.trim(resi_or_code) != ''){
location.href = base_url + 'resi/' + encodeURIComponent(resi_or_code);
}
if (localStorage.daftar_data){
daftar_data = JSON.parse(localStorage.getItem('daftar_data'));
$("#riwayat").toggle();
}
else {
daftar_data = [];
}
for (y in daftar_data){
var q = daftar_data[y].resis;
for (x in resi){
console.log(q);
if (q === resi[x])
{
console.log('Value exist');
}else{
console.log('Value does not exist');
daftar_data.push({'resis':resi[x]});
localStorage.setItem('daftar_data', JSON.stringify(daftar_data));
}
}
}
}
What did I do wrong? Please help.
Related
I am new to suitescript. Openly telling I hardly wrote two scripts by seeing other scripts which are little bit easy.
My question is how can read a data from sublist and call other form.
Here is my requirement.
I want to read the item values data highlighted in yellow color
When I read that particular item in a variable I want to call the assemblyitem form in netsuite and get one value.
//Code
function userEventBeforeLoad(type, form, request)
{
nlapiLogExecution('DEBUG', 'This event is occured while ', type);
if(type == 'create' || type == 'copy' || type == 'edit')
{
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
//var itemfield = nlapiGetFieldValue('item')
//nlapiLogExecution('DEBUG','This value is = ',itemfield);
var formname = nlapiLoadRecord('itemreceipt',itemfield);
nlapiLogExecution('DEBUG','This value is = ',formname);
}
}
}
How can I proceed further?
I want to read that checkbox field value in the following image when i get the item value from above
I recommend looking at the "Sublist APIs" page in NetSuite's Help; it should describe many of the methods you'll be working with.
In particular you'll want to look at nlobjRecord.getLineItemValue().
Here's a video copmaring how to work with sublists in 1.0 versus 2.0: https://www.youtube.com/watch?v=n05OiKYDxhI
I have tried for my end and got succeed. Here is the answer.
function userEventBeforeLoad(type, form, request){
if(type=='copy'|| type =='edit' || type=='create'){
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
var itemcount = nlapiGetLineItemCount('item');
nlapiLogExecution('DEBUG','This value is = ',+itemcount);
for(var i=1;i<=itemcount;i++)
{
var itemvalue = nlapiGetLineItemValue('item','itemkey',i);
nlapiLogExecution('DEBUG','LineItemInternalID = ',itemvalue);
var itemrecord = nlapiLoadRecord('assemblyitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
if(itemrecord == null){
var itemrecord = nlapiLoadRecord('inventoryitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
}
var value = itemrecord.getFieldValue('custitem_mf_approved_for_dock_to_stock');
nlapiLogExecution('DEBUG',"Checkboxvalue = ",value);
if(value == 'F'){
nlapiSetLineItemValue('item','location',i,9);
nlapiSetLineItemDisabled ('item','location',false,i );
}
else{
nlapiSetLineItemValue('item','location',i,1);
nlapiSetLineItemDisabled ('item','location',true,i );
}
}
}
}
}
I want to make conversion tool which converts one code (user input) to another (predefined). I decided to use Javascript object as a container for codes, and my function will take user input which is actually a key from a javascript object, match it to the one in Code container and if the match is found, the function will display value to the alert box.
I made one code, but it does not work. I tried to find the solution but for now, I failed.
Here is my code:
$(document).ready(function() {
$("#convert").click(function(){
var GardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"995331",
"A2" :"995332",
"A2A" :"995333",
"A3" :"995334",
"A3A" :"995335",
"A3B" :"995336",
"A4" :"995337",
"A4A" :"995338",
"A4B" :"995339",
"A4C" :"995340",
"A4D" :"995341",
"A4E" :"995342",
"A5" :"995343",
"A5A" :"995344",
"A5B" :"995345",
"A5C" :"995346",
"A6" :"995347",
};
var userInput = $("#userInput").val; /*for example 'A1'*/
if (userInput in GardinerToUnicodeCodePoint) {
alert(/*value of key 'userInput' -> 995328*/);
} else {
alert("No code found!");
}
});
});
You can use [] after calling the object to get the key value pair:
GardinerToUnicodeCodePoint[userInput]
Change your code to:
var userInput = $("#userInput").val; /*for example 'A1'*/
if (userInput in GardinerToUnicodeCodePoint) {
alert(GardinerToUnicodeCodePoint[userInput]);
} else {
alert("No code found!");
}
See jsfiddle: https://jsfiddle.net/wy70s3gj/
function getReturnCodeUsingKey(keyFromUserInput)
{
var GardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"etc"
};
returnVal = GardinerToUnicodeCodePoint[keyFromUserInput];
return returnVal ? returnVal : "error: no match found";
}
Pass that function your string input from the user, and it'll return what you want I think.
So, you're full solution would look like this:
$(document).ready(function() {
$("#convert").click(function(){
var userInput = $("#userInput").val(); /*for example 'A1'*/
// a call to our new function keeping responsibilities seperated
return getReturnCodeUsingKey(userInput);
});
});
function getReturnCodeUsingKey(keyFromUserInput)
{
var GardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"995331",
"A2" :"995332",
"A2A" :"995333",
"A3" :"995334",
"A3A" :"995335",
"A3B" :"995336",
"A4" :"995337",
"A4A" :"995338",
"A4B" :"995339",
"A4C" :"995340",
"A4D" :"995341",
"A4E" :"995342",
"A5" :"995343",
"A5A" :"995344",
"A5B" :"995345",
"A5C" :"995346",
"A6" :"995347",
};
// set a variable to hold the return of the object query
returnVal = GardinerToUnicodeCodePoint[keyFromUserInput];
//return valid value from object, or string if undefined
return returnVal ? returnVal : "error: no match found";
}
The issue here as expresed in the comments by #epascarello is that you should use $("#userInput").val(); with the parenthesis
Code example:
$('#convert').click(function() {
var GardinerToUnicodeCodePoint = {
A1: '995328',
A1A: '995329',
A1B: '995330',
A1C: '995331',
A2: '995332',
A2A: '995333',
A3: '995334',
A3A: '995335',
A3B: '995336',
A4: '995337',
A4A: '995338',
A4B: '995339',
A4C: '995340',
A4D: '995341',
A4E: '995342',
A5: '995343',
A5A: '995344',
A5B: '995345',
A5C: '995346',
A6: '995347'
};
var userInput = $('#userInput').val();
var result = userInput in GardinerToUnicodeCodePoint
? 'Value of key \'userInput\' -> ' + userInput
: 'No code found!';
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="userInput">
<button id="convert">Submit</button>
I am following this answer https://stackoverflow.com/a/20698523/1695685 in order to read value from a handheld barcode scanner. The code works fine as mentioned in the answer (fiddle is attached in the above link)
However, what I am trying to do is to make some ajax calls based on the current value of text input after reading a barcode.
The problem I'm facing is that if I scan barcode multiple times I am making ajax calls the same number of times after I press a button (which triggers the ajax call). For e.g. If I read 4 barcodes, I am making the same ajax call( in my case http://localhost:51990/Home/DecodeScanner) 4 times. What I am after is to make only one call after pressing a button, but only read the latest value from the text input box.
Every time I can scan a barcode the text input box is showing the new value (previous values are overridden). However, the ajax call is firing all the previous scans as well on pressing #scanner-verify-button button.
This is my modified Fiddle with my custom ajax calls
/*
This code will determine when a code has been either entered manually or
entered using a scanner.
It assumes that a code has finished being entered when one of the following
events occurs:
• The enter key (keycode 13) is input
• The input has a minumum length of text and loses focus
• Input stops after being entered very fast (assumed to be a scanner)
*/
var inputStart, inputStop, firstKey, lastKey, timing, userFinishedEntering;
var minChars = 3;
// handle a key value being entered by either keyboard or scanner
$("#scanInput").keypress(function(e) {
// restart the timer
if (timing) {
clearTimeout(timing);
}
// handle the key event
if (e.which == 13) {
// Enter key was entered
// don't submit the form
e.preventDefault();
// has the user finished entering manually?
if ($("#scanInput").val().length >= minChars) {
userFinishedEntering = true; // incase the user pressed the enter key
inputComplete();
}
} else {
// some other key value was entered
// could be the last character
inputStop = performance.now();
lastKey = e.which;
// don't assume it's finished just yet
userFinishedEntering = false;
// is this the first character?
if (!inputStart) {
firstKey = e.which;
inputStart = inputStop;
// watch for a loss of focus
$("body").on("blur", "#scanInput", inputBlur);
}
// start the timer again
timing = setTimeout(inputTimeoutHandler, 500);
}
});
// Assume that a loss of focus means the value has finished being entered
function inputBlur() {
clearTimeout(timing);
if ($("#scanInput").val().length >= minChars) {
userFinishedEntering = true;
inputComplete();
}
};
// reset the page
$("#reset").click(function(e) {
e.preventDefault();
resetValues();
});
function resetValues() {
// clear the variables
inputStart = null;
inputStop = null;
firstKey = null;
lastKey = null;
// clear the results
inputComplete();
}
// Assume that it is from the scanner if it was entered really fast
function isScannerInput() {
return (((inputStop - inputStart) / $("#scanInput").val().length) < 15);
}
// Determine if the user is just typing slowly
function isUserFinishedEntering() {
return !isScannerInput() && userFinishedEntering;
}
function inputTimeoutHandler() {
// stop listening for a timer event
clearTimeout(timing);
// if the value is being entered manually and hasn't finished being entered
if (!isUserFinishedEntering() || $("#scanInput").val().length < 3) {
// keep waiting for input
return;
} else {
reportValues();
}
}
// here we decide what to do now that we know a value has been completely entered
function inputComplete() {
// stop listening for the input to lose focus
$("body").off("blur", "#scanInput", inputBlur);
// report the results
reportValues();
}
function reportValues() {
// update the metrics
$("#startTime").text(inputStart == null ? "" : inputStart);
$("#firstKey").text(firstKey == null ? "" : firstKey);
$("#endTime").text(inputStop == null ? "" : inputStop);
$("#lastKey").text(lastKey == null ? "" : lastKey);
$("#totalTime").text(inputStart == null ? "" : (inputStop - inputStart) + " milliseconds");
if (!inputStart) {
// clear the results
$("#resultsList").html("");
$("#scanInput").focus().select();
} else {
// prepend another result item
var inputMethod = isScannerInput() ? "Scanner" : "Keyboard";
$("#resultsList").prepend("<div class='resultItem " + inputMethod + "'>" +
"<span>Value: " + $("#scanInput").val() + "<br/>" +
"<span>ms/char: " + ((inputStop - inputStart) / $("#scanInput").val().length) + "</span></br>" +
"<span>InputMethod: <strong>" + inputMethod + "</strong></span></br>" +
"</span></div></br>");
$("#scanInput").focus().select();
inputStart = null;
// Some transformations
const barcodeString = $("#scanInput").val();
const productCode = barcodeString.substring(5, 19);
const serialNumber = barcodeString.substring(36, 46);
const batch = barcodeString.substring(29, 34);
const expirationDate = barcodeString.substring(21, 27);
// AJAX calls
$('#scanner-verify-button').click(function() {
$.ajax({
url: "DecodeScanner",
type: "POST",
data: {
productCode: productCode,
serialNumber: serialNumber,
batch: batch,
expirationDate: expirationDate,
commandStatusCode: 0
},
async: true,
success: function(data) {
$('#pTextAreaResult').text(data);
}
});
});
}
}
$("#scanInput").focus();
HTML
<form>
<input id="scanInput" />
<button id="reset">Reset</button>
</form>
<br/>
<div>
<h2>Event Information</h2> Start: <span id="startTime"></span>
<br/>First Key: <span id="firstKey"></span>
<br/>Last Ley: <span id="lastKey"></span>
<br/>End: <span id="endTime"></span>
<br/>Elapsed: <span id="totalTime"></span>
</div>
<div>
<h2>Results</h2>
<div id="resultsList"></div>
</div>
<div class="col-sm-12">
<button id="scanner-verify-button" type="submit">Verify</button>
</div>
As per the code, the click handler for the scanner button seems to be registered multiple times.
The click handler should be registered only once.
The reportValues() is called multiple times which registers the click handler multiple times. This means when you press the button, all the click handlers get called and ajax request gets triggered.
You need to put the click handler outside of any function which can get called multiple times.
Also as per the code, all the variables which need to be accessed by the click handler should be declared outside reportValues.
The problem was the ajax call inside block $('#scanner-verify-button').click(function() {} was attaching new listener to the button on everytime the reportValues() call waas made.
I was able to solve this by moving the ajax calls in its own block
// Check for any input changes
var productCode, serialNumber, batch, expirationDate;
$("#scanInput").on("change paste keyup", function () {
barcodeString = $("#scanInput").val();
productCode = barcodeString.substring(5, 19);
serialNumber = barcodeString.substring(36, 46);
batch = barcodeString.substring(29, 34);
expirationDate = barcodeString.substring(21, 27);
});
// Ajax calls
$("#scanner-verify-button").click(function () {
$.ajax({
url: "DecodeScanner",
type: "POST",
data: {
productCode: productCode,
serialNumber: serialNumber,
batch: batch,
expirationDate: expirationDate,
commandStatusCode: 0
},
async: true,
success: function (data) {
$('#pTextAreaResult').text(data);
}
});
});
Working Fiddle
I'm trying to create something to refresh the list of dates to all users every 30 seconds.
I dynamically create a table with the list of dates in my database using AJAX, the thing is that the refresh removes what the user was writing in the moment of the refresh so I'm saving what the user writes in javascript global variables, calling the refresh function, then filling the inputs with the information in the variables and focusing the input the user was on.
The thing is the inputs aren't filled nor focused.
this is my relevant code here:
var identificacionc = "";
var nombresc = "";
var apellidosc = "";
var telefonoc = "";
var posicionc = 0;
var ladoc = 0;
//This is called on input onfocus to record the id
function recuerdo(posicion, lado)
{
posicionc = posicion;
ladoc = lado;
}
function actualizar()
{
//This line is not relevant
listaragenda();
if (document.getElementById("datepicker").value != "")
{
//put the info in the global variables and it works even if they're dynamically created
identificacionc = document.getElementById("txtidentificacion" + posicionc).value;
nombresc = document.getElementById("txtnombres" + posicionc).value;
apellidosc = document.getElementById("txtapellidos" + posicionc).value;
telefonoc = document.getElementById("txttelefono" + posicionc).value;
//Here is where I call the function to refresh dates
listarcitas();
}
}
function listarcitas()
{
var objAjax = crearObjeto();
var fecha = document.getElementById("datepicker").value;
objAjax.open("POST", "clases/listarcitas.php", true);
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
objAjax.onreadystatechange = function()
{
if (objAjax.readyState == 4 && objAjax.status == 200)
{
document.getElementById("citaslistadas").innerHTML = objAjax.responseText;
//Checks if any global variable is not empty to start to fill them with the info
//nothing inside this If works
//posicionc and ladoc have the correct values
if (identificacionc != "")
{
document.getElementById("txtidentificacion" + posicionc).value = identificacionc;
document.getElementById("txtnombres" + posicionc).value = nombresc;
document.getElementById("txtapellidos" + posicionc).value = apellidosc;
document.getElementById("txttelefono" + posicionc).value = telefonoc;
if (ladoc == 1)
{
document.getElementById("txtidentificacion" + posicionc).focus();
}
else if (ladoc == 2)
{
document.getElementById("txtnombres" + posicionc).focus();
}
else if (ladoc == 3)
{
document.getElementById("txtapellidos" + posicionc).focus();
}
else if (ladoc == 4)
{
document.getElementById("txttelefono" + posicionc).focus();
}
}
}
}
objAjax.send("fecha=" + fecha);
}
//the interval every 30s
window.setInterval("actualizar()", 30000);
Everything retrieved from AJAX works fine everything is listed, even in the web browser console I make alerts of the variables, set the values and focus the dynamically created inputs, everything works fine.
But why this is not working in the code?
Thanks in advance
In my entity (A) has 50 option set. If the user select 10 optionsset value and not selected remaining one, and he/she click save button. In that situation i need to alert user "To fill all the option set". I don't want to get the Schema name for the optionset individually, i need to get all the option set schema name dynamically.
Is it possible? Help me.
I have not tested this function, but you can try this and make changes if needed.
function IsFormValidForSaving(){
var valid = true;
var message = "Following fields are required fields: \n";
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == "required") {
if(attribute.getValue() == null){
var control = attribute.controls.get(0);
// Cheking if Control is an optionset and it is not hidden
if(control.getControlType() == "optionset" && control.getVisible() == true) {
message += control.getLabel() + "\n";
}
valid = false;
}
}
});
if(valid == false)
{
alert(message);
}
}
Ref: Microsoft Dynamics CRM 2011 Validate required form javascript
Required fields individual alert fire before the on save event. If you wish to prevent the single alert routine for all unfilled option sets you need to remove the requirement constraint and manage the constraint yourself, probably in your on save handler. I’m just writing the idea here (not tested).
// enter all optionsets ids
var OptionSets50 = ["new_optionset1","new_optionset2","new_optionset50"];
var dirtyOptions = [];
function MyOptionSet(id) {
var mos = this;
var Obj = Xrm.Page.getAttribute(id);
var Ctl = Xrm.Page.getControl(id);
Obj.addOnChange(
function () {
if (Obj.getValue() != null)
delete dirtyOptions[id];
else
dirtyOptions[id] = mos;
});
this.GetLabel = function() {
return Ctl.getLabel();
}
if (Obj.getValue() == null)
dirtyOptions[id] = mos;
}
function OnCrmPageLoad() {
for(var x in OptionSets50) {
OptionSets50 [x] = new MyOptionSet(OptionSets50 [x]);
}
Xrm.Page.data.entity.addOnSave(OnCrmPageSave);
}
//check for dirty options and alert
function OnCrmPageSave(execContext) {
var sMsg = "The following Optinsets Are Required: ";
var sLen = sMsg.length;
for(var os in dirtyOptions) {
sMsg += dirtyOptions[os].GetLabel() + "\n";
}
if (sMsg.length > sLen) {
execContext.getEventArgs().preventDefault();
alert(sMsg);
}
}