I am building a checkbox filter, which stores the clicked checkbox value in an array. After that, the computed data should update but I am always getting undefined.
The Data Structure:
Casino {
brand_tags {
Brand_Tag_Name
}
}
Computed:
computed: {
filteredCasinos: function() {
return this.casinos.forEach(casino => {
return casino.brand_tags.filter(brandTag => {
return this.filteredCategories.includes(brandTag.Brand_Tag_Name)
})
})
}
},
HTML (But that is working fine, I guess)
<label for="Featured">Featured Casinos
<input type="checkbox" v-model="filteredCategories" value="Featured">
</label>
<label for="Featured">Big Brands
<input type="checkbox" v-model="filteredCategories" value="Big Brand">
</label>
<label for="Featured">New Casinos
<input type="checkbox" v-model="filteredCategories" value="New Casino">
</label>
<label for="Featured">Pay n Play
<input type="checkbox" v-model="filteredCategories" value="Pay N Play">
</label>
<label for="Featured">Trusted Casinos
<input type="checkbox" v-model="filteredCategories" value="Trusted Casino">
</label>
It happens because return this.casinos.forEach returns undefined.
{ filteredCasinos: function() {
return this.casinos.filter(casino => {
return !!casino.brand_tags.find(brandTag => {
return this.filteredCategories.includes(brandTag.Brand_Tag_Name)
})
})
}
Related
I have a react component that contains a div with a conditional visibility. The component represents the page of a specific product on an ecommerce. The users can give their opinions once. The div with the conditional visibility contains a textarea to write this opinion. But it should only be visible if the user hasn't written a review yet. This decision must be taken before loading the component. How do I do that?
This is the component:
import Axios from "axios";
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import NavbarHome from "./NavbarHome";
function Product() {
//Visivility of the form
let visibility = false;
useEffect(() => {
Axios.get("http://localhost:3001/review").then((response) => {
if (response.data.length === 0) {
visibility = true;
}
});
}, []);
const idprod = useParams();
//POST of the review
function handleSubmit(event) {
event.preventDefault();
let info = {
message: event.target.review.value,
rating: event.target.stars.value
};
if (!info.message || !info.rating) {
if (!info.message) {
alert("You haven't witten a review");
} else if (!info.rating) {
alert("You haven't give any stars");
}
} else {
Axios.post("http://localhost:3001/review", {
message: info.message,
rating: info.rating,
id_prod: idprod
}).then((response) => {
if (response.data.err) {
alert("You have already written a review for this product");
}
});
}
}
return (
<div>
<NavbarHome />
<div className="container-fluid" id="container-producto">
<div className="row">
<div className="col-sm-6 bloque-description-product">
<h2>Example</h2>
<p>Example</p>
<p>Example</p>
<p>Example</p>
</div>
</div>
<h4>Opinions</h4>
<div className="container-opinions">
{visibility ? (
<form onSubmit={handleSubmit}>
<p className="clasification">
<input id="radio1" type="radio" name="stars" value="5" />
<label htmlFor="radio1">★</label>
<input id="radio2" type="radio" name="stars" value="4" />
<label htmlFor="radio2">★</label>
<input id="radio3" type="radio" name="stars" value="3" />
<label htmlFor="radio3">★</label>
<input id="radio4" type="radio" name="stars" value="2" />
<label htmlFor="radio4">★</label>
<input id="radio5" type="radio" name="stars" value="1" />
<label htmlFor="radio5">★</label>
</p>
<textarea
name="review"
placeholder="Leave your review..."
></textarea>
<input type="submit"></input>
</form>
) : (
<div></div>
)}
</div>
</div>
</div>
);
}
export default Product;
The div with the conditional visibility is container-opinions.
I've already tried using onLoad on that container, but it is not working.
Any ideas?
You should change let variable with react state
import Axios from "axios";
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import NavbarHome from "./NavbarHome";
function Product() {
const [visibility, setVisibility] = useState(false)
useEffect(() => {
Axios.get("http://localhost:3001/review").then((response) => {
if (response.data.length === 0) {
setVisibility(true);
}
});
}, []);
const idprod = useParams();
//POST of the review
function handleSubmit(event) {
event.preventDefault();
let info = {
message: event.target.review.value,
rating: event.target.stars.value
};
if (!info.message || !info.rating) {
if (!info.message) {
alert("You haven't witten a review");
} else if (!info.rating) {
alert("You haven't give any stars");
}
} else {
Axios.post("http://localhost:3001/review", {
message: info.message,
rating: info.rating,
id_prod: idprod
}).then((response) => {
if (response.data.err) {
alert("You have already written a review for this product");
}
});
}
}
return (
<div>
<NavbarHome />
<div className="container-fluid" id="container-producto">
<div className="row">
<div className="col-sm-6 bloque-description-product">
<h2>Example</h2>
<p>Example</p>
<p>Example</p>
<p>Example</p>
</div>
</div>
<h4>Opinions</h4>
<div className="container-opinions">
{visibility ? (
<form onSubmit={handleSubmit}>
<p className="clasification">
<input id="radio1" type="radio" name="stars" value="5" />
<label htmlFor="radio1">★</label>
<input id="radio2" type="radio" name="stars" value="4" />
<label htmlFor="radio2">★</label>
<input id="radio3" type="radio" name="stars" value="3" />
<label htmlFor="radio3">★</label>
<input id="radio4" type="radio" name="stars" value="2" />
<label htmlFor="radio4">★</label>
<input id="radio5" type="radio" name="stars" value="1" />
<label htmlFor="radio5">★</label>
</p>
<textarea
name="review"
placeholder="Leave your review..."
></textarea>
<input type="submit"></input>
</form>
) : (
<div></div>
)}
</div>
</div>
</div>
);
}
export default Product;
You'll want to use the useState react hook to keep track of the visibility in a way your app can react to:
import Axios from "axios";
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import NavbarHome from "./NavbarHome";
function Product() {
//Visivility of the form
// THIS NEEDS TO BE useState
const [visibility, setVisibility] = useState(false)
useEffect(() => {
Axios.get("http://localhost:3001/review").then((response) => {
if (response.data.length === 0) {
// Use setVisibility to update the state
setVisibility(true);
}
});
}, []);
const idprod = useParams();
//POST of the review
function handleSubmit(event) {
event.preventDefault();
let info = {
message: event.target.review.value,
rating: event.target.stars.value
};
if (!info.message || !info.rating) {
if (!info.message) {
alert("You haven't witten a review");
} else if (!info.rating) {
alert("You haven't give any stars");
}
} else {
Axios.post("http://localhost:3001/review", {
message: info.message,
rating: info.rating,
id_prod: idprod
}).then((response) => {
if (response.data.err) {
alert("You have already written a review for this product");
}
});
}
}
return (
<div>
<NavbarHome />
<div className="container-fluid" id="container-producto">
<div className="row">
<div className="col-sm-6 bloque-description-product">
<h2>Example</h2>
<p>Example</p>
<p>Example</p>
<p>Example</p>
</div>
</div>
<h4>Opinions</h4>
<div className="container-opinions">
{visibility ? (
<form onSubmit={handleSubmit}>
<p className="clasification">
<input id="radio1" type="radio" name="stars" value="5" />
<label htmlFor="radio1">★</label>
<input id="radio2" type="radio" name="stars" value="4" />
<label htmlFor="radio2">★</label>
<input id="radio3" type="radio" name="stars" value="3" />
<label htmlFor="radio3">★</label>
<input id="radio4" type="radio" name="stars" value="2" />
<label htmlFor="radio4">★</label>
<input id="radio5" type="radio" name="stars" value="1" />
<label htmlFor="radio5">★</label>
</p>
<textarea
name="review"
placeholder="Leave your review..."
></textarea>
<input type="submit"></input>
</form>
) : (
<div></div>
)}
</div>
</div>
</div>
);
}
export default Product;
I am using checkboxes to behave like radio buttons but the one behavior that I want to fix is the ability to keep the checkbox checked until the second one is checked (which will then uncheck the first one). I don't want the ability to deselect the checkbox by clicking on it again, just to hit the "none" checkbox to deselect the one below.
Referring to the image above, the label selects the checkbox as well. Once the checkbox is selected and is tapped on again, it goes back to the none checkbox on the left. Maybe radio buttons would be better, but I like checkboxes more. Here's the code:
<label :for="'none-'+product.id"
class="none addon_label"
:class="{'addon_selected': !selected}"
>
<input class=""
type="checkbox"
:id="'none-'+product.id"
:true-value="false"
:false-value="true"
:value="false"
v-model="selected"
checked
/>
<span class="checkmark addon_checkbox"></span>
<div class="v-center">None</div>
</label>
<label :for="'product-'+product.id"
class="is_flex addon_label"
:class="{'addon_selected': selected}"
:data-product-id="product.id"
>
<div class="checkbox-container">
<input class=""
type="checkbox"
:true-value="true"
:false-value="false"
:id="'product-'+product.id"
v-model="selected"/>
<span class="checkmark addon_checkbox"></span>
To do this, you just need to have two v-models, one for each button, and to create a function that when one of the two buttons changes, each of the values takes its opposite value.
Then, in order to avoid deselection by clicking on its own button, you use :disabled= with the reference of your button
Vue.js 3 with Composition
<script setup lang="ts">
import { ref } from "vue";
let selectedNone = ref(true);
let selectedChoice = ref(false);
function selectOption() {
selectedNone.value = !selectedNone;
selectedChoice.value = !selectedChoice;
}
</script>
<template>
<label>
<input
type="checkbox"
:value="false"
v-model="selectedNone"
:disabled="selectedNone"
#click="selectOption"
/>
<span>None</span>
</label>
<label >
<input
type="checkbox"
v-model="selectedChoice"
:disabled="selectedChoice"
#click="selectOption"
/>
<span>Choice</span>
</label>
</template>
You can use watch to check if the value of the checkbox has changed, and then either select all or deselect all, based on that.
Here's a quick demo
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => {
return {
options: {
check1: null,
check2: null,
check3: null,
},
check1: null,
check2: null,
check3: null,
deselect: null,
};
},
watch: {
deselect(isDeselected) {
if (isDeselected) {
this.options.check1 = false;
this.options.check2 = false;
this.options.check3 = false;
}
},
options() {
console.log("Change");
},
...["options.check1", "options.check2", "options.check3"].reduce(function (
acc,
currentKey
) {
acc[currentKey] = function (newValue) {
if (newValue) this.deselect = false;
};
return acc;
},
{}),
},
})
<script src="https://unpkg.com/vue#2.x/dist/vue.js"></script>
<div id="app">
<label for="check1">Check 1</label>
<input type="checkbox" v-model="options.check1" id="check1" />
<br />
<label for="check2">Check 2</label>
<input type="checkbox" v-model="options.check2" id="check2" />
<br />
<label for="check3">Check 3</label>
<input type="checkbox" v-model="options.check3" id="check3" />
<br />
<label for="deselect-check">Deselect All</label>
<input type="checkbox" v-model="deselect" id="deselect-check" />
</div>
Check-all feature stops working when I try to get value of each checkbox in an array using v-model. I read lot of questions on different portals including stackoverflow, people are saying that v-model doesn't work with :checked attribute which I understand but could not find a solution / alternate code to make it work.
The 1st code that I tried was to select all checkboxes using the 1st checkbox. This works well. Code below:
new Vue({
el: "#app",
data: {
selectAll:false
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<label>
<input type="checkbox" v-model="selectAll">
Select all
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 1">
Item 1
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 2">
Item 2
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 3">
Item 3
</label>
</div>
The 2nd code that I tried was to get value of each checkbox in an array but in this case 'select all' automatically stops working. Code below:
new Vue({
el: "#app",
data: {
selectAll:false,
eachCheckbox: [],
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<label>
<input type="checkbox" v-model="selectAll">
Select all
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 1" v-model="eachCheckbox">
Item 1
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 2" v-model="eachCheckbox">
Item 2
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 3" v-model="eachCheckbox">
Item 3
</label>
<br>
Selected checkbox values: {{eachCheckbox}}
</div>
I don't know how to make this work. Can someone help please?
Use Vue.set to create objects in the checkbox array once an API call completes.
This shows a simulated async api call which takes 2.5 seconds to complete.
new Vue({
el: '#app',
data () {
return {
loading: false,
checkall: false,
checkboxes: []
}
},
methods: {
toggleAll () {
this.checkall = !this.checkall
this.checkboxes.forEach(c => {
c.checked = this.checkall
})
}
},
watch: {
checkboxes: {
deep: true,
handler: function () {
this.checkall = this.checkboxes.every(c => c.checked)
}
}
},
mounted () {
// simulate an async api call which takes 2.5 seconds to complete
this.loading = true
setTimeout(() => {
Array.from(Array(3), (c, i) => ({ checked: false, text: `Option ${i + 1}` })).forEach((c, i) => {
Vue.set(this.checkboxes, i, c)
})
this.loading = false
}, 2500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="checkbox" #click="toggleAll" v-model="checkall"/> Check All<br/>
<div v-for="(c, i) in checkboxes" :key="i">
<input type="checkbox" v-model="c.checked"/>{{ c.text }}<br/>
</div>
<p v-if="!loading">Checked: {{ checkboxes.filter(c => c.checked).map(c => c.text).join(',') }}</p>
<p v-else>Fetching data...</p>
</div>
i had faced the same problem before and i didn't find a good solution, but i had tried something like the following :
new Vue({
el: "#app",
data: {
selectAll: false,
eachCheckbox: [],
},
methods: {
selectAllItems() {
this.selectAll ? this.eachCheckbox = ["Item 1", "Item 2", "Item 3"] : this.eachCheckbox = [];
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<label>
<input type="checkbox" v-model="selectAll" #change="selectAllItems">
Select all
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 1" v-model="eachCheckbox">
Item 1
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 2" v-model="eachCheckbox">
Item 2
</label>
<br>
<label>
<input type="checkbox" :checked="selectAll" value="Item 3" v-model="eachCheckbox">
Item 3
</label>
<br> Selected checkbox values: {{eachCheckbox}}
</div>
I am not able to click or select on any of my radio buttons. Can someone help me out how to work with radio buttons in react?
I tried removing e.preventDefault() but that didn't help either.
Here's what my code looks like:
File 1:
this.state = {
fields: {
gender: ''
}
}
fieldChange(field, value) {
this.setState(update(this.state, { fields: { [field]: { $set: value } } }));
}
<Form
fields={this.state.fields}
onChange={this.fieldChange.bind(this)}
onValid={() => handleSubmit(this.state.fields)}
onInvalid={() => console.log('Error!')}
/>
File 2:
render() {
const { fields, onChange, onValid, onInvalid, $field, $validation } = this.props;
return (
{/* Gender */}
<div id={styles.genderField} className={`form-group ${styles.formGroup} ${styles.projName}`}>
<label className="col-sm-2 control-label">Gender:</label>
<div className="col-sm-10">
<label className="radio-inline">
<input type="radio" name="gender" id="male"
checked={fields.gender === "Male"}
value={fields.gender} {...$field( "gender", e => onChange("gender", e.target.value)) } />
Male
</label>
<label className="radio-inline">
<input type="radio" name="gender" id="female"
checked={fields.gender === "Female"}
value={fields.gender} {...$field( "gender", e => onChange("gender", e.target.value)) } />
Female
</label>
</div>
</div>
<div className={`modal-footer ${styles.modalFooter}`}>
<button
className={`btn btn-primary text-white ${styles.saveBtn}`}
onClick={e => {
e.preventDefault();
this.props.$submit(onValid, onInvalid);
}}
>
Save
</button>
</div>
)
}
That's not how the docs handle onChange events. https://reactjs.org/docs/handling-events.html
You need to provide the full code to be able to help with that particular component.
Check out this working example: https://stackblitz.com/edit/react-radiobtns
class App extends Component {
constructor(props) {
super(props);
this.state = {selectedOption: 'option1'};
// This binding is necessary to make `this` work in the callback
this.handleOptionChange = this.handleOptionChange.bind(this);
}
handleOptionChange(changeEvent) {
this.setState({
selectedOption: changeEvent.target.value
});
}
render() {
return (
<form>
<label>
<input
onChange={this.handleOptionChange}
type="radio" value="option1"
checked={this.state.selectedOption === 'option1'}
name="radio1"/>
Option 1
</label>
<label>
<input
onChange={this.handleOptionChange}
checked={this.state.selectedOption === 'option2'}
type="radio"
value="option2"
name="radio1"/>
Option 2
</label>
<label>
<input
onChange={this.handleOptionChange}
checked={this.state.selectedOption === 'option3'}
type="radio"
value="option3"
name="radio1"/>
Option 3
</label>
</form>
);
}
}
I've something weird going on here with Angular.
I have a details view with an edit button. When I press the edit button, I pass the object to the edit view. On the edit form there are a few dropdown boxes. The first time I click the edit button, everything loads well. All the dropdowns has the correct value selected. When I press cancel on the edit form, I get back to the details view. When I do nothing and press the Edit button again on the details view, the dropdowns don't have selected values at all! However the dropdowns do have items.
How is this possible? I didn't do anything with the data!
The details view and edit view are both directives:
In the template of customerDetails:
<div>
Here all the details of the customer
<button ng-click="ShowCustomerEditForm()">Edit</button>
</div>
<customer-edit
visible="showCustomerForm"
customer = "customer">
</customer-edit>
directive customer-edit:
app.directive("customerEdit", function (CustomerService, CountryService) {
return {
restrict: 'E',
templateUrl: '/Customer/Add',
scope: {
customer: '=',
visible: '=',
onCustomerSaved: '&'
},
link: function (scope, element, attributes) {
CustomerService.getAllAcademicDegrees().then(function (response) {
scope.academicDegrees = response;
});
CustomerService.getAllGenders().then(function (response) {
scope.genders = response;
});
CountryService.getAllCountries().then(function (response) {
scope.countries = response;
});
scope.$watch('customer', function (newValue) {
if (newValue && newValue.Id > 0) {
scope.customer.originalCustomer = {};
angular.copy(scope.customer, scope.customer.originalCustomer);
}
});
scope.customerFormSubmit = function () {
if (scope.customer.Id > 0) {
editCustomer();
}
else {
addCustomer();
}
}
scope.hideCustomerForm = function (restoreOriginal) {
if (restoreOriginal) {
angular.copy(scope.customer.originalCustomer, scope.customer);
}
scope.visible = false;
}
// Private functions
function editCustomer() {
var editCustomer = createCustomer(scope.customer);
editCustomer.Id = scope.customer.Id;
CustomerService.editCustomer(editCustomer).then(editCustomerSucceeded);
scope.hideCustomerForm(false);
}
function editCustomerSucceeded(response) {
var uneditedCustomer = _.findWhere(scope.customers, { Id: response.Id });
angular.copy(response, uneditedCustomer);
}
function addCustomer() {
var newCustomer = createCustomer(scope.customer);
CustomerService.addCustomer(newCustomer).then(function (response) {
scope.onCustomerSaved({ customer: response });
scope.hideCustomerForm(false);
});
}
}
}
});
I am trying to fix this for 6 hours now and I just don't understand it and I'm getting very desperate.. I just don't know how to fix this and what's causing this. I really hope someone can help me..
edit:
The customer edit html:
<div class="add-edit-container">
<div class="titleBox">
{{ customerFormData.title }}
<span class="close" title="Annuleren en sluiten" ng-click="hideCustomerForm(true)">×</span>
</div>
<div class="border">
<form id="frmAddCustomer" name="form" novalidate data-ng-submit="customerFormSubmit()">
<div>
<fieldset>
<legend>Identificatie</legend>
<label>Code:</label>
<input type="text" data-ng-model="customer.Code" />
<label>Geslacht:</label>
<label style="float: left;margin-right: 3px;" data-ng-repeat="gender in genders" data-ng-hide="$first">
<input type="radio" name="gender" data-ng-value="gender" data-ng-model="customer.Gender" />{{gender.Description}}
</label>
<div class="clear-float"/>
<label>Titel:</label>
<select data-ng-model="customer.AcademicDegree" data-ng-options="degree.Description for degree in academicDegrees"></select>
<label>Initialen:</label>
<input type="text" required data-ng-model="customer.Initials" />
<label>Voornaam: </label>
<input type="text" required data-ng-model="customer.FirstName" />
<label>Tussenvoegsel:</label>
<input type="text" data-ng-model="customer.MiddleName" />
<label>Achternaam:</label>
<input type="text" required data-ng-model="customer.LastName" />
<label>Geboortedatum:</label>
<input type="text" datepicker="01-01-1950" required data-ng-model="customer.BirthDate" />
<label>BSN:</label>
<input type="text" required data-ng-model="customer.BSNNo" />
<label>Identificatienummer:</label>
<input type="text" required data-ng-model="customer.IdCardNo" />
</fieldset>
<fieldset>
<legend>Contact</legend>
<label>Straat:</label>
<input type="text" required data-ng-model="customer.Street" />
<label>Huisnummer + toevoeging:</label>
<input type="text" required data-ng-model="customer.HouseNumber" style="width: 50px"/>
<input type="text" data-ng-model="customer.HouseNumberAddition" style="width: 50px"/>
<label>Postcode:</label>
<input type="text" required data-ng-model="customer.ZipCode" />
<label>Woonplaats:</label>
<input type="text" required data-ng-model="customer.City" />
<label>Telefoonnummer overdag:</label>
<input type="text" required data-ng-model="customer.DayPhone" />
<label>Telefoon anders:</label>
<input type="text" data-ng-model="customer.PhoneOther" />
<label>E-mailadres:</label>
<input type="email" required data-ng-model="customer.EmailAddress" />
<label>Bedrijfsnaam:</label>
<input type="text" data-ng-model="customer.CompanyName" />
<label>Land:</label>
<select data-ng-model="customer.Country" data-ng-options="country.Description for country in countries"></select>
</fieldset>
<fieldset>
<legend>Afwijkend postadres</legend>
<label>Straat:</label>
<input type="text" data-ng-model="customer.OtherStreet" placeholder="leeg indien niet van toepassing" />
<label>Huisnummer + toevoeging:</label>
<input type="text" data-ng-model="customer.OtherHouseNumber" style="width: 50px"/>
<input type="text" data-ng-model="customer.OtherHouseNumberAddition" style="width: 50px"/>
<label>Postcode:</label>
<input type="text" data-ng-model="customer.OtherZipCode" placeholder="leeg indien niet van toepassing" />
<label>Woonplaats:</label>
<input type="text" data-ng-model="customer.OtherCity" placeholder="leeg indien niet van toepassing" />
<input type="hidden" data-ng-model="customer.OtherAddressId" />
</fieldset>
</div>
<div class="button-box">
<input type="submit" value="Opslaan" class="button" />
Annuleren
</div>
</form>
</div>
</div>
I can answer why this problem is happening.
The problem is:
angular.copy(scope.customer.originalCustomer, scope.customer);
angular.copy does a deep copy. After the above call, scope.customer.Country, for instance, is a brand new object, it's not an element of scope.countries anymore. Therefore, the select directives lost track of the selected values.