I am trying to add a line to a Sales Oder when a specific item has been added, but before it does, I need it to verify the state first.
This is where my struggle comes in. I have the code to add the item correctly working, but my state check errors out.
function validateField(type, name, linenumber) {
var shipstate = nlapiGetFieldText()
if (shipstate == 'PA') {
function recalc(type) {
if (type == 'item') {
var itemId = nlapiGetCurrentLineItemValue('item', 'item');
if (itemId == 1658) {
//Insert item
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', 1516);
nlapiSetCurrentLineItemValue('item', 'quantity', 1);
nlapiSetCurrentLineItemValue('item', 'amount', '0.24');
nlapiCommitLineItem('item');
}
}
return true;
}
}
return true;
}
Any insight to where my issue is? I think my issue is where I'm storing the state value so it can check the variable.
I would recommend adding your line with a recalc function instead of a validateField function. This is because if you try to add a new line while you are still editing an existing line it will cancel out of your current line. With a recalc function it will wait until you hit the 'Add' button on the existing line before checking the state and adding a new line.
You are on the right track with your state validation, the function you need is nlapiGetFieldValue('shipstate');. I believe the code below should solve your issue.
function recalc(type) {
var shipstate = nlapiGetFieldValue('shipstate');
if (shipstate === 'PA') {
addNewLine(type);
}
return true;
}
function addNewLine(type) {
if (type === 'item') {
var itemId = nlapiGetCurrentLineItemValue('item', 'item');
if (itemId === '1658') {
//Insert item
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', '1516');
nlapiSetCurrentLineItemValue('item', 'quantity', '1');
nlapiSetCurrentLineItemValue('item', 'amount', '0.24');
nlapiCommitLineItem('item');
}
}
return true;
}
Related
I have a simple drag and drop system when an item is entered, it creates a localstorage object with the "value" key. If I replace this added item with the drag and drop event, a new localstorage element is created with the "other" key and it is saved there, but I want it to be deleted from the "value" section when the item is replaced. How can I achieve this? You can check the codepen demo for a trial. Codepen: https://codepen.io/BerkayAkgurgen/pen/ExNbZGo
// Above Code is only about localstorage full code is on codepen account
function getLocalStorage() {
let value;
if (localStorage.getItem('value') === null) {
value = [];
} else {
value = JSON.parse(localStorage.getItem("value"))
}
return value;
}
function addToLocalStorage(paragraph) {
let value = getLocalStorage();
value.push(paragraph);
localStorage.setItem("value", JSON.stringify(value))
}
function changeAddToStorage(value) {
localStorage.setItem("other", JSON.stringify(value))
}
function dragStart(element) {
element.classList.add('draggable')
}
function dragEnd(element) {
drags.forEach(function (item) {
if (item.classList.contains('box-2')) {
changeAddToStorage(element.innerHTML)
}
})
element.classList.remove('draggable')
}
To remove the item from "value", call localStorage.removeItem("value") when the item is replaced.
function changeAddToStorage(value) {
localStorage.removeItem("value") // remove "value"
localStorage.setItem("other", JSON.stringify(value)) // save in "other"
}
if ($('<input/>').length == 0) {
T.stop();
}
the above is how I create the timer stop function.
This is where the part of the code has been placed:
$.map(exercise.syllables, function (syllable, j) {
if (!syllable || !syllable.trim().length) {
// If it doesn't exist or is an empty string, return early without creating/appending elements
return;
}
var innerSylCol = $('<div/>', {
class: 'col-md-3 inputSyllables'
});
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').each(function () {
$(this).replaceWith(getCorrectBtn($(this).val()))
});
S.addRight();
S.playRight();
} else if (cValue !== syllable){
// $(this).css({'color':'#e00413'});
S.playWrong();
S.addWrong();
}
});
innerSylCol.append(sylInput);
sylRow.append(innerSylCol);
});
idsyll = 0;
sylCol.append(sylRow);
exer.append(colLeft, sylCol);
exerciseArea.append(exer);
});
return exerciseArea;
if ($('<input/>').length == 0) {
T.stop();
}
}
The loop creates inputs based on words in my array, the inputs change to buttons when the inserted data is correct. I am trying to create it such that when the length of the inputs becomes 0 (so there are no input fields left, only buttons) it will stop the timer.
Two problems:
This code:
if ($('<input/>').length == 0) {
creates an input element, which is put in a jQuery wrapper, and then checks the number of elements in the wrapper. So the condition will always be false, because the length will always be 1. To search for input elements, remove the < and />: $("input")
You need to run that code in response to some condition (perhaps within the timer itself?) that might make $("input").length 0 by removing all input elements. Your quoted code is incomplete, but it doesn't seem like that check is being done later or in response to some event where inputs may have been removed.
I am using the below code to render the same as many as times,
I have two sections, one section with show-all class and another with no class.
When 'show-all' class is not available, it need to run countIncrease function, if class available no need to run the function,
In every time section need to check whether the class is available or not.
class Grid {
init() {
$('.grid').each(function() {
const $this = $(this);
// getting values & url from from html
const dropDownUrlpath = $this.find('.grid__dropdown-select').attr('data-ajaxurl');
const hasClass = $this.find('.grid').hasClass('grid_showall');
// countIncrease shows the inital 6 compoents/div and rest of will be hidden
// onclick it will display 3 components/div
function countIncrease() {
let limit = parseInt($this.find('.grid__component').attr('data-initcount'), 10);
const incrementalCall = parseInt($this.find('.grid__component').attr('data-incrementalcount'), 10);
$this.find(`.grid__content > .grid__component:gt(' ${limit - 1} ') `).hide();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
else {
$this.find('.grid__cta').show();
}
$this.find('.grid__cta').on('click', function(event) {
event.preventDefault();
limit += incrementalCall;
$this.find(`.grid__content > .grid__component:lt(' ${limit} ')`).show();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
});
}
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
// on dropdown change taking the selected dropdown value and adding #end of the url and replacing the previous html
$this.find('.grid__dropdown-select').on('change', function() {
const optionValue = this.value;
$.ajax({
url: dropDownUrlpath + optionValue,
success(result) {
$this.find('.grid__content').html(result);
countIncrease();
}
});
});
});
}
}
I written if condition, but it running once and giving false condition in both the scenarios,
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
How to handle it...?
shouldnt you add a parameter to the .hasClass so it knows what to check?
if ( $this.hasClass ('some class') === true ) {
alert('something');
}
or set if(hasClass.length > 0){}
keep the checking class in a variable by finding with parent div,
const hasClass = $this.find('.grid').hasClass('grid_showall');
gets the attribute value for only the first element in the matched set with .attr() method
const classInthis = hasClass.attr('class');
check the condition, with
if (classInthis !== 'grid_showall') {
countIncrease();
}
I created a js quiz. The questions are stored in a jquery array. However, clicking on next will not proceed to the next array value. How to fix this?
function nextQuestion() {
submt = true;
$('#explanation').empty();
$('#question').append(quiz[currentquestion]['question']).html();
if (quiz[currentquestion].hasOwnProperty('image') && quiz[
currentquestion]['image'] != "") {
if ($('#question-image').length == 0) {
$(document.createElement('img')).addClass(
'question-image').attr('id',
'question-image').attr('name', 'anscho').attr(
'src', quiz[currentquestion]['image']).attr(
'alt', htmlEncode(quiz[currentquestion][
'question'
])).insertAfter('#question');
} else {
$('#question-image').attr('src', quiz[
currentquestion]['image']).attr('alt',
htmlEncode(quiz[currentquestion]['question'])
);
}
} else {
$('#question-image').remove();
}
addChoices(quiz[currentquestion]['choices']);
setupButtons();
}
Solved it. Thanks to Johnny Mopp for pointing out that currentquestion should be incremented. Thanks!!!
Is it possible to return through multiple functions?
I have a jQuery on click function with a $.each loop in it. In the $.each loop I test for various conditions, and if not met display an alert message and then return. Here is a cut down version of my code:
$(document).on('click', '.add-to-basket, #add-to-basket', function(e) {
var data = {
id: $(this).data('id'),
quantity: 1
};
if($('#quant').length > 0) {
data.quantity = $('#quant').val();
}
var i = 0;
var j = 0;
if($('.product-option').length > 0) {
$('.product-option').each(function(index, element) {
if($(this).is('select')) {
//check to see if this is a required select, and return if a selection has not been made.
if($(this).data("force") == 1 && $(this).val() == 0) {
AlertDialogue($(this).data("title") + " requires a selection before you can add this product to your basket.", "Required Option");
return;
}
data.opts[i++] = $(this).val();
} else if($(this).is('input[type="checkbox"]:checked')) {
data.opts[i++] = $(this).val();
//check to see if this is a required group of checkboxes, and if so at least one has been checked. If not return.
} else if($(this).is('input[type="checkbox"]')) {
if($(this).data("force") == 1 && $('input[name="' + $(this).prop("name") + '"]:checked').length == 0) {
AlertDialogue($(this).data("title") + " requires at least one option to be checked before you can add this product to your basket.", "Required Option");
return;
}
} else if($(this).is('input[type="radio"]:checked')) {
data.opts[i++] = $(this).val();
} else if($(this).is('textarea')) {
//Check to see if this is a required textarea, and if so make sure there is some text in it.
if($(this).data("force") == 1 && $.trim($(this).val()).length == 0) {
AlertDialogue($(this).data("title") + " requires text before you can add this product to your basket.", "Required Option");
return;
}
if($(this).val().length > 0) {
data.text[j].id = $(this).data("id");
data.text[j++].val = $(this).val();
}
}
});
}
//submit product to the cart
});
However the return will only break that loop of the $.each loop, and start the next loop. I would like to not only break the $.each loop, but return from the on click function entirely.
Is this possible?
If so, how can I achieve this?
To exit from $.each you should return false
To exit from event handler function you should use return
As per your requirement you can do little like below,
var break = false;
$('.product-option').each(function(index, element) {
// rest of code
if(condition) {
break = true;
return false; // this will break out of each loop
}
});
if(break) {
return; // return from event handler if break == true;
}
// rest of code
Check out the docs for jQuery.each():
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same
as a continue statement in a for loop; it will skip immediately to
the next iteration.
Essentially, use return false; instead of just return;.