Select Options: replace text with new value - html

I feel as though I am very close to a solution for this. I searched for similar questions but I do not believe I have found the answer I am looking for.
What I would like:
I have a select dropdown with long text options, and would like to replace the value from handle change with the first word in the option, and set that as the new button select option.
What I currently have:
I modify the incoming handleChange to the first word, attempt to set it on the select button, and it never happens.
codepen: https://codepen.io/anon/pen/gdXVJM?editors=1011
code:
HTML
<div id="input"></div>
JS
class MyInput extends React.Component{
constructor(props){
super(props);
this.state = {
buttonStyle: '',
voiceSelected: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
event.persist();
if (event.target.id === 'voiceSelected') {
//set the state we're going to use later
this.setState(() => ({ 'voiceSelected': event.target.value}));
//Take the first word from the string to make it visable on button
let totalWords = event.target.value
var firstWord = totalWords.replace(/ .*/,'');
console.log(firstWord)
this.setState(() => ({'buttonStyle': firstWord}));
} else {
console.log("Something Went Wrong!")
}
}
render(){
return <select
id="voiceSelected"
value={this.state.buttonStyle}
name={this.state.buttonStyle}
onChange={(e) => {this.handleChange(e)}}
>
<option value="" selected disabled hidden>Choose Voice</option>
<option value="Ivy">Ivy [English - American]</option>
<option value="Joanna">Joanna [English - American]</option>
<option value="Joey">Joey [English - American]</option>
<option value="Justin">Justin [English - American]</option>
<option value="Kendra">Kendra [English - American]</option>
<option value="Kimberly">Kimberly [English - American]</option>
<option value="Salli">Salli [English - American]</option>
<option value="Nicole">Nicole [English - Australian]</option>
<option value="Russell">Russell [English - Australian]</option>
<option value="Emma">Emma [English - British]</option>
<option value="Brian">Brian [English - British]</option>
<option value="Amy">Amy [English - British]</option>
<option value="Raveena">Raveena [English - Indian]</option>
<option value="Geraint">Geraint [English - Welsh]</option>
<option value="Ricardo">Ricardo [Brazilian Portuguese]</option>
<option value="Vitoria">Vitoria [Brazilian Portuguese]</option>
<option value="Lotte">Lotte [Dutch]</option>
<option value="Ruben">Ruben [Dutch]</option>
<option value="Mathieu">Mathieu [French]</option>
<option value="Celine">Celine [French]</option>
<option value="Chantal">Chantal [Canadian French]</option>
<option value="Marlene">Marlene [German]</option>
<option value="Dora">Dora [Icelandic]</option>
<option value="Karl">Karl [Icelandic]</option>
<option value="Carla">Carla [Italian]</option>
<option value="Giorgio">Giorgio [Italian]</option>
<option value="Mizuki">Mizuki [Japanese]</option>
<option value="Liv">Liv [Norwegian]</option>
<option value="Maja">Maja [Polish]</option>
<option value="Jan">Jan [Polish]</option>
<option value="Ewa">Ewa [Polish]</option>
<option value="Cristiano">Cristiano [Portuquese]</option>
<option value="Ines">Ines [Portuquese]</option>
<option value="Carmen">Carmen [Romanian]</option>
<option value="Maxim">Maxim [Russian]</option>
<option value="Tatyana">Tatyana [Russian]</option>
<option value="Enrique">Enrique [Spanish]</option>
<option value="Penelope">Penelope [US Spanish]</option>
<option value="Enrique">Miguel [US Spanish]</option>
<option value="Conchita">Conchita [Castilian Spanish]</option>
<option value="Astrid">Astrid [Swedish]</option>
<option value="Filiz">Filiz [Turkish]</option>
<option value="Gwyneth">Gwyneth [Welsh]</option>
</select>
}
}
ReactDOM.render(<MyInput/>, document.getElementById('input'));

<select> doesn't have 'value' attribute. we can get the value of select box by using 'selected' attribute in <options>
Please refer doc

I don't know if it suits you but if you can keep your options in the state you can somehow manipulate them. But with this method, you are losing the long values when you select an option. Maybe you can improve the logic starting with this answer.
class App extends React.Component {
state = {
options: [
"Ivy [English - American]",
"Joanna [English - American]",
"Joey [English - American]",
"Justin [English - American]"
],
selectedIndex: 0
};
handleChange = event => {
const { selectedIndex, value } = event.target;
const { options } = this.state;
var firstWord = value.replace(/ .*/, "");
const newOptions = Object.assign([], options, {
[selectedIndex - 1]: firstWord
});
this.setState({ options: newOptions, selectedIndex });
};
render() {
const { options } = this.state;
return (
<select
id="voiceSelected"
value={this.state.options[this.state.selectedIndex - 1]}
name={this.state.buttonStyle}
onChange={this.handleChange}
>
<option value="">Choose Voice</option>
{
options.map( option =>
<option key={option}>{option}</option>
)
}
</select>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Related

JQuery match different id with the last same number

I have example HTML code like this:
<select id="label_1">
<option></option>
</select>
<select id="item_1">
<option></option>
</select>
<select id="label_2">
<option></option>
</select>
<select id="item_2">
<option></option>
</select>
How do I write jQuery code to match the label and item id with the same number?
if($("#label_" + [/[0-9]+$/]) == $("#item_" + [/[0-9]+$/])) {
//do something
}
You can find all the label elements first and then iterate them to find the matching item elements
$("select[id^='label_']").each((_, label) => {
const idSuffix = label.id.split("_").pop();
const item = $(`#item_${idSuffix}`);
// now you have both `label` and `item`
});
The vanilla JS version isn't much different
document.querySelectorAll("select[id^='label_']").forEach((label) => {
const idSuffix = label.id.split("_").pop();
const item = document.getElementById(`item_${idSuffix}`);
// now you have both `label` and `item`
});
If you want to do one time : return false
$.each($("select[id^= 'label_']"), function(){
let num = this.id.replace('label_', '')
let equal = $(this).value === $("#item_" + num).value
if(equal) {
// do something
// if you want to run one times ( return false)
return false
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="label_1">
<option value="1" selected>1</option>
</select>
<select id="item_1">
<option value="1" selected>1</option>
</select>
<select id="label_2">
<option value="2" selected>2</option>
</select>
<select id="item_2">
<option value="2" selected>2</option>
</select>

Default option in select

I have this very simple select element:
<label>Items per page</label>
<select class="form-control input-sm w25" ng-model="itemsPerPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
with controller:
$scope.itemsPerPage = 5; // default value
But the default value is a blank option and the default value attempt doesn't do anything.
How do I make the value 5 the default?
Angular is probably converting that value to a string, so do:
$scope.itemsPerPage = "5";
The blank option appears because ng-model can't find an option that matches the value of the bound property (option values are converted to string and the bound property is number).
If you don't want to change the type of your itemsPerPage property and make it a string, you can keep a number and define, in your $scope, an object with a getter and setter that will take care of the type conversion.
angular.module('dummyApp', [])
.controller('DummyController', function($scope) {
var itemsPerPage = 5; // still a number
Object.defineProperty($scope, "itemsPerPage", {
get: function() {
return itemsPerPage + "";
},
set: function(newValue) {
itemsPerPage = parseInt(newValue);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.js"></script>
<div ng-app="dummyApp" ng-controller="DummyController">
<label>Items per page</label>
<select class="form-control input-sm w25" ng-model="itemsPerPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</div>
<option value="5" selected>5</option>
This should work^^

how to change second drop-down based on first option selection and third drop-down based on second option selection

Please can someone help me - I want the second drop-down to change based on a selection from the first option and also the third drop-down to change based on a second selected option. Here is my html:
<select name="selectLevel" id="selectLevel" >
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary 3">Tertiary</option>
</select>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="maths">Mathematics</option>
<option data-value="tertiary" value="IT">Business Math</option>
</select>
<select name="selectTopic" id="selectTopic" >
<option value=""> -- select a topic -- </option>
<option data-value="jhs">Spelling</option>
<option data-value="shs">Matrix</option>
<option data-value="tertiary">Calculus</option>
</select>
And here is my script:
$(document).ready(function(){
$('#jhs').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectSubject option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectSubject').html(options).show();
});
$('#selectSubject').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectTopic option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectTopic').html(options).show();
});
});
Thank You very much!
I change a little bit to make it easier.
When we change the first select, it will check the second select's option and change its value.
After that, it will trigger the second select's change event and so on.
$(document).ready(function() {
// Save all selects' id in an array
// to determine which select's option and value would be changed
// after you select an option in another select.
var selectors = ['selectLevel', 'selectSubject', 'selectTopic']
$('select').on('change', function() {
var index = selectors.indexOf(this.id)
var value = this.value
// check if is the last one or not
if (index < selectors.length - 1) {
var next = $('#' + selectors[index + 1])
// Show all the options in next select
$(next).find('option').show()
if (value != "") {
// if this select's value is not empty
// hide some of the options
$(next).find('option[data-value!=' + value + ']').hide()
}
// set next select's value to be the first option's value
// and trigger change()
$(next).val($(next).find("option:first").val()).change()
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectLevel" id="selectLevel">
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary">Tertiary</option>
</select>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="calculus">Calculus</option>
<option data-value="tertiary" value="IT">Info Tech</option>
</select>
<select name="selectTopic" id="selectTopic">
<option value=""> -- select a topic -- </option>
<option data-value="calculus">Calculus</option>
<option data-value="calculus">Matrix</option>
<option data-value="english">Basic English</option>
<option data-value="english">Basic English 2</option>
<option data-value="IT">Info Tech Studies</option>
<option data-value="IT">Info Tech Studies 2</option>
</select>
i got it u would add script CDN code in your code
https://www.w3schools.com/jquery/jquery_get_started.asp
just above your script code
Like this :
<select name="selectLevel" id="selectLevel" >
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary 3">Tertiary</option>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="maths">Mathematics</option>
<option data-value="tertiary" value="IT">Business Math</option>
<select name="selectTopic" id="selectTopic" >
<option value=""> -- select a topic -- </option>
<option data-value="jhs">Spelling</option>
<option data-value="shs">Matrix</option>
<option data-value="tertiary">Calculus</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#selectLevel').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectSubject option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectSubject').html(options).show();
});
$('#selectSubject').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectTopic option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectTopic').html(options).show();
});
});
You can do this by Ajax request.

add create 'All' option in drop down button in html

[HTML]
Now that I have three options in the drop down button:
<select id='campus' class="form-control">
<option value="Z010">Campus1</option>
<option value="Z020">Campus2</option>
<option value="Z040" selected>Campus3</option>
<option value="?????">- All Campuses-</option>
</select>
Now that i want to add a choice of "All Campus" in the drop down menu, which includes all students from all campus, what should i do ?
I can not do the following because i need "AND" within the bracket, not "OR":
<option value="{'Z010', 'Z020', 'Z040'}">All</option>
Any suggestions?
Thank you very much!!
Here is one approach, using a <select multiple> and a few lines of javascript:
var campusOptions = document.getElementsByTagName('option');
var allCampuses = document.querySelector('[value="all-campuses"]');
function selectAllCampuses() {
if (allCampuses.selected === true) {
for (var i = 0; i < (campusOptions.length - 1); i++) {
campusOptions[i].selected = true;
allCampuses.selected = false;
}
}
}
allCampuses.addEventListener('click', selectAllCampuses, false);
<select id="campus" class="form-control" multiple>
<option value="Z010">Campus1</option>
<option value="Z020">Campus2</option>
<option value="Z040" selected>Campus3</option>
<option value="all-campuses">- All Campuses -</option>
</select>

How to select part of "select"

I've got two multiple select lists
<html><head></head>
<body>
<select name="cars" multiple="multiple" size="7">
<option value="">-</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select name="drivers" multiple="multiple" size="7">
<option value="1">Luiza</option>
<option value="2">Sebastian</option>
<option value="3">John</option>
<option value="4">Arthur</option>
<option value="5">Staszek</option>
<option value="6">Patryk</option>
<option value="7">Lucas</option>
<option value="8">Madlen</option>
<option value="9">Bartek</option>
<option value="10">Inter</option>
</select>
</body></html>
I have to select "drivers" depending on the "cars"
For example, when i select Volvo it atumatically should select Luiza, John and Staszek.
If i select saab, i must have selected Arthur, Inter, Lucas, Patryk
And if it is not possible, then after selecting from the "cars" select "drivers" should be disabled, and when i select "-" from "Cars", "drivers" should be active again.
do this with ajax and load the data from database if it is possible.
or try this with jquery
$(document).ready(function() {
$('#a2').attr("disabled", "disabled");
$('#a1').change(function() {
var str = "";
$("#a1 option:selected").each(function () {
str += $(this).text() + " ";
});
if(str.trim()=="-")
$('#a2').removeAttr("disabled");
else
$('#a2').attr("disabled", "disabled");
});
});
and give id for case as "a1" and drivers for "a2"
Whith jQuery you can do it easyly :
$(document).ready(function (){
$('#select-cars').change(function(){
var car = $('#select-cars').val();
// Uncheck ALL driver
$('#select-drivers option').each(function (index, value) {
$(this).removeAttr('selected');
});
// Check each driver in funcition of the car
if (car == 'volvo') {
//check Luiza etc
$('#select-drivers option[value=1]').attr('selected', 'true');
} else if (car == 'saab') {
}
});
});