I want to bind the value of a select element in a Svelte component (Form.svelte) to the variable active in its parent (App.svelte). I've tried using bind:value={active} on the Form component in App, but this doesn't work because I need to access the select's value. How should I access the value of the select element? Thanks in advance.
Minimum working example: https://svelte.dev/repl/bc872132e21f4071abe5a255728fb0ec?version=3.43.0
You need to expose the value property if you want to bind to it. Here, we also bind the value property to the select element so that it is updated with changes to the select.
/* Select.svelte */
<script>
export let value
</script>
<select bind:value>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
You can then bind to it in your parent
/* App.svelte */
<script>
import Select from './Select.svelte'
let active;
</script>
<Select bind:value={active}/>
<p>{active}</p>
REPL
Related
Iam trying to do something that look easy but i cant find any soulotion,
i have <select> tag with 5 <option> all i want to do is when i click a button (have function inside of it) the select tag will be the default one (the first one)
for example :
<select className={'smallSelect'} onChange={appliances}>
<option defaultValue =''>Add</option> {/* The default */}
<option value='<Fan/>'>Air-Conditioner</option>
<option value='<HotTub/>'>boilermaker</option>
<option value='<Bulb/>'>lamp</option>
<option value='<Radio/>'>stereo system</option>
</select><br/> {/* After clicking the button the option will be the default */}
<button className={'myButton'} onClick={newAppliances}>Add</button>
I assume the button onClick event calls the function newAppliances?
You need to set the select value to ''. So add something like this at the end of your newAppliances function.
document.getElementById('.smallSelect').value = '';
See this:
How do I programmatically set the value of a select box element using JavaScript?
For React
The above solution is for normal javascript, if you want to do the react way, read this:
React JSX: selecting "selected" on selected <select> option
So, I was just wondering if I absolutely need to have a onChange event handler on a select component in React?
I have a prop passing in the default value on the option I want selected. It works no problem if I have:
<select
value={this.props.defaultValue}
>
<option value="a">A</option>
<option value="b">B</option>
</select>
Except, it is static as I am sure you are familiar with the error:
Warning: Failed form propType: You provided a `value` prop to a form field without an `onChange` handler.
This will render a read-only field.
As I am getting the value using Jquery, I don't need a state or any passing between child and parent...
Is there a simple way to allow the select to get a default value from props and still operate as a normal select where changing an option changes the value I can grab with jquery, or do I have to have a state, and a onChange handler?
Thanks!
What I have already tried:
<select
defaultValue={this.props.defaultValue} // just returns the first option
>
<options etc.>
</select>
Also, I would rather not use an external package like React-Select... I just want to have a default value and a normal select...
As #julien mentions, you can use ref instead of JQuery to get the current value of the select in an uncontrolled component:
class MySelect extends React.Component {
constructor(props) {
super(props);
this.state = { currentValue: this.props.defaultValue };
}
updateValue() {
this.setState({ currentValue: this.refs.myselect.value });
}
render () {
return (
<div>
<div>
<button className="current" onClick={this.updateValue.bind(this)}>{this.state.currentValue}</button>
</div>
<select ref="myselect" defaultValue={this.props.defaultValue}>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</div>
);
}
}
For the other part, defaultValue should work just as you were trying.
Check this example fiddle: https://jsfiddle.net/y64gbhf8/1/
you can try Uncontrolled Components
you don't need to write event handler for state update,DOM will handle it,
then you can use a ref to get form values from the DOM
I have this tempScale object defined in my controller:
$scope.tempScale = {
scaleType : [],
deviations : [],
intervals : 0
};
Which connects to my html:
<select id="scales" ng-model="tempScale.scaleType" class="form-control">
<option value="Manually Calculated" ng-selected="true">Manually Calculated</option>
<option value="Automatically Calculated">Automatically Calculated</option>
</select>
I added in the ng-selected=true so that manually calculated would be the first and selected option (basically a default option 1), however, when I run the page, my HTML looks like:
<select id="scales" ng-model="tempScale.scaleType" class="form-control ng-valid ng-dirty ng-touched">
<option value="? undefined:undefined ?"></option>
<option value="Manually Calculated" ng-selected="true" selected="selected">Manually Calculated</option>
<option value="Automatically Calculated">Automatically Calculated</option>
</select>
Why are those ng classes appearing on load, and where is this undefined option value coming from? It's not a loop, so I'm baffled.
You do not need ng-selected. Set the model from the controller as $scope.tempScale.scaleType='Manually Calculated';.
One cannot set a default selected item when using ng-model directive with select element. The select element is bind to model field, which data is undefined. What value select should display? Yes, undefined. You try to pass data via markup, it is not an Angular way.
Just keep your data in JS model, not in HTML markup.[Ref]
Plunker demo
I have a number of items that get their data from a Json object and populate it using angular.
<select ng-model="MyCtrl.cargoList">
<option ng-repeat="cargo in MyCtrl.cargoList">{{ cargo.name }}</option>
</select>
And whenever I load the form, I get something like this in my console:
<select ng-model="MyCtrl.cargoList">
<option value="? object:25 "?></option>
<option value="">Gloves</option>
<option value="">Jacket</option>
<option value="">Shoes</option>
</select>
I can get the values to appear just fine, but I can't seem to get rid of the very first option. I don't mind the select box showing the very first element in the list, but I don't want it to be a blank line. How do I get rid of it?
You need to select 1st option by default on ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name" & ng-model name should not be same as that of your cargoList.
Markup
<select ng-model="MyCtrl.selectedCargo" ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name">
<option ng-repeat="cargo in MyCtrl.cargoList" value="cargo.name">{{ cargo.name }}</option>
</select>
Demo Plunkr
Use ngOption <option>
The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.
I have used following expression
label for value in array
HTML
<select ng-model="MyCtrl.cargo" ng-options="cargo.name for cargo in MyCtrl.cargoList">
</select>
and In your controller set model value as first element of list
this.cargo = this.cargoList[0]
Also note: You can use MyCtrl.cargoList as model as well as array So you should use another variable to hold the model value.
Use ng-options instead of ng-repeat
<select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList"></select>
You can fine tune the labels/values further if you like, check the documentation here - https://docs.angularjs.org/api/ng/directive/ngOptions
You can ng-init, or set the first value to defualt, something like
MyCtrl.selectedListItem = MyCtrl.cargoList[0]
So if you want a function to detect you have changed the value of the select you would use ng-change like so :
<select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList" ng-change="selectChanged"></select>
In your controller
$scope.selectChanged = function(){
//apply your logic
};
I have the following markup:
<select onchange="jsFunction()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
When a user pulls down the combobox and selects the same option that was previously selected (or doesn't change the selection at all), JavaScript doesn't regard it as an onchange event. So, the jsFunction() is not called. But I want the jsFunction() called even in this case. How can I achieve this?
I'd do it like this:
<select onchange="jsFunction()">
<option value="" disabled selected style="display:none;">Label</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
If you want you could have the same label as the first option, which in this case is 1.
Even better: put a label in there for the choices in the box.
You have to add empty option to solve it,
I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.
<select onChange="jsFunction()" id="selectOpt">
<option value="1" onclick="jsFunction()">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
function jsFunction(){
var myselect = document.getElementById("selectOpt");
alert(myselect.options[myselect.selectedIndex].value);
}
Just set the selectIndex of the associated <select> tag to -1 as the last step of your processing event.
mySelect = document.getElementById("idlist");
mySelect.selectedIndex = -1;
It works every time, removing the highlight and allowing you to select the same (or different) element again .
Try this. Just add an empty option. This will solve your problem.
<select onchange="jsFunction()">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
For this problem, I have finally put a new <i> tag to refresh the select instead. Don't try to trigger an event if the selected option is the same that the one already selected.
If user click on the "refresh" button, I trigger the onchange event of my select with :
const refreshEquipeEl = document.getElementById("refreshEquipe1");
function onClickRefreshEquipe(event){
let event2 = new Event('change');
equipesSelectEl.dispatchEvent(event2);
}
refreshEquipeEl.onclick = onClickRefreshEquipe;
This way, I don't need to try select the same option in my select.
use the "onmouseup" property with each option element. it's verbose, but should work. also, depending on what your function is actually doing, you could arrange things a little differently, assuming the number is important in the handler:
<select>
<option onmouseup="handler()" value="1">1</option> //get selected element in handler
<option onmouseup="handler(2)" value="2">2</option> //explicitly send the value as argument
<option onmouseup="handler(this.value)" value="3">3</option> //same as above, but using the element's value property and allowing for dynamic option value. you could also send "this.innerHTML" or "this.textContent" to the handler, making option value unnecessary
</select>
JavaScript code:
on mousedown event: set selectedIndex property value to -1
on change event: handle event
The only drawback is that when the user clicks on the dropdown list, the currently selected item does not appear selected
It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change event.
You can handle the blur event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.