Get a result when an option value selection is changed in javascript - javascript

I'm trying to get a different value when the value of an option is changed. I have this code, but when I change my selection, the result is not changing.
let cantidad1 = document.getElementById("cantidad");
let moneda1 = document.getElementById("cambio").value;
if (moneda1 === "cup") {
tipodemoneda = 97;
} else if (moneda1 === "mlc") {
tipodemoneda = 0.89;
}
let tasadecambio = tipodemoneda;
let resultado1 = document.getElementById("resultado")
cantidad1.addEventListener("change", () => {
resultado1.value = parseFloat(tasadecambio) * parseFloat(cantidad1.value)
})

Listen for input events instead of change events. Change events only fire for a text input or text area when the the element lose focus (1)
let cantidad1 = document.getElementById("cantidad");
let moneda1 = document.getElementById("cambio").value;
if (moneda1 === "cup") {
tipodemoneda = 97;
} else if (moneda1 === "mlc") {
tipodemoneda = 0.89;
}
let tasadecambio = tipodemoneda;
let resultado1 = document.getElementById("resultado")
cantidad1.addEventListener("input", () => {
resultado1.value = parseFloat(tasadecambio) * parseFloat(cantidad1.value)
})
<input id="cantidad">
<input id="cambio" value="cup">
<input id="resultado">
Also the way the code is right now, moneda1 only gets set once. You should move it into the event handler.
let cantidad1 = document.getElementById("cantidad");
let moneda1 = document.getElementById("cambio");
let resultado1 = document.getElementById("resultado")
let tipodemoneda; // Put this to stop it from being a global variable (window.tipodemoneda)
function updateResultado() { // Handler in its own function
if (moneda1.value === "cup") { // Check mondedal.value since it can change
tipodemoneda = 97;
} else if (moneda1.value === "mlc") {
tipodemoneda = 0.89;
}
let tasadecambio = tipodemoneda;
resultado1.value = parseFloat(tasadecambio) * parseFloat(cantidad1.value)
}
cantidad1.addEventListener("input", updateResultado)
moneda1.addEventListener("change", updateResultado)
<input id="cantidad">
<select id="cambio">
<option value="mlc">mlc</option>
<option value="cup">cup</option>
</select>
<input id="resultado">

Related

I want to prevent being able to choose a number less than zero with e.target.value

I want to prevent negative values ( < 0) to be chosen on input field. Being "0" the lowest value available for the input field.
Here is the javascript and html code:
// Button functions
const minusButton = document.getElementById('minus');
const plusButton = document.getElementById('plus');
const inputField = document.getElementById('amount');
minusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue - 0.01;
});
plusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue + 0.01;
});
// Returning 0 when clearing input
const numInputs = document.querySelectorAll('input[type=number]')
numInputs.forEach(function(input) {
input.addEventListener('change', function(e) {
if (e.target.value == '') {
e.target.value = 0
}
})
})
<button class="input-btn" id="minus">−</button>
<button class="input-btn" id="plus">+</button>
<input class="input" type="number" value="0" id="amount"/>
Your code is almost correct.
In the minusButton event handler logic, you can enforce that the value never gets set to anything lower than 0.
Edit the input event handler to check for values lower than 0, not equal to it.
Note: the event handler you add to input to fire upon 'change' only gets executed when the user manually makes the change to the value of input box, and NOT when it gets changed by code (as you're doing through minusButton and plusButton). Since, the user clicks the button (and never interact with the input directly), the event happens on the button, not the input box.
You can give below code a try.
// Button functions
const minusButton = document.getElementById("minus");
const plusButton = document.getElementById("plus");
const inputField = document.getElementById("amount");
minusButton.addEventListener("click", (event) => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
// if less than 0, set to 0, else currentValue - 0.01
inputField.value = currentValue - 0.01 < 0 ? 0 : currentValue - 0.01;
});
plusButton.addEventListener("click", (event) => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue + 0.01;
});
// Returning 0 when clearing input
const numInputs = document.querySelectorAll('input[type="number"]');
numInputs.forEach((input) => {
input.addEventListener("change", function (e) {
if (e.target.value === "" || e.target.value < 0) {
e.target.value = 0;
}
});
});
If you were using a submit button and the input box was in a form element, you could have used the min attribute
<input class="input" type="number" value="0" id="amount" min="0" />
This would be the ideal front-end way of doing it.
You could use JavaScript too, but it can be disabled by the user.
You should, however, check this value (validation) when it gets submitted, before you use it because even this can be bypassed.
let newValue = currentValue - 0.01
if(newValue < 0) {
newValue = 0
}
inputField.value = newValue

Star Rating Js + html with symfony

I'm working on a project with symfony 4. I want to implement a star rating system. I display 5 stars in each row in a table. I have two problems, one is more important than the other.
So the first issue is that I want to be able to retrieve the value of the star I selected. If I select 5 stars, I want to get that value back in my entity controller.
The second issue is that, currently, let's say I have 5 items in my table, so 5 rows. Currently, if I select 5 stars in one row it's selected for all rows and I can't select another value anymore. So, it's global or something.
Here is the javascript I'm using:
<script>
const stars = document.querySelectorAll('.star');
let check = false;
stars.forEach(star => {
star.addEventListener('mouseover', selectStars);
star.addEventListener('mouseleave', unselectStars);
star.addEventListener('click', activeSelect);
})
function selectStars(e) {
const data = e.target;
const etoiles = priviousSiblings(data);
if (!check) {
etoiles.forEach(etoile => {
etoile.classList.add('hover');
})
}
}
function unselectStars(e) {
const data = e.target;
const etoiles = priviousSiblings(data);
if (!check) {
etoiles.forEach(etoile => {
etoile.classList.remove('hover');
})
}
}
function activeSelect(e) {
if (!check) {
check = true;
document.querySelector('.note').innerHTML = 'Note ' + e.target.dataset.note;
}
}
function priviousSiblings(data) {
let values = [data];
while (data === data.previousSibling) {
if (data.nodeName === 'I') {
values.push(data);
}
}
return values;
}
</script>
And Here is the twig.html I'm displaying:
<td>
<i class="star" data-note="1">★</i>
<i class="star" data-note="2">★</i>
<i class="star" data-note="3">★</i>
<i class="star" data-note="4">★</i>
<i class="star" data-note="5">★</i>
<i class="note">Note:</i>
</td>
I want to be able to retrieve the value once I made a selection, and to have a different selection for each row I have.
The problem is with the "mouseover" and "mouseleave" event handlers - selectStars and unselectStars. In "selectStars", you are adding the class to only one star. And in "unselectStars", you were not resetting, or applying the "remove" class method to other stars.
Anyway, here is how I have achieved what you are trying to do:
const ratings = document.querySelectorAll('.rating');
ratings.forEach(rating =>
rating.addEventListener('mouseleave', ratingHandler)
);
const stars = document.querySelectorAll('.rating .star');
stars.forEach(star => {
star.addEventListener('mouseover', starSelection);
star.addEventListener('mouseleave', starSelection);
star.addEventListener('click', activeSelect);
});
function ratingHandler(e) {
const childStars = e.target.children;
for(let i = 0; i < childStars.length; i++) {
const star = childStars.item(i)
if (star.dataset.checked === "true") {
star.classList.add('hover');
}
else {
star.classList.remove('hover');
}
}
}
function starSelection(e) {
const parent = e.target.parentElement
const childStars = parent.children;
const dataset = e.target.dataset;
const note = +dataset.note; // Convert note (string) to note (number)
for (let i = 0; i < childStars.length; i++) {
const star = childStars.item(i)
if (+star.dataset.note > note) {
star.classList.remove('hover');
} else {
star.classList.add('hover');
}
}
}
function activeSelect(e) {
const parent = e.target.parentElement
const childStars = parent.children;
const dataset = e.target.dataset;
const note = +dataset.note; // Convert note (string) to note (number)
for (let i = 0; i < childStars.length; i++) {
const star = childStars.item(i)
if (+star.dataset.note > note) {
star.classList.remove('hover');
star.dataset.checked = "false";
} else {
star.classList.add('hover');
star.dataset.checked = "true";
}
}
const noteTextElement = parent.parentElement.lastElementChild.children.item(0)
noteTextElement.innerText = `Note: ${note}`;
}
You might notice I have a .rating class component. This is a div which I have created to hold all these "stars". Here is a link to a codepen I have created. Feel free to play around with it.
And as a note, please provide codepen (or any other) demos so that we can debug a bit better and faster.
I hope the codepen link would help you solve your problem.

Can you use decrement/increment operator but skip 0 in JavaScript just like how continue works?

I have here a number counter code where it has increment and decrement buttons. Whenever you click a button, it does its job of incrementing and decrementing the value of the input.
// =number_counter
function decrement(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value--;
target.value = value;
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
function increment(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value++;
target.value = value;
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
const decrementButtons = document.querySelectorAll(
`button[data-action="decrement"]`
);
const incrementButtons = document.querySelectorAll(
`button[data-action="increment"]`
);
decrementButtons.forEach(btn => {
btn.addEventListener("click", decrement);
});
incrementButtons.forEach(btn => {
btn.addEventListener("click", increment);
});
This time, I wanted to skip 0 when clicking the buttons having the input value as either -1 or 1. Can I add a behavior such as continue; without the loop and just having increment/decrement operators?
Continue does't exist outside of the loops. The simplest solution for you is to add a condition inside increment/decrement where you would check if the current value is -1/1 and add additional logic in those cases :)
The solution was just to set the value = 1 or value = -1;
function decrement(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value--;
if (value == 0) {
value = -1;
target.value = value;
} else {
target.value = value;
}
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
function increment(e) {
const btn = e.target.parentNode.parentElement.querySelector(
'button[data-action="decrement"]'
);
const target = btn.nextElementSibling;
let value = Number(target.value);
value++;
if (value == 0) {
value = 1;
target.value = value;
} else {
target.value = value;
}
toggleRowClass(btn, value, ["bg-red-200", "item-returned"]);
}
Sorry I have missed it.

Splicing only one element when creating a new element

I'm trying to make it where when a user creates a widget, and then reloads the page (it'll appear because it's saved in localStorage) and then once you create another widget, I want to be able to delete the old widget before the page refreshes but it deletes the widget that the user clicked and the new widget.
Each time a new widget it created, it gets assigned a property name 'id' and the value is determined based on what is already in localStorage and it finds the next available (or not in use) id number. The widgets array also gets sorted from smallest id to largest id before setting it back to localStorage.
I've tried attaching a click listener for the delete button on the widget both when it's created and when the document is loaded. But that wasn't working.
Now i'm thinking I have to call a function with the id as its param to add a click listener to all the widgets that are appended to the document and when a new widget is created.
app.js:
function addRemoveListener(id) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
$(`#widget-${id} > span > .widget-clear`).click(() => {
for (let i = 0; i < localUi.widgets.length; i++) {
let thisWidget = `#widget-${id}`;
if (localUi.widgets[i].id == id) {
localUi.widgets.splice(i, 1)
}
$(thisWidget).remove();
console.log(localUi)
}
let newUi = JSON.stringify(localUi);
localStorage.setItem('ui', newUi);
})
}
widget.js:
static appendToDom(ui) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
for (let i = 0; i < localUi.widgets.length; i++) {
let widget = localUi.widgets[i];
let query = () => {
if (widget.type == 'humidity') {
return `${Math.floor(ui.weather.currently.humidity * 100)}`
} else if (widget.type == 'eye') {
return `${Math.floor(ui.weather.currently.visibility)}`
} else if (widget.type == 'windsock') {
return `${Math.floor(ui.weather.currently.windSpeed)}`
} else if (widget.type == 'pressure') {
return `${Math.floor(ui.weather.currently.pressure)}`
} else if (widget.type == 'uv-index') {
return `${ui.weather.currently.uvIndex}`
}
}
$('nav').after(`<div class="widget widget-${widget.size}" id="widget-${widget.id}">
<span>
<i class="material-icons widget-clear">clear</i>
<i class="material-icons widget-lock-open">lock_open</i>
<i class="material-icons widget-lock">lock_outline</i>
</span>
<div class="data-container">
<img src=${widget.image}>
<h1> ${widget.type}: ${query()} ${widget.unit} </h1>
</div>
</div>`)
$(`#widget-${widget.id}`).delay(1000 * i).animate({ opacity: 1 }, 1000);
$(`#widget-${widget.id}`).css({ left: `${widget.left}`, top: `${widget.top}`, 'font-size': `${widget.dimensions[2]}` })
$(`.widget`).draggable();
$(`#widget-${widget.id}`).css({ width: `${widget.dimensions[0]}`, height: `${widget.dimensions[1]}` })
addRemoveListener(i);
}
// this function is called earlier in the script when the user has selected
// which kind of widget they want
let makeWidget = () => {
let newWidget = new Widget(this.size, this.id, this.image, this.type, this.unit, this.dimensions);
saveWidget(newWidget);
addRemoveListener(this.id)
}
I have no problems with this until I delete an existing widget after I create a new one, and before refreshing.
You might have a problem with the id that is passed to your addRemoveListener function. It could be passing the same id for any widget so the loop will delete the UI because thisWidget is in the for loop. Try adding some console logging.
function addRemoveListener(id) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
$(`#widget-${id} > span > .widget-clear`).click(() => {
for (let i = 0; i < localUi.widgets.length; i++) {
let thisWidget = `#widget-${id}`;
if (localUi.widgets[i].id == id) {
localUi.widgets.splice(i, 1)
}
// Move this inside the if statement above.
$(thisWidget).remove();
console.log(localUi)
}
let newUi = JSON.stringify(localUi);
localStorage.setItem('ui', newUi);
})
}
or better yet, re-write it to continue if the id doesn't match
function addRemoveListener(id) {
let storageUi = localStorage.getItem('ui');
let localUi = JSON.parse(storageUi);
$(`#widget-${id} > span > .widget-clear`).click(() => {
for (let i = 0; i < localUi.widgets.length; i++) {
let thisWidget = `#widget-${id}`;
if (localUi.widgets[i].id !== id) {
continue;
}
localUi.widgets.splice(i, 1)
$(thisWidget).remove();
console.log(localUi)
}
let newUi = JSON.stringify(localUi);
localStorage.setItem('ui', newUi);
})
}

Illustrator JavaScript only works once - won't toggle

I'm writing a script which changes the colours of a stick-man's arms and legs. Once "he" is selected, it effectively just mirrors the colours:
//Declare and initialize variables
var msgType = "";
var app;
var docRef = app.activeDocument;
var testColor = docRef.swatches.getByName("CMYK Green");
var leftColor = docRef.swatches.getByName("LeftColor");
var rightColor = docRef.swatches.getByName("RightColor");
function sameColor(CMYKColor1, CMYKColor2) {
"use strict";
var isTheSameColor;
if ((CMYKColor1.cyan === CMYKColor2.cyan) && (CMYKColor1.magenta === CMYKColor2.magenta) && (CMYKColor1.yellow === CMYKColor2.yellow) && (CMYKColor1.black === CMYKColor2.black)) {
isTheSameColor = true;
} else {
isTheSameColor = false;
}
return isTheSameColor;
}
// check if a document is open in Illustrator.
if (app.documents.length > 0) {
var mySelection = app.activeDocument.selection;
var index;
// Loop through all selected objects
for (index = 0; index < mySelection.length; index += 1) {
// Switch left and right colours
if (sameColor(mySelection[index].strokeColor, leftColor.color)) {
mySelection[index].strokeColor = rightColor.color;
}
if (sameColor(mySelection[index].strokeColor, rightColor.color)) {
mySelection[index].strokeColor = leftColor.color;
}
if (sameColor(mySelection[index].fillColor, leftColor.color)) {
mySelection[index].fillColor = rightColor.color;
}
if (sameColor(mySelection[index].fillColor, rightColor.color)) {
mySelection[index].fillColor = leftColor.color;
}
}
}
It works, but it only works once (i.e. I can't toggle the change again). If I undo the change and try again it works again. Why is this?
After a lot of head-scratching / debugging it turns out that it was changing the CMYK values to be not quite the same (by a tiny fraction).
Changed the following:
if ((CMYKColor1.cyan === CMYKColor2.cyan) ...
to:
if ((Math.round(CMYKColor1.cyan) === Math.round(CMYKColor2.cyan)) ...
and it works fine now.

Categories