Select Event not working after first time in React - javascript

I have a select filter menu which holds 5 different options.This event works fine when the page loads and also on refresh.When i try to select option continuously it is not filtering the content based on the option
part of the code is:
<div className="filter_role">Role{" "}<select
defaultValue={this.state.role}
onChange={this.filterRole.bind(this)}
>
<option value="">All</option>
<option value="Batsman">Batsman</option>
<option value="Wk-Batsman">WK-Batsman</option>
<option value="Bowler">Bowler</option>
<option value="All-Rounder">All-Rounder</option>
</select>
</div>
filterRole = (event) => {
if(event.target.value === "") {
this.setState({role:event.target.value, players: this.state.players})
} else {
this.setState({
role: event.target.value,
players: this.state.players.filter(player => player.role.indexOf(event.target.value)>=0)
})
}
console.log(event.target.value)
}
What am i doing wrong here? can anyone please help me out.

I think you are filtering it the wrong way, it should be like:
this.state.players.filter(player => player.role.indexOf(event.target.value) < 0)

Related

Vue JS Make drop-down select run query when option selected

I am very new to Vue and stuck on a problem. I have several drop-down select menus which return info from an Axios request The select t only works when I hit the submit button though. I would like it to run when the user makes the drop-down selection. I can't work out what I am missing. Can anyone help?
I have included some of the code below. Thanks
The html:
<div class="form-group col-md-6">
<label for="subject" class="control-label">Subject</label>
<select
v-model="subject"
class="form-control"
:disabled="selectDisabledSubject"
>
<option disabled value="">Select subject</option>
<option
v-for="subject in uniqueSubjects"
:key="subject"
:value="subject"
>
{{ subject }}
</option>
</select>
</div>
The vue
uniqueSubjects() {
const metaVFees = this.results
.filter((result) => result.metaData && result.metaData.V)
.map((item) => item.metaData.V)
.filter((subject, i, arr) => arr.indexOf(subject) === i);
// Split multiple subjects in strings and store in an array
let subjects = [];
metaVFees.forEach((item) => {
const splitArr = item.split(", ");
subjects = subjects.concat(splitArr);
});
return subjects
.sort()
.filter((subjects, i, arr) => arr.indexOf(subjects) === i);
},
You can use vue Watchers
watch:{
subject(newVal){
// call the function you normally call with submit click
}
}

How to render two event listeners on one page

In my rails app, I have a page where I need to display or hide divs based on a select option. This needs to happen to two seperate divs in my app and so I tried using two jquery event listeners to achieve this. I dont really understand javacript so I am struggling to figure out what I am doing wrong. The problem is, only one event listener can work at a time and not both event listeners.
This is the code in my js
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="lesson[lesson_type]"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
if(event.target.value === "physical" ) {
hiddenDiv.style.display='inline-block';
}
else {
hiddenDiv.style.display='none';
}
}
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="lesson[course_id]"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
var course_status = $('#lesson_course_id option:selected').attr('course_type');
if(course_status == "physical" ) {
$(".vimeo_link_display").hide();
}
else {
$(".vimeo_link_display").show();
}
}
These are the two separate drop-downs in the page
<%= f.input :lesson_type, label: t(".lesson_type") %>
<%= f.association :course, collection: current_academy.courses.collect { |u| [u.title, u.id, { course_type: u.course_type }] }, prompt: t("select") %>
This is the generated html for the first select in the js
<select class="form-control enum optional form-control"
name="lesson[lesson_type]" id="lesson_lesson_type"><option value="">
</option> <option selected="selected" value="video">video</option>
<option value="podcast">podcast</option> <option
value="physical">Physical</option>
</select>
The other one has this generated html
<select class="form-control select required" name="lesson[course_id]"
id="lesson_course_id"><option value="">Vælg</option> <option
course_type="online" value="27">Lov om ansættelsesklausuler</option>
<option course_type="online" value="54">Skat:
Omstrukturering</option>
<option course_type="online" value="154">1min couse</option> <option
course_type="podcast" value="157">Ransack 101</option> <option
course_type="physical" value="158">Physical Course Test </option>
</select>
Only one of the event works on the page. My aim is to have both working when I select the right values from each dropdown.
Please let me know if you need more code samples.
You onlu need one root listner, combine into one. You can rename changeEventHandler1 and changeEventHandler2 to your desired names :)
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="lesson[lesson_type]"]').onchange=changeEventHandler1;
},false);
function changeEventHandler1(event) {
if(event.target.value === "physical" ) {
hiddenDiv.style.display='inline-block';
}
else {
hiddenDiv.style.display='none';
}
}
document.querySelector('select[name="lesson[course_id]"]').onchange=changeEventHandler2;
},false);
function changeEventHandler2(event) {
var course_status = $('#lesson_course_id option:selected').attr('course_type');
if(course_status == "physical" ) {
$(".vimeo_link_display").hide();
}
else {
$(".vimeo_link_display").show();
}
}
$(document).ready(function(){
$('.you-select-tag').change(function(){
$('.div1-to-hide').hide(); # or .show();
$('.div2-to-hide').hide(); # or .show();
}
}

JQuery show/hide gives weird results

Im having some weird issues with javascript I can't really resolve.
I have three html input boxes with a small js file to show or hide the second and third one depending on what is picked in the first box. I'm using these functions:
$('#maintype').on('change', function() {
if (this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
The problem im running to is that the second dropdown is not shown when I highlight "fries". The third input box is never shown. I've tried all sorts of solutions, but I just can't figure out why.
I put my code on github
Anyone that can give me some insight on where I am going wrong? Is there maybe another, simpler way to get this done?
You have two issues:
The problem im running to is that the second dropdown is not shown when I highlight "fries"
Your check for fries is wrong, you have:
if ( this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
but the check should be for '6' since that is the value you assigned to it in your #maintype select.
The other issue:
The third input box is never shown.
You assigned the different IDs (eg. #fries, #icecream, etc.) to the <div> and not to the <select>.
You should also not have several elements with the same id or name (ie. #selectlist) in your case this will be solved when you fix the second issue.
There is no handler for <option value="6">fries</option> , i mean there is no if ( this.value == '6') type line in your javascript code. I added below lines in your js file and it worked.
$('#maintype').on('change', function() {
if ( this.value == '6')
//.....................^.......
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
});
Demo : https://jsfiddle.net/gd548j0g/
In your #maintype select, fries has a value of '6'. But in your change handler, you are looking for a value of 1. In fact, there is no value in the select that has a value of 1. Hence, the fries select box is never shown. Either change your handler to look for the id of 6:
$('#maintype').on('change', function() {
if ( this.value == '6') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
Or change your option value for fries to 1:
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="1">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
Working example: https://jsfiddle.net/mspinks/vnofjobu/2/
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="6">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
$('#maintype').on('change', function() {
if ( this.value == 6)
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
be careful with the values that you assign to the options
your value of fries is 6, not 1
I have checked your code in Git, you can achieve your output with below code in your showhide.js file.
$(document).ready(function(){
$('#maintype').on('change', function() {
$('input[type="text"]').hide(); //Hides all input with type Text, better if we do this using class
var id = '#' + this.value;
$(id).show(); //Show input with id which you have returned with this.value
});
});

Filter options of drop down menus with different values

Based on this useful topic Use jQuery to change a second select list based on the first select list option I try to adapt the code for my purposes.
My problem is that for some reasons I cannot have the exact same integer values in my 2 selection. I only can provide something close as:
<select name="select1" id="dropDown">
<option value="fruit">Fruit</option>
<option value="animal">Animal</option>
<option value="bird">Bird</option>
<option value="car">Car</option>
</select>
<select name="select2" id="dropDown_2">
<option value="fruit-01">Banana</option>
<option value="fruit-02">Apple</option>
<option value="fruit-03">Orange</option>
<option value="animal-01">Wolf</option>
<option value="animal-02">Fox</option>
<option value="animal-03">Bear</option>
<option value="bird-01">Eagle</option>
<option value="bird-02">Hawk</option>
<option value="car-01">BMW<option>
</select>
The js to be modified is:
$("#dropDown").change( function() {
if ( $(this).data('options') == undefined ) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data( 'options', $("#dropDown_2").find('option').clone() );
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$("#dropDown_2").html(options);
} );
I know that there are some js techniques to subtract substrings and similar stuff. But my skills are not so good to exactly say how. Is there anyone willing to help me? I need to filter the second options with its values based (but not identical) on the values of the first. Hope I explained myself sufficiently. Many many thanks!
EDIT
First of all sorry for not explaining myself sufficiently. I have to add that I cannot change the markUp!
So I inserted an each loop before the code that Shiran kindly delivered me to prepare it like so:
$("#dropDown_2").find('option').each( function() {
var $this = $(this);
var val = $this.val();
var myFilter = val.slice(0,-3)
$this.addClass( myFilter );
// $this.data('filter', myFilter ); does not work don’t know why
} );
Which seems to work at least in principle. Yet, for reasons that remain obscure for me sadly my attempt to attach data-filter to my option elements wasn’t accepted. So I had to go for classes which worked (at least for the loop).
I then tried to modify the code ending up with the following:
$("#dropDown").change(function() {
var filters = [];
if ($(this).attr('class') == "") {
$(this).find("option").each(function(index, option) {
if ($(option).attr('class') != "")
filters.push($(option).attr('class'));
} );
} else {
filters.push($(this).attr('class'));
}
$("#dropDown_2").html("");
$.each(filters, function(index, value) {
$options.find("option." + value ).clone().appendTo($("#dropDown_2"));
} );
} );
But as you can guess this didn’t work. :-(
And I also noted that the values of my filter array are the class (would be analogue to the filter value in the original) of my select not of the options of it. But obviously Shorans code did work well. What did I wrong here?
Please help, I am getting grey hair with this!! Thanks so much in advance!
$(this).data("options") gets:
<select data-options="the data here"> ==> "the data here"
Here's a working version:
(notice how I used data-filter in the second select and in the last each loop in the javascript part)
$(document).ready(function() {
var $options = $("#dropDown_2").clone(); // this will save all initial options in the second dropdown
$("#dropDown").change(function() {
var filters = [];
if ($(this).val() == "") {
$(this).find("option").each(function(index, option) {
if ($(option).val() != "")
filters.push($(option).val());
});
} else {
filters.push($(this).val())
}
$("#dropDown_2").html("");
$.each(filters, function(index, value) {
$options.find("option").each(function(optionIndex, option) { // a second loop that check if the option value starts with the filter value
if ($(option).val().startsWith(value))
$(option).clone().appendTo($("#dropDown_2"));
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="select1" id="dropDown">
<option value="">All</option>
<option value="fruit">Fruit</option>
<option value="animal">Animal</option>
<option value="bird">Bird</option>
<option value="car">Car</option>
</select>
<select name="select2" id="dropDown_2">
<option value="fruit-01">Banana</option>
<option value="fruit-02">Apple</option>
<option value="fruit-03">Orange</option>
<option value="animal-01">Wolf</option>
<option value="animal-02">Fox</option>
<option value="animal-03">Bear</option>
<option value="bird-01">Eagle</option>
<option value="bird-02">Hawk</option>
<option value="car-01">BMW
<option>
</select>

With webdriver.js, how to get the selected option of a <select>?

Plenty of answers for java and C#, but I can't find how to do it in javascript. Seems the API are different...
yeah it is possible. Lets say we have the following select element:
<select name="test" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You get the current selected option by using getValue and you can change the selection by using click. Here is an simple example:
var webdriverjs = require('webdriverjs'),
client = webdriverjs.remote({desiredCapabilities:{browserName:'phantomjs'}}).init();
client
.url('http://localhost:8080')
.getValue('#select',function(err,val){
console.log(val); // will output "1"
})
.click('//*[#id="select"]/option[3]')
.getValue('#select',function(err,val){
console.log(val); // will output "3"
})
.end();
Hope that helps.
cheers
For those who are just looking for pure WebDriverJS solution and not any framework specific like webdriver.io or protractor, here is the code,
var element = driver.findElement(wd.By.id('mySelect'));
element.getAttribute('value').then(function(selected) {
if(selected === 'the one I expected') {
done();
}
else {
done(new Error('something went wrong');
}
});
If you want the option element, use the return value of then callback:
driver.findElement(By.css('select[name=eventTypes]'))
.then((select) => {
return select.getAttribute('value').then((value) => {
return {select: select, value: value};
});
})
.then((data) => {
return data.select.findElement(By.css('option[value="'+data.value+'"]'));
})
.then((option) => {
//do something.
});
If you have this in your html for an example
<select name="test" id="myId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You can select for a example option 3 like this
var driver = new firefox.Driver();
driver.findElement(By.css('#myId>option:nth-child(2)')).click();
Works for me and I am using selenium-webdriver with JavaScript
Although the question has been posted for 7 years, I would like to share my answer that works now. You can get the selected option/value by
let select_value = await driver.findElement(By.css('select')).getAttribute('value')
I did using this
element=await driver.findElement(By.name("quantity")); // here you have to select your element suppose i am using get element by name
// below will help you to get selected value from select option
var SelectedValue=element.getAttribute('value').then(function(selected) { return selected;});

Categories

Resources