There was a need to add a drop-down list with a choice of accounts. The chosen value is processed through "event.target.value". This handler takes the value visible to the user, but I only need the 'key' value of the selected record where the stored "account.Id". I've tried get access to key, but it doesn't seem to work.
First experience with JS, so apologize in advance if the question is incorrect or elementary.
Page:
<select class="slds-select" name = "accountSelect" onchange={changeHandler2} >
<template for:each={allAccounts.data} for:item="account">
<option key={account.Id} value={account.Id}>{account.Name}</option>
</template>
</select>
Handler:
changeHandler(event) {
if (field === 'accountSelect') {
this.accountId = event.target.options[event.target.selectedIndex].getAttribute('key');
}
}
Did you tried to use the data to get it :
changeHandler(event) {
if (field === 'accountSelect') {
this.accountId = allAccounts.data.find(item => item.Id === event.target.value);
}
}
Related
I have an array of state which is controlled through a dropdown.
This is state held like:
const [finalselected, setfinalSelected] = useState([]);
When a submit button is clicked, I would like to confirm that an element does not already exist in the array, for example an individual cannot input "experience": "A similar role" 10 times into the array.
My current function does not stop additional elements coming if it is a duplicate:
const onSubmitFinalSelection = (val) => {
if (!finalselected.includes(selectedExperience)) {
//if finalselected does NOT include the element, then add in a new element
// setfinalSelected((prev) => [...prev, selectedExperience, inputfield]);
setfinalSelected((prevFinalSelection) => [
...prevFinalSelection,
{
//this is the dropdown
experience: selectedExperience,
//this is an input
inputfield,
},
]);
}
console.log(finalselected)
};
How would you re-write this?
Something like this? I don't think the includes function works with the selectedExperience as single parameter since the array contains objects.
const onSubmitFinalSelection = (val) => {
// If found, return
if (finalselected.some(x => x.experience === selectedExperience))
return;
setfinalSelected([...finalSelected, {
//this is the dropdown
experience: selectedExperience,
//this is an input
inputfield,
}])
console.log(finalsSlected)
};
Alerting if the element is already inside my array if not doing normal push.
let selectedValues = document.querySelector(".selectedValues");
let array = [];
function myFunction(option) {
option = option.value;
if (array.includes(option)) {
alert(option + " "+ "is already selected")
} else {
array.push(option);
}
selectedValues.textContent = array;
}
<textarea class="selectedValues" type="text"></textarea>
<select onchange="myFunction(this)" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
to automate CRUD functionality I need to select the 2nd item from a static drop down and the html is like
<select name="segment[segment_contact_id]" id="segment_segment_contact_id">
<option value="73082">Rita Basu</option>
<option value="73349">researcher user</option>
</select>
So by using cypress I am using the hardcoded value and my code is like
const segmentUser2 = 'researcher user'
const userValue2 = 73349
cy.get('select#segment_segment_contact_id')
.select(segmentUser2)
.should('have.value', userValue2)
I need suggestion because I don't like to use the hardcoded value instead I would like to use always the 2nd item from the drop down dynamically.
You could do something like this
Cypress.Commands.add(
'selectNth',
{ prevSubject: 'element' },
(subject, pos) => {
cy.wrap(subject)
.children('option')
.eq(pos)
.then(e => {
cy.wrap(subject).select(e.val())
})
}
)
Usage
cy.get('[name=assignedTo]').selectNth(2)
Here is #ItsNotAndy's way without the custom command.
cy.get('select#segment_segment_contact_id')
.children('option').eq(1)
.then($option => {
cy.wrap($option).parent().select($option.val())
})
As a function
function selectNth(selector, pos) {
cy.get(selector)
.children('option').eq(pos)
.then($option => {
cy.wrap($option).parent().select($option.val())
})
}
selectNth('select#segment_segment_contact_id', 1)
Verifying from text displayed
cy.get('select#segment_segment_contact_id')
.find(':selected')
.contains('researcher user')
Verifying by selectedIndex
cy.get('select#segment_segment_contact_id')
.its('0.selectedIndex')
.should('eq', 1)
You can use this as well. Here first we are getting value of the second item in the list using the eq() command. Then once we have got the value, we are just simply passing that to select().
cy.get('select#segment_segment_contact_id option').eq(1).invoke('val')
.then((val) => {
cy.get('select#segment_segment_contact_id').select(val)
})
And if you want to just validate the value or text you can do:
cy.get('select#segment_segment_contact_id option')
.eq(1).should('have.value', 73349)
cy.get('select#segment_segment_contact_id option')
.eq(1).should('have.text', 'researcher user')
Referring to this question
I am able to successfully apply filter for my table. Now I want to change the way this filter is working. Here is the situation:
I am applying Mapped filter. It filtered out all mapped variables for me. Now I will change the value of one of the filtered variables, as soon as I delete the complete value, the variable is moved to Unmapped list and User is not able to change the variable. User now need to change the filter to either All or UnMapped filter to edit that variable.
Same in the case of Unmapped filter. Select Unmapped filter, as soon as I try entering value, the variable disappears and moved to 'Mapped' list.
What I need to do is to apply filter only when I select filter from drop down using ng-change and when I try to edit some variable the filter should not work.
Here is the code:
For Filter :
$scope.filterOpt = 'All';
$scope.emptyOrNull = function (variable) {
if ($scope.filterOpt == "All")
return true;
if ($scope.filterOpt == "Mapped")
return variable.Name && variable.Variable
if ($scope.filterOpt == "UnMapped")
return !(variable.Variable) ;
}
HTML :
<select class="selectpicker form-control" ng-model="filterOpt" ng-change="emptyOrNull()">
<option value="All">All</option>
<option value="Mapped">Mapped</option>
<option value="UnMapped">Un-Mapped</option>
</select>
and Table:
<tr ng-repeat="var in Mappings | filter: searchVariable | filter : emptyOrNull">
<td>{{var.Name}}</td>
<td>
<div><input-dropdown name="fqn" ng-model="var.Variable" list="variables" ng-disabled="var.IsTrue"></input-dropdown></div>
</td>
</tr>
UI :
In above picture when I select Mapped from filter and try to change/delete Value1 it should not disappear.
Please help.
Basically I don't understand why do you want | filter : emptyOrNull, when you want to update UI only if you change the dropdown value.
Why don't you only update array($scope.Mappings). In this array you can only push values you want to display.
Remove filter and update your dropdown ng-change function like this
Here origArray is your original array, I am just changing scope variables
$scope.emptyOrNull = function (variable) {
$scope.Mappings = [];
if ($scope.filterOpt == "All") {
$scope.Mappings = angular.copy(origArray);
} else {
for (var i = 0; i < origArray.length; i++) {
if ($scope.filterOpt == "Mapped") {
if (origArray[i].Name && origArray[i].Variable) {
$scope.Mappings.push(origArray[i]);
}
}
if ($scope.filterOpt == "UnMapped") {
if (!origArray[i].Variable) {
$scope.Mappings.push(origArray[i]);
}
}
}
}
}
Don't use filter for this kind of requirements, it reduces performance.
What you can do is add a conditional filter. That means apply filter only when you want it to be and don't apply when you don't want.
you can check when input is focused with something like and toggle a variable to disable or enable filter
<input-dropdown name="fqn" ng-model="var.Variable" ng-focus="disable=true" list="variables" ng-disabled="var.IsTrue"></input-dropdown>
And to do conditional filtering use
<tr ng-repeat="var in Mappings | filter : (disable ? '' : emptyOrNull)">
And then you can update the disable to true on changing mapped/unmapped dropdown.
Hope this helps
I am using antd design in my React app.
Here's a code snippet where I am facing the issues :
<Select
showSearch
optionFilterProp = "children"
placeholder = "Select Company"
value = "{this.state.company}"
name = "company"
onSelect = "{this.handleCompanyChange}"
>
Now it shows the correct value selected if this.state.company is not null. But if this.state.company is empty or null, placeholder doesn't shows up.
How can I solve this issue so that the placeholder appears if value is null?
set this.state.company to be undefined instead of null.
you should update as below:
<Select
showSearch
optionFilterProp = "children"
placeholder = "Select Company"
value = {this.state.company || undefined} ---- update this line
name = "company"
onSelect = "{this.handleCompanyChange}"
>
It should be set to undefined instead of null or "" empty string.
this.props.form.setFieldsValue({
myFieldName: undefined
})
I have faced the the same issue, heres the solution:
Code snippet for ant design select
<Select key="1" value={this.getStateValue()} showSearch allowClear placeholder='Select Weight' onChange={onWeightChange}>
{options}
</Select>
where getStateValue will be this:
getStateValue = () => {
const { value } = this.state;
if (value) {
return value;
}
}
I changed from:
const [value, updateValue] = useState("");
To:
const [value, updateValue] = useState(undefined);
And it worked!
If you are using Form.create() of the Antd then there is another cool way to set/get the value of the form. Note that in this method the components (Select and others) have to be inside a <Form> element. Also the enclosing class should be passed in Form.create() object as props, as shown below:
export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(YourClassName));
This way we have this.props.form available in the props. This will have an important function named getFieldDecorator, as shown below:
const { getFieldDecorator } = this.props.form;
Every Input component must be wrapped inside a , see below:
<FormItem>
{ getFieldDecorator('prefix', {
initialValue: '86',
})(
<Select style={{ width: 70 }}>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
);}
</FormItem>
As you can see above, this is more easier way to set initial value to the form elements.
Note that at times when you need to set values of the form elements in functions programatically then you can use setFieldsValue, setFields etc.
Before using getFieldsValue getFieldValue setFieldsValue and so on, please make sure that corresponding field had been registered with getFieldDecorator.
Please refer https://ant.design/components/form/?locale=en-US#Form-fields for more information on coordinated controls.
Example:
componentDidMount() {
if (someCheckHere){
this.props.form.setFieldsValue({
company: userData.companyName
})
}
}
Check the image posted, you need to target the name and try to set it to null if its an empty string, this should work.
I want to change the country selected in the intl-Tel-Input based on another select list. e.g. if Malaysia is selected in the country select list, the intl-Tel-Input should be changed to malaysia and should display its flag and code. similary if the country is changed to United States, the intl-Tel-Input should change accordingly.
Any help is appreciated.
Regards.
I would simply create js object "kind of json format" containing all the country code with there specific names, and dynamically try to alter the input placeholder once the country selected matches using javascript
if you are using React, here is the solution
constructor(){
super()
this.state = {
updated:true
}
}
To keep tracking if country is being changed.
componentWillReceiveProps(nextProps){
if(this.props.selectedCountry !== nextProps.selectedCountry){
this.setState({
updated:false
})
}
}
tells you its going to change now
componentDidUpdate(nextProps){
if(this.props.selectedCountry !== nextProps.selectedCountry){
this.setState({
updated:true
})
}
}
Changed now.
render(){
const { selectedCountry } = this.props;
var countryCode = 'us'
if(selectedCountry)
countryCode = selectedCountry.toLowerCase()
var field = <Field
className="ibm-fullwidth urx-country"
name="phone"
onInputChange={this.onInputChange}
component={this.renderPhoneInput}
defaultCountry={countryCode}
/>
return (
<span>
{this.state.updated &&
<span>{field}</span>
}
</span>
)
}
Basically its is re-rendering on country change.