Send POST request only if check box is checked - javascript

So I'm trying to make my script only log and send the POST request if the check box is checked... The problem is when I un-check the box. It's still sending the post request.
This script basically adds check boxes to a specific elements, and gets the ID value if it's checked.
Here's my script:
const userlist = document.querySelector('#userlist');
new MutationObserver(() => {
userlist.querySelectorAll('.user:not([data-has-checkbox])').forEach((userDiv) => {
const checkbox = userDiv.insertBefore(document.createElement('input'), userDiv.children[0]);
checkbox.type = 'checkbox';
userDiv.dataset.hasCheckbox = true;
});
}).observe(userlist, { childList: true });
userlist.addEventListener('change', ({ target }) => {
if (target.matches('.user > input[type="checkbox"]')) {
const userDiv = target.parentElement;
var nameb = userDiv.id.replace("user_", ""); // Make variable for REQUEST
}
var evtSource = new EventSource("http://myurl.com/_watch//_index?_=1557958948927");
evtSource.onmessage = function(e) {
var obj = JSON.parse(e.data);
var line = JSON.stringify(obj.line)
var size = JSON.stringify(obj.lineWidth)
var color = JSON.stringify(obj.lineColor) // Not needed, but defined
anyways.
var chat = JSON.stringify(obj.msg)
var original = line
//var mirror = JSON.parse(JSON.stringify(original).replace(/\d+/g, number => 20 + +number))
var list = JSON.parse(JSON.stringify(userList)) //LineLog
//--------------------------
if (obj.ident === nameb) // if ident ='s userDiv's Id value...
{
$.post("/draw.php?ing=_index", {
l: (line),
w : parseInt(obj.lineWidth) + 2,
c: ("ffffff"),
o: ("100"),
f: ("1"),
_: ("false")
})
console.log(nameb) //log the value.
}
});
If you can help me find a solution that would be great. Thank you.

Have you tried this?
const checkbox = document.querySelector('#myCheckBox');
checkbox.addEventListener('change', e => {
const self = e.target;
if (self.checked){
// send
}
})
const userlist = document.querySelector('#userlist');
new MutationObserver(() => {
userlist.querySelectorAll('.user:not([data-has-checkbox])').forEach((userDiv) => {
const checkbox = userDiv.insertBefore(document.createElement('input'), userDiv.children[0]);
checkbox.type = 'checkbox';
userDiv.dataset.hasCheckbox = true;
});
}).observe(userlist, { childList: true });
userlist.addEventListener('change', (e, { target }) => {
if ( !e.target.checked ) return
if (target.matches('.user > input[type="checkbox"]')) {
const userDiv = target.parentElement;
var nameb = userDiv.id.replace("user_", "");
}
var evtSource = new EventSource("http://myurl.com/_watch//_index?_=1557958948927");
evtSource.onmessage = function(e) {
var obj = JSON.parse(e.data);
var line = JSON.stringify(obj.line)
var size = JSON.stringify(obj.lineWidth)
var color = JSON.stringify(obj.lineColor) // Not needed, but defined
anyways.
var chat = JSON.stringify(obj.msg)
var original = line
//var mirror = JSON.parse(JSON.stringify(original).replace(/\d+/g, number => 20 + +number))
var list = JSON.parse(JSON.stringify(userList)) //LineLog
//--------------------------
if (obj.ident === nameb) // if ident ='s userDiv's Id value...
{
$.post("/draw.php?ing=_index", {
l: (line),
w : parseInt(obj.lineWidth) + 2,
c: ("ffffff"),
o: ("100"),
f: ("1"),
_: ("false")
})
console.log(nameb) //log the value.
}
});

Related

How to auto grow text on input value?

I have an input form field that outputs text on submit to another created input, essentially an editable todo list. I have tried to make the input text value auto grow, but cannot figure out how to do it. Right now the user has to scroll over to see the rest of the text on each list item. This should not be.
What I tried:
I have tried creating a span and attaching editableContent but that makes my input text disappear.
I have tried setting an attribute on max-length on the created input but cannot get it to work. What is the best way to accomplish auto growing the text input value?
Here is the full codepen
const createTodoText = (todo) => {
const itemText = document.createElement("INPUT");
// const itemText = document.createElement("span");
// itemText.contentEditable
// itemText.contentEditable = 'true'
itemText.classList.add("todoText");
itemText.value = todo.name;
itemText.addEventListener("click", (e) => {
e.currentTarget.classList.add("active");
});
// update todo item when user clicks away
itemText.addEventListener("blur", (e) => {
todo.name = e.currentTarget.value;
renderTodos();
});
return itemText;
};
There you go: -
// select DOM elements
const todoForm = document.querySelector(".todo-form");
const addButton = document.querySelector(".add-button");
const input = document.querySelector(".todo-input");
const ul = document.getElementById("todoList");
let todos = [];
todoForm.addEventListener("submit", function (e) {
e.preventDefault();
addTodo(input.value);
});
const addTodo = (input) => {
if (input !== "") {
const todo = {
id: Date.now(),
name: input,
completed: false
};
todos.push(todo);
renderTodos();
todoForm.reset();
}
};
const renderTodos = (todo) => {
ul.innerHTML = "";
todos.forEach((item) => {
let li = document.createElement("LI");
// li.classList.add('item');
li.setAttribute("class", "item");
li.setAttribute("data-key", item.id);
const itemText = createTodoText(item);
const cb = buildCheckbox(item);
const db = buildDeleteButton(item);
// if (item.completed === true) {
// li.classList.add('checked');
// }
li.append(cb);
li.append(db);
li.append(itemText);
ul.append(li);
});
};
const createTodoText = (todo) => {
const itemText = document.createElement("span");
itemText.setAttribute('role','textbox');
itemText.setAttribute('contenteditable',"true");
itemText.classList.add("todoText");
itemText.innerHTML = todo.name;
itemText.addEventListener("click", (e) => {
e.currentTarget.classList.add("active");
});
// update todo item when user clicks away
itemText.addEventListener("blur", (e) => {
todo.name = e.target.textContent;
renderTodos();
});
return itemText;
};
const buildCheckbox = (todo) => {
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.name = 'checkbox';
cb.classList.add('checkbox');
cb.checked = todo.completed;
// checkbox not staying on current state ??
cb.addEventListener('click', function (e) {
if (e.target.type === 'checkbox') {
// todo.completed = e.target.value;
todo.completed = e.currentTarget.checked
e.target.parentElement.classList.toggle('checked');
}
});
return cb;
};
const buildDeleteButton = (todo) => {
const deleteButton = document.createElement("button");
deleteButton.className = "delete-button";
deleteButton.innerText = "x";
deleteButton.addEventListener("click", function (e) {
// duplicates children sometimes ??
const div = this.parentElement;
div.style.display = "none";
todos = todos.filter((item) => item.id !== todo.id);
});
return deleteButton;
};
// //------ Local Storage ------
function addToLocalStorage(todos) {}
function getFromLocalStorage() {}
// getFromLocalStorage();
This is the Javscript code part. In createTodoText, you can see the changes i've made. It's working according to what you want. What i've done is simple used 'span' instead of 'input'.
How about trying something like
if (todo.name.length) {itemText.size = todo.name.length;}

Local storage in JS not loading items problem

I have a problem with the local storage it seems the items are getting saved to local storage but I cannot make it work to load at start.
Any tips and advice much appreciated.
I am posting the code below.
const input = document.getElementById('input');
const list = document.getElementById('list');
const addButton = document.getElementById('addButton');
const completed = document.getElementById("completed");
let LIST;
let id;
let loadSTORAGE = localStorage.getItem("STORAGE");
if (loadSTORAGE) {
LIST = JSON.parse(loadSTORAGE);
id = LIST.length;
loadList(LIST);
} else {
LIST = [];
id = 0;
}
function loadList() {
LIST.forEach(function() {
addTask();
});
}
addButton.addEventListener("click", addTask);
input.addEventListener("keyup", function(event) {
(event.keyCode === 13 ? addTask() : null)
})
function addTask() {
const newTask = document.createElement("li");
const delBtn = document.createElement("button");
const checkBtn = document.createElement("button");
delBtn.innerHTML = "<button>Reset</button>"
checkBtn.innerHTML = "<button>Done</button>"
if (input.value !== "") {
newTask.textContent = input.value;
list.appendChild(newTask);
newTask.appendChild(checkBtn);
newTask.appendChild(delBtn);
LIST.push({
name: input.value,
id: id,
});
id++
input.value = "";
console.log(LIST);
localStorage.setItem("STORAGE", JSON.stringify(LIST));
}
checkBtn.addEventListener("click", function() {
const parent = this.parentNode
parent.remove();
completed.appendChild(parent);
});
delBtn.addEventListener("click", function() {
const parent = this.parentNode
parent.remove();
});
}
You need to break out the logic of building the item and getting the value. Something like the following where the addTask just makes sure there is input and calls a method that builds an item. Now with the localstorage call, you can call just the code that builds the item.
const input = document.getElementById('input');
const list = document.getElementById('list');
const addButton = document.getElementById('addButton');
const completed = document.getElementById("completed");
const loadSTORAGE = localStorage.getItem("STORAGE");
const LIST = loadSTORAGE ? JSON.parse(loadSTORAGE) : [];
let id = LIST.length;
loadList(LIST);
function loadList() {
LIST.forEach(function(data) {
addTaskElement(data);
});
}
function addTask() {
if (input.value !== "") {
cons newItem = {
name: input.value,
id: id,
};
LIST.push(newItem);
id++;
localStorage.setItem("STORAGE", JSON.stringify(LIST));
input.value = "";
addTaskElement(newItem);
}
}
function addTaskElement(data) {
const newTask = document.createElement("li");
const delBtn = document.createElement("button");
const checkBtn = document.createElement("button");
delBtn.textContent = "Reset"
checkBtn.textContent = "Done"
newTask.textContent = data.name;
newTask.appendChild(checkBtn);
newTask.appendChild(delBtn);
list.appendChild(newTask);
}

Set time interval on actions JS (Await, setTimeout Or setinterval )

We have more than 30 inputs in our HTML file, (name,adresse,phone....) on diferent pages
the script in the chrome extension autocomplete all inputs one after one, in one time,
My question is how to make a function whait for the action beforr.
set the value of each input one after one but with interval of 500ms.
function setById(id,valeur ){
setTimeout(()=>{
var ev = new Event('input');
if (document.getElementById(id)) {
Elem = document.getElementById(id) ? document.getElementById(id) : null
Elem.value =valeur;
Elem.dispatchEvent(ev);
}else{
console.log('L"element ' + id + ' introuvable, pour valeur ==> '+ valeur);
}
},500);
}
///////////////////////////////////////
// immatriculation
const immatriculation = setById('immatriculation',matricule.replaceAll('-',''));
// codePostalGarage
const codePostalGarage = setById('codePostalGarage',setData__.station_cp_n);
// villeGarage
const villeGarage = setById('villeGarage',setData__.station_ville_n);
Thank you Codeurs,
Try something like this
// dummy data
const matricule = "x-x-x"
const setData__ = {
station_cp_n: "x",
station_ville_n : "y"
}
// object from your statements
const values = [
{ 'immatriculation': matricule.replaceAll('-', '') },
{ 'codePostalGarage': setData__.station_cp_n },
{ 'villeGarage': setData__.station_ville_n }
];
cnt = 0;
const setById = () => {
const ev = new Event('input');
const [id, valeur] = Object.entries(values[cnt])[0]; // destruct the element
if (document.getElementById(id)) {
Elem = document.getElementById(id) ? document.getElementById(id) : null
Elem.value = valeur;
Elem.dispatchEvent(ev);
} else {
console.log('LĀ“element ' + id + ' introuvable, pour valeur ==> ' + valeur);
}
cnt++;
if (cnt < values.length) setTimeout(setById, 500); // stop if finished
}
setById(); // start it

How do I get items from localStorage and display in my UI?

This is what I have tried. It works with just a small issue. Anytime I add a new item to the localStorage it multiplies the items when displaying it until I refresh the page
const displayStorage = () => {
let values = [],
keys = Object.keys(localStorage),
i = keys.length;
while (i--) {
if (keys[i] === 'theme') continue;
values.push(JSON.parse(localStorage.getItem(keys[i])));
}
values.reverse();
return values.forEach(obj => showNotes(obj));
};
e.g let's say I have 123 stored and I want to add 4. It returns 1231234 instead of just 1234
This is the function that handles the UI display
const showNotes = ({ id, post, date }) => {
const noteSection = document.createElement('div');
noteSection.classList.add('notes-container');
const notes = document.createElement('article');
notes.classList.add('single-note');
notes.textContent = post.substring(0, 100);
const viewMore = document.createElement('a');
viewMore.classList.add('view-more');
viewMore.textContent = '...';
viewMore.setAttribute('title', 'View more');
viewMore.addEventListener('click', e => {
e.preventDefault();
if (notes.textContent.length <= 110) {
notes.textContent = post;
notes.appendChild(viewMore);
viewMore.setAttribute('title', 'View less');
} else {
notes.textContent = post.substring(0, 100);
notes.appendChild(viewMore);
viewMore.setAttribute('title', 'View more');
}
});
const noteActions = document.createElement('span');
noteActions.classList.add('note-actions');
const deleteLink = document.createElement('a');
deleteLink.textContent = 'Delete';
deleteLink.setAttribute('data-id', `${id}`);
deleteLink.addEventListener('click', deleteNote);
const notesDate = document.createElement('aside');
notesDate.classList.add('note-date');
notesDate.textContent = date;
noteActions.appendChild(deleteLink);
notes.appendChild(viewMore);
notes.appendChild(noteActions);
noteSection.appendChild(notesDate);
noteSection.appendChild(notes);
document.querySelector('.notes').appendChild(noteSection);
};
This is the function to save
notesForm.addEventListener('submit', e => {
e.preventDefault();
const save = (sid, spost, sdate) => {
const obj = { id: sid, post: spost, date: sdate };
localStorage.setItem(`${sid}`, JSON.stringify(obj));
};
save(generateId(), post.value, dateFormat());
displayStorage();
});
its a simple solution but may be useful for someone,
just clear items from UI, and again display them from localstorage, this will show the old and new items from localstorage.

Modify payment lines pos odoo 8

someone have any idea how i should modify the payment-lines in the POS,I want to add a type of credit card(like a many2one, I did it) but every time I add a line my option change to the first and also when the order is finished not save the value in pos.order -> statement_id.
enter image description here
here is my code:
function POS_CashRegister (instance, local) {
var pos = instance.point_of_sale;
var _t = instance.web._t;
var QWeb = instance.web.qweb;
var round_pr = instance.web.round_precision
const ParentOrder = pos.Order;
pos.PosModel.prototype.models.push({ //loaded model
model: 'pos.credit.card',
fields: ['id', 'name'],
domain: [['pos_active','=',true]],
loaded: function(self,credit_cards){ //pass parameters
self.credit_cards = credit_cards;
},
});
pos.PaymentScreenWidget = pos.PaymentScreenWidget.extend({
validate_order: function(options) {
var self = this;
var currentOrder = self.pos.get('selectedOrder');
var plines = currentOrder.get('paymentLines').models;
for (var i = 0; i < plines.length; i++) {
if(plines[i].cashregister.journal_id[1] === 'Tarjeta de Credito (PEN)')
{
var value = plines[i].node.firstElementChild.nextElementSibling.nextElementSibling.firstElementChild.value;
plines[i].set_credit_card(parseInt(value));
//console.log(plines[i].node.firstElementChild.nextElementSibling.nextElementSibling.firstElementChild.value);
//plines[i].node
}
}
console.log(currentOrder);
self._super(options);
},
render_paymentline: function (line) {
var self = this;
if(line.cashregister.journal_id[1] !== 'Tarjeta de Credito (PEN)'){
if (line.cashregister.currency[1] !== 'USD') {
return this._super(line);
} else {
var el_html = openerp.qweb.render('Paymentline', {widget: this, line: line});
el_html = _.str.trim(el_html);
var el_node = document.createElement('tbody');
el_node.innerHTML = el_html;
el_node = el_node.childNodes[0];
el_node.line = line;
el_node.querySelector('.paymentline-delete')
.addEventListener('click', this.line_delete_handler);
el_node.addEventListener('click', this.line_click_handler);
var sourceInput = el_node.querySelector('.source-input');
var convertedInput = el_node.querySelector('.converted-input');
sourceInput.addEventListener('keyup', function (event) {
el_node.line.set_usd_amount(event.target.value);
convertedInput.value = el_node.line.get_amount_str();
});
line.node = el_node;
return el_node;
}
}else {
return this._super(line);
}
},
});
pos.Paymentline = pos.Paymentline.extend({
initialize: function(attributes, options) {
this.amount = 0;
this.cashregister = options.cashregister;
this.name = this.cashregister.journal_id[1];
this.selected = false;
this.credit_card = false;
this.pos = options.pos;
},
set_credit_card: function(value){
this.credit_card = value;
this.trigger('change:credit_card',this);
},
get_credit_card: function(){
return this.credit_card;
},
export_as_JSON: function(){
return {
name: instance.web.datetime_to_str(new Date()),
statement_id: this.cashregister.id,
account_id: this.cashregister.account_id[0],
journal_id: this.cashregister.journal_id[0],
amount: this.get_amount(),
credit_card_id: this.get_credit_card(),
};
},
});
}
any suggestions?
You can create 2 journals here too. One for visa and another for master If you don't want that drop down there. Another way is you have to store selected option in a variable and then print that variable in front.
To store selected option initially assigned ids to each values of option and after then while validating order you can get that id of that field and from that id you can get your value. By this way also you can do that.

Categories

Resources