Angular 6 reset select options onclick - select

I am trying to reset options value when clicked on button. I was unable to find any solution. I have a component where I am using this code:
<select class='select-option' required [(ngModel)]='optionSelected' (ngModelChange)="toNumber()">
<option [ngValue]="undefined" disabled selected> Please select one option </option>
<option *ngFor='let option of options' [ngValue]="option">{{option}}</option>
</select>
Inside my class I am using this code:
options = ["Bar", "Pie", "Area"];
To call options inside a loop. I am using this code on button event:
appendToContainer(){
// logic
this.options == null
}
What should I do to make it default or null

Your logic is correct, but implementation is wrong:
appendToContainer(){
// logic
this.options == null; // ==> WRONG expression
this.options = []; // ==> CORRECT
}

Try this:
appendToContainer(){
// logic
this.options.value == this.options.options.first;//if the first options is 'Select'
}

Related

Target the current value of an option list using js, and add that value to an object?

HTML
<div class="options-container">
<select id="all-options">
<option value="0" selected>NY</option>
<option value="1">LA</option>
<option value="2">Toronto</option>
<option value="3">Paris</option>
</select>
</div>
JS
let selectedOption = {};
let allOptions = document.getElementById('all-options');
let optionValue = allOptions.options[all-options.selectedIndex].value;
if (optionValue == "0") {
selectedOption.value === "0"
} else if (optionValue === "1") {
selectedOption.value === "1"
} else if (optionValue === "2") {
selectedOption.value === "2"
} else if (optionValue === "3") {
selectedOption.value === "3"
};
I'm attempting to target the current value of an option list element in my HTML file using JS so that I can add that value to the selectedOption object. The value can be added either as a string or number object.
Defining the Event Listener
You're going to want to define an event listener in your <select>. For example:
function onSelectItem(evt)
{
let value = evt.target.selectedOptions[0].value;
let text = evt.target.selectedOptions[0].text;
// Assign it how you want here:
selectedOption = value;
}
You can't really "push" to an object. If you meant an array, change the selected option to an array ([]) and do selectedOption.push(value). If you want a useful object, however, you could just assign it to evt.target.selectedOptions[0].
Attaching the Listener
After that, you can attach it in html, and pass the event object via the default event variable:
<select id="all-options" onchange="onSelectItem(event)">
<option value="0">NY</option>
<option value="1">LA</option>
<option value="2">Toronto</option>
<option value="3">Paris</option>
</select>
or more Javascript when the page loads (by setting the onload attribute to "init()" in <body>):
function init()
{
let menu = document.getElementById('all-options');
menu.addEventListener('change', onSelectItem);
// Since it seems that you also want a default selected value when the
// page loads, you should probably also initialize your `selectedOption` to `0`.
selectedOption = menu.selectedOptions[0].value;
}

Select: Limit number of selected options

I'm using ANT Design's Select component in multiple select mode. After two options are selected (see screenshot) I'd like to prevent any more from being selected. The field should not be disabled, so that you can deselect an option and select another.
I've tried the onFocus event, but it doesn't provide an event that I could use to preventDefault or otherwise keep from opening the dropdown. I've also tried adding a ref and calling blur() whenever the onFocus event is called. This closes the dropdown, but it's still visible for a second.
Does anyone know of a way to accomplish this?
If 3 or more options selected then with a simple condition you can disable other options.
Store selected options in state and while displaying options disable them based on condition.
https://codesandbox.io/s/happy-leftpad-lu84g
Sample code
import React, { useState } from "react";
import { Select } from "antd";
const { Option } = Select;
const opts = ["a11", "b12", "c13", "d14", "e15"];
const Selectmultiple = () => {
const [optionsSelected, setOptionsSelected] = useState([]);
const handleChange = value => {
console.log(`selected ${value}`);
setOptionsSelected(value);
};
return (
<div>
<Select
mode="multiple"
style={{ width: "100%" }}
placeholder="Please select"
onChange={handleChange}
>
{opts.map(item => (
<Option
disabled={
optionsSelected.length > 1
? optionsSelected.includes(item)
? false
: true
: false
}
key={item}
>
{item}
</Option>
))}
</Select>
</div>
);
};
I solved this problem using "open" prop:
const isMaxValues = value.length === limit;
<Select
mode="multiple"
disabled={false}
{...(isMaxValues && { open: false, onDropdownVisibleChange: handleShowError })}
>
{renderOptions()}
</Select>
So you still able to remove/deselect some options
Also you can provide isMaxValues option to renderOptions method and disable Options to be selected(if you need dropdown to be visible)

Set the selected attribute in a dropdown list if the condition is met in Angular2

I have 2 objects in my project: a company and an user. I have a form where the user can update his profile. One of the things he can update is the country. Now to show the countries I use a dropdown list.
I want to set the selected attribute in the option where the name of the country is equal to the actual country of the user. (country.name==user.country)
This is what I have tried but It doesn't seem to work.
<select>
<option *ngFor="#c of countries" [ngStyle]="setStyles()" [ngValue]="c">{{c.name}}</option>
</select>
setStyles(){
let styles;
if (this.companies[i].name == this.user.country ) {
styles = {
'selected'
}
return styles;
}
I would try the following:
<select>
<option *ngFor="#c of countries"
[attr.selected]="c.name == user.country ? true : null"
[ngValue]="c">
{{c.name}}
</option>
</select>
I think that it's an attribute you need and not a style.

Knockoutjs (version 2.1.0): bind boolean value to select box

I want to bind boolean value to select element using KO v2.1.0, but obviously it doesn't work as expected.
HTML code:
<select data-bind="value: state">
<option value="true">On</option>
<option value="false">Off</option>
</select>
JavaScript code:
var model = {
state: ko.observable(false)
};
ko.applyBindings(model)
So I expect the select box goes to "Off" position with the initial value false but it was at "On". If I put state: ko.observable("false") it will be correct but that's not I wanted. Anyone know how to bind the boolean value to select box with KO?
Jsfiddle: https://jsfiddle.net/greenlaw110/Ajm58/
Here is an option that we explored for this one from this forum post:
ko.bindingHandlers.booleanValue = {
init: function(element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
interceptor = ko.computed({
read: function() {
return observable().toString();
},
write: function(newValue) {
observable(newValue === "true");
}
});
ko.applyBindingsToNode(element, { value: interceptor });
}
};
So, we use a custom binding to inject a writeable computed observable between the UI and our view model. This is just an alternative to doing it directly in your view model.
Sample here: https://jsfiddle.net/rniemeyer/H4gpe/
This happens because the select is working with strings, and not booleans at any stage.
You should try a ko.computed( ... ) value instead.
Check here for details: https://jsfiddle.net/Ajm58/3/
<select id="testSelect" data-bind="value: stateString">
<option value="true">true</option>
<option value="false">false</option>
</select>
​
var model = {
state: ko.observable(false)
};
model.stateString = ko.computed({
read: function() { return (this.state() ? "true" : "false"); },
write: function(value) { this.state(value == "true"); }
}, model);
ko.applyBindings(model);
setTimeout(function() {
model.state(true);
}, 1500);
setTimeout(function() {
$("#testSelect").val("false");
}, 3000);
Much easier than the other answers: use the options-Binding.
The answer is in the kind of lengthy expression below:
<select data-bind="options: [{text: 'On', value: true}, {text: 'Off', value: false}], value: lala1, optionsValue: 'value', optionsText: 'text'">
By using the options binding, you're able to assign virtually everything to the value of an option. It's rather uncommon, I guess, to bind an explicit value to the options binding, but in this 2-way case, it is reasonable.
I think I got the answer, put the number "1" and "0" to the option value respectively:
<select data-bind="value: state">
<option value="1">On</option>
<option value="0">Off</option>
</select>
See https://jsfiddle.net/greenlaw110/Ajm58/2/

How to bind multiple pair of selector:event in jQuery ON method

I m using jQuery 1.7+ latest .on method, but failed to implements, please help me.
working Fiddle.
basically here is my
HTML
<ul id="sortByRight" >
<li id="1">List</li>
<li id="2">Photo</li>
<li id="3">Map</li>
</ul>
<select name="sort" id="sort" >
<option value="1">Recommended</option>
<option value="2">Price: low to high</option>
<option value="3">Price: high to low </option>
<option value="4">Newest</option>
</select>
jQuery code
$(document).on('change click', 'ul#sortByRight,select#sort', function() {
selectedOption = $('select#sort').val();
whatToShow = $(this).attr('id');
alert('selectedOption:'+selectedOption+'whatToShow:'+whatToShow);
}
);
now I havebelow problems/queries.
can we bind one event with one selector i.e. above function should be called
EITHER on change of selectbox OR on click of ul.
how to set data argument in .on method. I have tried like below
$(document).on('change click', 'ul#sortByRight,select#sort',
{ selectedOption : $('select#sort').val(), whatToShow : $(this).attr('id') } ,
function(){console.log('selectedOption:'+selectedOption+'whatToShow:'+whatToShow);}
);
but get an error that selectedOption is not defined.
can we write something like this $(this, li); because I need the id of li not the id of selectbox.
if there is any other optimized solution ( using function like live or bind ), then please tell me.
Thanks A Lot.
I'm not 100% clear on what you actually want to do, but one thing doesn't make much sense. You want to send the ID of the LI when the select box is changed. Which LI? The last LI clicked? You need to store the state of the active LI so that you can send it in the ajax request if the select box is changed.
Perhaps something like this:
$('select#sort').change(function() {
processAjax();
});
$('ul#sortByRight > li > a').click(function() {
$(this).closest('ul').find('li').removeClass('active');
$(this).closest('li').addClass('active');
processAjax();
});
function processAjax() {
selectedOption = $('select#sort').val();
whatToShow = $('ul#sortByRight').find('.active').attr('id');
alert('selectedOption:' + selectedOption + 'whatToShow:' + whatToShow);
}
or check out the jsFiddle