Any better way to declare variables avoiding repetition of code? - javascript

Here is the js code which i am trying to use. I don't like the same code repeating again and I couldn't help myself to do this in a better way.
$(function(){
$('[data-behavior~=quick-reject]').on("click", function(){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if((some_reasons.val() === "") && ( some_action === "reject")){
var errorReason = "Please select a reason";
form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if(some_action === "verify"){
some_reasons.hide();
}else{
some_reasons.show();
}
});
});

You could just make a little utility function, something like.
function getVars(that) {
var form = $(that).closest("[data-behavior~=modal-footer]").find("form");
return {
form: form,
some_action: form.find("#some_actions").val(),
some_reasons: form.find("[data-behavior~=escalation-reason-select-box]")
}
}
$('[data-behavior~=quick-reject]').on("click", function(){
var v = getVars(this);
if((v.some_reasons.val() === "") && ( v.some_action === "reject")){
var errorReason = "Please select a reason";
v.form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
v.form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var v = getVars(this);
if(v.some_action === "verify"){
v.some_reasons.hide();
}else{
v.some_reasons.show();
}
});

Related

How can ı make capitalization checker with array some and map function?

I use OOP system. I have one product list add project and ı want to capitalization check. I know two solution for problem but doesn't work.
For example, I entered a product called "bag" and again I want the same product not to be capitalized. Different letters such as "bag" and "Bag" or "BAG" should not be written in capital letters. how can ı fix this? Thanks advance for answer. (You just need to answer one of the two solutions.) Full code: https://codepen.io/BerkayAkgurgen/pen/bGBNojw
// Some Solution
function addProductToUI(e) {
const productName = nameInput.value.trim().toLowerCase();
const productModel = modelInput.value.trim();
const productPrice = priceInput.value.trim();
let products = getTodosFromStorage();
const urunlerim = new Urunler(productName, productModel, productPrice);
if (productModel == "" || productName == "" || productPrice == "") {
UI.showAlert("danger", "Hatalı Giriş")
} else if (todos.some(a => a.trim().toLowerCase() == newTodoValuee)) {
console.log("sdaas");
return false;
} else {
let control = false;
const products = Storage.getProductsFromStorage();
products.forEach(function (product) {
if (productName === product.productName) {
control = true;
}
});
if (control === false) {
UI.urunEkle(urunlerim);
Storage.addProductsToStorage(urunlerim);
UI.showAlert("success", "Başarılı Giriş");
nameInput.value = "";
modelInput.value = "";
priceInput.value = "";
} else {
UI.showAlert("danger", "Aynı Marka Girilemez");
}
}
e.preventDefault();
}
// Map Solution
function addProductToUI(e) {
const productName = nameInput.value.trim().toLowerCase();
const productModel = modelInput.value.trim();
const productPrice = priceInput.value.trim();
let products = getTodosFromStorage();
var words = todos.map(w => w.toLowerCase());
const urunlerim = new Urunler(productName, productModel, productPrice);
if (productModel == "" || productName == "" || productPrice == "") {
UI.showAlert("danger", "Hatalı Giriş")
} else if (words.includes(productName)) {
e.preventDefault();
console.log("Aynı Todo");
nameInput.value = "";
return false;
} else {
let control = false;
const products = Storage.getProductsFromStorage();
products.forEach(function (product) {
if (productName === product.productName) {
control = true;
}
});
if (control === false) {
UI.urunEkle(urunlerim);
Storage.addProductsToStorage(urunlerim);
UI.showAlert("success", "Başarılı Giriş");
nameInput.value = "";
modelInput.value = "";
priceInput.value = "";
} else {
UI.showAlert("danger", "Aynı Marka Girilemez");
}
}
e.preventDefault();
}
Ok, your code is huge, makes sense I guess, so I'll just give you a function you can use to only return common letters from a given text element(so that you can work with it)
The idea of how the function is used is that you store all values as lowercase FROM THE INPUT and do checks when INPUT IS ALREADY LOWERED
var x=document.getElementById('x')
function lowerCaseInput(elem){return elem.value.toLowerCase()}
var obj={}
document.getElementById('b')
.addEventListener('click',function(ev){
var input=lowerCaseInput(x)
if(obj[input]){alert(`Error: "${input}" already exists`)}
else{obj[input]=1; console.log(obj)}
})
<input id="x" />
<button id="b">add value</button>

Simplify jQuery code - slide and slideToggle

How can I simplify current JavaScript code? It looks too complicated.
// Data from AJAX response
var errorsJSON = {
"name-pl": ["The name-pl field is required."],
"name-en": ["The name-en field is required."]
}
var errorString = $(this).data('validate-multiple');
var errorNamesArray = errorString.split(", ");
var ul = $('<ul class="list-unstyled">');
$.each(errorNamesArray, function(key, value) {
if (errorsJSON.hasOwnProperty(value)) {
ul.append(`<li><span class="help-block">${errorsJSON[value]}</span></li>`);
}
});
if (! $(this).is(':visible') && ul.children('li').length > 0) {
$(this).find('div.controls').empty().append(ul);
$(this).slideDown(500);
} else if ($(this).is(':visible') && ul.children('li').length === 0) {
$(this).slideUp(500);
} else if ($(this).is(':visible') && ul.children('li').length > 0) {
$(this).slideUp(500, function() {
$(this).find('div.controls').empty().append(ul);
$(this).slideDown(500);
});
}
Here I pasted both html and js code http://jsfiddle.net/ecLjnnhm/
I would like to point out that errorsJSON can change and depends what user put in the input fields.
Readability: Use variables to store the conditions of your if statements instead of lengthy declarations each time.
Efficiency: Cache $(this) as a variable so jQuery only has to do the work once.
Personal preference: I'd suggest prefacing any jQuery object variables (like ul in your case) with a $ to indicate that they're a jQuery object.
// Data from AJAX response
var errorsJSON = {
"name-pl": ["The name-pl field is required."],
"name-en": ["The name-en field is required."]
}
var errorString = $(this).data('validate-multiple');
var errorNamesArray = errorString.split(", ");
var $ul = $('<ul class="list-unstyled">');
var $t = $(this);
var isVisible = $t.is(':visible');
var hasErrors = false;
$.each(errorNamesArray, function(key, value) {
if (errorsJSON.hasOwnProperty(value)) {
$ul.append(`<li><span class="help-block">${errorsJSON[value]}</span></li>`);
hasErrors = true;
}
});
if (!isVisible && hasErrors) {
$t.find('div.controls').empty().append(ul);
$t.slideDown(500);
} else if (isVisible && !hasErrors) {
$t.slideUp(500);
} else if (isVisible && hasErrors) {
$t.slideUp(500, function() {
$t.find('div.controls').empty().append(ul);
$t.slideDown(500);
});
}

jQuery / js toLowercase

I can't turn searchBox to a .toLowerCase and my code is case sensitive because of this. I want the code to scan on both upperCase and lowerCase letters.
I wasn't able to find a solution to my problem.
<script>
$("#searchBtn").keyup(function () {
var searchBox = $("#searchBtn").val();
var returnRows = [];
$('tr').not('.headerRow').each(function () {
var addRow = true;
var $currentRow = $(this);
$currentRow.find('td').each(function () {
var $td = $(this);
var word = $td.text();
if (word.indexOf(searchBox) > -1) {
addRow = false;
return false;
// console.log("KOMT IN IF STATEMENT"); //sla deze rij op in een tijdelijke array
}
});
if (addRow) {
returnRows.push($currentRow)
}
});
if (true)
{
$('tr').show();
}
$.each(returnRows, function (i, v) {
$(v).hide();
});
});
</script>
I am not sure but you are making it a bit more complicated. Try something like this:
$("#searchBtn").keyup(function() {
var word = $("#searchBtn").val(),
timer;
if(timer){ clearTimeout(timer); }
timer = setTimeout(function(){
$('tr').not('.headerRow').filter(function(){
var txt = $(this).find('td').text();
return txt.indexOf(word) !== -1 && txt === word;
}).hide();
},900);
});
=== lets you compare strictly. So, in such case T !== t would result in true.

javascript regexp on keyup

i'm trying to make script which will replace all unwanted characters (from regexp) in input on keyup event. I tried everything but nothing works for me...
My code:
$('#form_accomodation_cell').on('keyup', 'input[name="accomodation_cell[]"]', function() {
var value = $(this).val();
var regex_cell = /^[0-9 \+]+$/g;
if (!isNumeric(value, regex_cell))
{
var new_value = value.replace(regex_cell, '');
alert(new_value);
}
function isNumeric(elem, regex_cell) {
if(elem.match(regex_cell)){
return true;
}else{
return false;
}
}
});
Try this:
$('#form_accomodation_cell').on("keyup", function () {
var value = $(this).val();
var regex_cell = /[^[0-9 +]]*/gi;
var new_value = value.replace(regex_cell, '');
alert(new_value);
});
See it here in action.
I think you should try to catch the event and finaly write this way !
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /^[0-9 \+]+$/g;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}

jQuery if condition text contains

I wrote a simple if condition, but not quite working.
if text is 123 change to hi, if text is 456 change it to hi2
Could someone please give me a hand.
<h1>123</h1>
<h1>456</h1>
<h1>789</h1>​
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
var text = $(h1).text();
if (text == changeText) {
$(this).text('hi');
} else if (text == changeText2 ) {
$(this).text('hi2');
}
});
​
http://jsfiddle.net/8P2ma/
There are multiple things wrong with your code:
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
var text = $(h1).text(); //aside from having to iterate through, the jquery
//selector needs to be enclosed in quotes: $('h1')
if (text == changeText) { //The variable 'changeText' does not exist.
$(this).text('hi');
} else if (text == changeText2 ) {
$(this).text('hi2');
}
});
//working code:
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
$('h1').each(function() {
var text = $(this).text();
if (text == changeText1) {
$(this).text('hi');
} else if (text == changeText2) {
$(this).text('hi2');
}
});
});​
$(function() {
$('h1:contains("123")').text('hi');
$('h1:contains("456")').text('hi2');
});​
FIDDLE
Do it like this:
$(document).ready(function() {
var change = {
'123': 'hi',
'456': 'hi2'
};
$('h1').text(function(i, txt) {
return change[$.trim(txt)];
});
});
DEMO: http://jsfiddle.net/By4Ra/

Categories

Resources