How to make changes by using onChange using <select> in React? - html

I'm making an app that uses a dropdown menu like:
<select name="color">
<option value="red" onChange={this.func}>Red</option>
<option value="blue" onChange={this.func}>
Blue
</option>
</select>
However, the onChange function is not working. The function given is:
func = () => {
console.log("Color");
};
I'm wondering why is this not working? What should be done to make it work?
Thanks in advance.

Your code does not work, because selects fire onChange events, and options don't. You need move the onChange event handling to the <select/>:
<select name="color" onChange={this.func}>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
// and for your func:
func = (event) => {
//event.target.value contains the selected option value, e.g. "red"
console.log("Color: ", event.target.value);
};

Related

Not able to keep the option selected in drop-down list

I have a drop-down list which POSTs to express and then redirects to same page.
Now, I want the one valid option to be selected before submitting, hence I added required property in <select> tag.
But, I also want a value to be Selected in the list when page renders
If first time render, then first option
If after submitting, the submitted option to be selected by default
Here is the skeleton code
<select required data-style="btn-info" name="selectpicker">
<optgroup label="Select Map">
<option name="table1" value="Station">Station</option>
<option name="table2" value="Station2">Station2</option>
</optgroup>
</select>
and the things I tried
<option value="" selected disabled>Select station</option>
<option name="table1" value="Station" selected>Station</option>
but none of them fulfills my requirements.
if you are using javascript for handling the form just add event.preventDefault() in your onsubmit function so when you submit it won't revert back to default
The problems were solved by
<form action="any" method="any" onSubmit="return fieldCheck();">
<select required id="collec" data-style="btn-info" name="selectpicker">
<option value="Select Station" selected disabled hidden>Select City</option>
<option name="table1" value="Vice City">Vice City</option>
<option name="table2" value="Delhi City">Delhi City</option>
and script
function fieldCheck() {
var collec = document.querySelector('#collec');
if(collec.value != "Select Station") {
return true;
}
else {
alert("Select a city first!!");
return false;
}
}

How can we call two different function for a dropdown in HTML/Angular?

I coded a dropdown with two option inside: english and french.
But for each option I need to call a different function.
My code is in HTML :
<select (click)="myFuncEnglish()">
<option value="EN">English</option>
<option value="FR">France</option>
</select>
And for Angular is:
myFuncEnglish() {
console.log('function called is english');
}`
Can you help me please to know how can I code different function for the different options, and to display when I click on french "function called is french", and when I click on english "function called is english".
I guess, you don't need to call two functions.
You need to pass the selected value as the function argument and check the value in the function body to console log your message.
HTML
<select (ngModelChange)="myFuncEnglish($event)" [(ngModel)]="lang">
<option value="EN">English</option>
<option value="FR">France</option>
</select>
Component
myFuncEnglish(lang) {
if(lang === 'FR'){
console.log('function called is french');
} else {
console.log('function called is english');
}
}
See a working example here
Do it onchange insted, on Angular i think it is ng-change="funcEnglish()"
Then on funcEnglish validate the item.value to know you what to do.
function funcEnglish(item) {
console.log('function called is '+ item.value);
}
<select onchange="funcEnglish(this)">
<option value="Empty">None</option>
<option value="EN">English</option>
<option value="FR">France</option>
</select>
Another way is not using ngModel just use change event.
HTML
<select (change)="myFuncEnglish($event)">
<option value="EN">English</option>
<option value="FR">France</option>
</select>
Typescript
myFuncEnglish(event: any) {
if(event.value === 'FR'){
console.log('function called is french');
} else {
console.log('function called is english');
}
}

How to alert the chosen option from HTML option select using javascript function?

function myFunction() {
var chosen = document.getElementById("input").value;
alert(chosen);
}
<select id="input" onchange="myFunction()">
<option selected>Choose...</option>
<option>ONE</option>
<option>TWO</option>
<option>THREE</option>
<option>FOUR</option>
</select>
So what I am trying to achieve, is when the user selects from the list (ONE, TWO, THREE or FOUR), then it should alert their selection to the window.
However, this doesn't work for me.
Any help would be deeply appreciated!

doesn't show select option in chrome

I have a problem with my site. I have a select menu and 3 options: images, video and audio. When I click one of the options it should display a button to pick out the image/video/audio to upload, but this doesn't display in Google Chrome. In Firefox there is no problem with this. Does anyone have a solution for this?
Thanks very much!
EDIT:
This is the code
<select name="service_id">
<option value="video" onClick="showSection('video',['image','audio']);" <?=count($videos)?'selected="selected"':''?>>Video</option>
<option value="image" onClick="showSection('image',['video','audio']);" <?=count($images)?'selected="selected"':''?>>Imagini</option>
<option value="audio" onClick="showSection('audio',['video','image']);" <?=count($audios)?'selected="selected"':''?>>Audio</option>
</select>
things i modified:
the second parameter is now a class name, each value separated by a "|"
used onChange() to trigger a selection (but does not trigger unless the value changes)
used this to pass a reference to the select rather than passing values (you can do more this way)
demo here
<select name="service_id" onChange="showSection(this)">
<option value="video" class='image|audio'>Video</option>
<option value="image" class='video|audio'>Imagini</option>
<option value="audio" class='video|image'>Audio</option>
</select>
<script type="text/javascript">
function showSection(el){
//modified to get the first and second parameters of showSection()
//get the value
var firstParam = el.value;
//get the class name of the selected element, and split it
var secondparam = el.options[el.selectedIndex].className.split('|');
console.log(firstParam);
console.log(secondparam);
}
</script>​
Call the function on select not in options:
<select onClick='showSection(this.value,"a")'>
<option value="video" >Video</option>
<option value="image">Imagini</option>
<option value="audio">Audio</option>
</select>
i have tested this in chrome its working alright.
one suggestion is if you are using dropdown then use onchange event rather then using onClick
<?php
$videos=0;
$images=0;
$audios=0;
?>
<select name="service_id">
<option value="video" onClick="showSection('video',['image','audio']);" <?=count($videos)?'selected="selected"':''?>>Video</option>
<option value="image" onClick="showSection('image',['video','audio']);" <?=count($images)?'selected="selected"':''?>>Imagini</option>
<option value="audio" onClick="showSection('audio',['video','image']);" <?=count($audios)?'selected="selected"':''?>>Audio</option>
</select>

Redirect on select option in select box

At the moment I am using this:
<select ONCHANGE="location = this.options[this.selectedIndex].value;">
it redirect me on the location inside of the option value. But it doesn't work as expected .. mean that if I click on the first option of the select, then onChange action not running. I was thinking about javascript, but I think you'll have some better suggestions guys. So how can I make it work if I click on each option it'll redirect me to the it's value?
Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.
Here's an example:
https://jsfiddle.net/bL5sq/
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="">Select...</option>
<option value="https://google.com">Google</option>
<option value="https://yahoo.com">Yahoo</option>
</select>
I'd strongly suggest moving away from inline JavaScript, to something like the following:
function redirect(goto){
var conf = confirm("Are you sure you want to go elswhere?");
if (conf && goto != '') {
window.location = goto;
}
}
var selectEl = document.getElementById('redirectSelect');
selectEl.onchange = function(){
var goto = this.value;
redirect(goto);
};
JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.
In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.
Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert
to make it as globally reuse function using jquery
HTML
<select class="select_location">
<option value="http://localhost.com/app/page1.html">Page 1</option>
<option value="http://localhost.com/app/page2.html">Page 2</option>
<option value="http://localhost.com/app/page3.html">Page 3</option>
</select>
Javascript using jquery
$('.select_location').on('change', function(){
window.location = $(this).val();
});
now you will able to reuse this function by adding .select_location class to any Select element class
For someone who doesn't want to use inline JS.
<select data-select-name>
<option value="">Select...</option>
<option value="http://google.com">Google</option>
<option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[data-select-name]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
window.location.href = this.options[this.selectedIndex].value;
}
</script>
This can be archived by adding code on the onchange event of the select control.
For Example:
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value=""></option>
<option value="http://google.com">Google</option>
<option value="http://gmail.com">Gmail</option>
<option value="http://youtube.com">Youtube</option>
</select>
{{-- dynamic select/dropdown --}}
<select class="form-control m-bot15" name="district_id"
onchange ="location = this.options[this.selectedIndex].value;"
>
<option value="">--Select--</option>
<option value="?">All</option>
#foreach($location as $district)
<option value="?district_id={{ $district->district_id }}" >
{{ $district->district }}
</option>
#endforeach
</select>
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="">Select...</option>
<option value="https://reactjs.org/">React Js</option>
<option value="https://angularjs.org/">Angular Js</option>
</select>