How to get value of selected text by tag name, not id - jquery-selectors

I only have names of tags, no ids. Need to figure out a way to get text of selected dropdowns. This is the HTML:
<SELECT name="selectRightName">
<OPTION value="76" >1</OPTION>
<OPTION value="200" >2</OPTION>
<OPTION value="201" >3</OPTION>
<OPTION value="202" >4</OPTION>
<OPTION value="203" >5</OPTION>
</SELECT>
By some reason this returns empty value:
$(document).ready(function(){
alert(productName);
alert(selectRightName);
$('select[name=selectRightName]').change(onSelectChange);
$('select[name=selectLeftName]').change(onSelectChange);
});
function onSelectChange(){
var fselected = $('select[name=selectRightName] option:selected');
var sselected = $('select[name=selectLeftName] option:selected');
alert(fselected + " " + sselected);

The attribute in your HTML starts with a capital S, but your selector isn't reflecting it, and attribute selectors are case-sensitive everywhere.
var fselected = $('select[name=SelectRightName] option:selected');
Also there's a stray ) in your HTML, not sure what that's doing there but you should remove it.

Related

How to add an input text field into a select element

I try to develop a custom selectbox with „chosen“ (https://harvesthq.github.io/chosen/).
How can I achieve to add a single input text field ("Eigene Auflage") at the bottom of the opened select box which adds his value to the top, if someone clicks at it types something in. See image: )
Do I have to change the select/option into a ul/li ?
Here is my markup:
<select class="replace-select">
<option value="select-filled-1">Select Filled 1</option>
<option value="select-filled-2">Select Filled 2</option>
<option value="select-filled-3">Select Filled 3</option>
<option value="select-filled-4">Select Filled 4</option>
<option value="select-filled-5">Select Filled 5</option>
<option value="select-filled-6">Select Filled 6</option>
<option value="select-filled-7">Select Filled 7</option>
<option value="select-filled-8">Select Filled 8</option>
</select>
You can do this just by appending a text box to the chosen's created dropdown div, with events to add the contents of the text box to the original select. It's pretty much just a matter of using jQuery to append the box to the right element.
How it works is when you initialize chosen, it hides the select and creates a custom set of nested li's within a few divs. The dropdown div has class .chosen-drop, so you just need to use jQuery to select that element with $(".chosen-drop"), then append the text box to that using $.append(...). Your event handlers then just need to take the contents of that text box and add it to the original select.
$(document).ready(function() {
//initialize the chosen.
$("#chosenSelect").chosen({
width: "100px"
});
//append text box
$("#selectContainer .chosen-drop").append('<input class = "chosen-input"/>');
//click event for enter key
$('.chosen-input').bind("enterKey", function(e) {
//get value of text box, and add it to the select.
var newValue = $(".chosen-input").val();
//insert newValue into an option HTML with template literals
var optionHTML =`<option value="${newValue}">${newValue}</option>`;
$("#chosenSelect").prepend(optionHTML).trigger("chosen:updated");
//clear the textbox after adding to the select
$(".chosen-input").val("");
});
//watch for enter key
$('.chosen-input').keyup(function(e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
});
.chosen-input {
width: 100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<link href="https://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />
<div id="selectContainer">
<label>Press enter to add new item to select</label>
<br>
<select id="chosenSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
Let me know if you need an explanation of any elements in my example.

Angular2 reactive forms select how to set invalid?

I use reactive forms within my app. In a certain form I want to display a required (Validators.required) select like this:
<select class="form-control"
[id]="dformControl.key"
[formControlName]="dformControl.key"
[multiple]="dformControl.multiple">
<option *ngIf="!dformControl.value"
value="undefined">
Choose ...
</option>
<option *ngFor="let opt of dformControl.options"
[value]="opt.value"
[selected]="dformControl.value == opt.value">
{{opt.label}}
</option>
</select>
The problem is whether I use value="undefined" or value="" the form control still is set to valid because it got a value. Do not present the value attribute results in value="Choose ...".
Am I using select with reactive forms in a false way or how would I be able to make the option "Choose ..." being not valid??
Assigning initial value of select control to null will do the trick. Try below,
model_property = null
....
this.fb.group({
....
'control_key' : [this.model_property, Validators.required]
...
})
Check this Plunker!!, Look into app/reactive/hero-form-reactive.component.ts file.
I updated the Plunker to include below and it seems to be working,
<select id="power" class="form-control"
formControlName="power" required >
// see the value is set to empty,
<option value="">Choose...</option>
<option *ngFor="let p of powers" [value]="p">{{p}}</option>
</select>
Hope this helps!!
What I do is add a blank option and when that is selected since there is no value it is not valid.
<select class="form-control"
[id]="dformControl.key"
[formControlName]="dformControl.key"
[multiple]="dformControl.multiple">
<option></option>
<option *ngFor="let opt of dformControl.options"
[value]="opt.value"
[selected]="dformControl.value == opt.value">
{{opt.label}}
</option>
</select>

Get text from selected option

I have a form with some <select> bound to an object comming from a webservice :
<select [(ngModel)]="configDatas.type" name="type" id="type">
<option value="0">Disabled</option>
<option value="1">Day</option>
<option value="2">Week</option>
</select>
<select [(ngModel)]="configDatas.days" name="days" id="days">
<option value="0">Monday</option>
<option value="1">Tuesday</option>
<option value="2">Wednesday</option>
</select>
Everything work as expected on this side.
I need to add at the end of my form a sentence which is a summary of the users's choice.
Something like :
<span> You selected type {{configDatas.type}} with day {{configDatas.days}}</span>
but instead of the value i'm looking for the text of the option.
I would like to see something like :
You selected type Week with day Monday
Is this possible directly in the template without using any kind of conversion on the component side ?
This may be a version difference, but the accepted answer didn't work for me. But pretty close did. this is what did the trick for me.
(change)="updateType(type.options[type.options.selectedIndex].text)
Updated: You can use the change event to keep track of the newly selected option:
<select [(ngModel)]="configDatas.type" name="type" id="type" #type (change)="updateType(type.options[type.value].text)">
<option value="0">Disabled</option>
<option value="1">Day</option>
<option value="2">Week</option>
</select>
<select [(ngModel)]="configDatas.days" name="days" id="days" #days (change)="updateDay(days.options[days.value].text)">
<option value="0">Monday</option>
<option value="1">Tuesday</option>
<option value="2">Wednesday</option>
</select>
<span> You selected type {{selectedType}} with day {{selectedDay}}</span>
export class App {
configDatas: any;
selectedType: string;
selectedDay: string;
constructor() {
this.configDatas = {
'type': '',
'days': ''
};
}
updateType(text: string) {
this.selectedType = text;
}
updateDay(text: string) {
this.selectedDay = text;
}
}
Updated Example http://plnkr.co/edit/ay7lgZh0SyebD6WzAerf
Another way to accomplish this is to use complex objects for your select list options.
You declare an interface for your options:
export interface Day {
id: number;
text: string;
}
Give it some options in the constructor:
this.days = [
{id: 0, text: 'Monday'},
{id: 0, text: 'Tuesday'},
{id: 0, text: 'Wednesday'}
];
Bind it to the option list. It's important to use ngValue here:
<select [(ngModel)]="configDatas.days" name="days" id="days">
<option *ngFor="let day of days" [ngValue]="day">{{day.text}}</option>
</select>
And finally output it:
<span> You selected type {{selectedType}} with day Id: {{configDatas.days.id}}, Text: {{configDatas.days.text}}</span>
Full example: http://plnkr.co/edit/kDanyC
Is this possible without keeping a separate array for each select ?
Not sure of the aversion to using two arrays to solve this but two functions could fix it.
<span> You selected type {{displayType(configDatas.type)}} with day {{displayDate(configDatas.days)}}</span>
Then just have some functions that return the text you want.
displayType(type) : string {
if (type == 0) {
return "disabled"
} else { //continue adding ifs
return ""
}
}
A objectively nicer way would to have two arrays that contain both the id and the text to display and then use a *ngFor to build the options up.
In simple way to get selected option text using (change)="selectDay($event)" event
<select [(ngModel)]="configDatas.days" name="days" id="days" (change)="selectDay($event)">
<option value="0">Monday</option>
<option value="1">Tuesday</option>
<option value="2">Wednesday</option>
</select>
In TS File
selectCity(event:any) {
console.log(event.target[event.target.selectedIndex].text);
let day = event.target[event.target.selectedIndex].text;
}

Change form action according to select option

I have a simple form:
<form name="simple" id="simple" method="post" action="X.php">
<select name="select">
<option value="none"> Select </option>
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
</form>
I want X (X.php) to change with option values.
For example, when user selects 1st, it should change to 1.php.
Is it possible?
Yes you can, example with jquery is as follows:
$("#selectID").change(function() {
var action = $(this).val();
$("#simple").attr("action", action + ".php"); // Can also use .prop("action", action + ".php");
});

Value of <select><option> coming back as string

Is there any way to have the value of an <option> to be set to an actual integer? I have the following html code:
<select id="proteinperc" onchange="setMacrosProtein()">
<option value="0" selected>0%</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
<option value="25">25%</option>
<option value="30">30%</option>
<option value="35">35%</option>
<option value="40">40%(Rec.)</option>
<option value="45">45%</option>
<option value="50">50%</option>
<option value="55">55%</option>
<option value="60">60%</option>
<option value="65">65%</option>
<option value="70">70%</option>
<option value="75">75%</option>
<option value="80">80%</option>
<option value="85">85%</option>
<option value="90">90%</option>
<option value="95">95%</option>
<option value="100">100%</option>
</select>
Then I have the script below that is trying to access these option values and perform calculations using them. The problem is that when I do any calculations with them, all I get is string concatenation or strange values.
function setMacrosProtein() {
myProtein = document.getElementById("proteinperc").value;
var removeValue = 101 - (myProtein + myFats + myCarbs);
alert(removeValue); // Alert here just for testing the first calculation.
var x = document.getElementById("fatperc").options.length;
for (i = 0; i < x; i++) {
// Check fatperc
if (document.getElementById("fatperc").options[i].value + myFats >= removeValue) {
document.getElementById("fatperc").options[i].disabled = true;
} else if (document.getElementById("fatperc").options[i].value + myFats < removeValue) {
document.getElementById("fatperc").options[i].disabled = false;
}
// Check carbperc
if (document.getElementById("carbperc").options[i].value + myCarbs >= removeValue) {
document.getElementById("carbperc").options[i].disabled = true;
} else if (document.getElementById("carbperc").options[i].value + myCarbs < removeValue) {
document.getElementById("carbperc").options[i].disabled = false;
}
}
//setCals();
}
If there is no way to return an integer from an option value, I do have a workaround in mind but with a small issue. I could set up a new array with mirroring values to the options list, ie: array[0] would be equal to option[0] and I could check against the array in my if statements.
However, how would I set a variable to the currently selected option this way? How do I reference the current selected option's position in the option array to get the mirrored position in my newly created array? To clarify, if the selected option is currently option[4], how do I reference its position to then pull array[4]'s value?
You could use parseInt() to get the int value from it like this:
myProtein = parseInt(document.getElementById("proteinperc").value);
In javascript file try to use parseInt(...).
Use the unary operator +. Easier than parseInt(). Simply put a plus in front of what you'd like to convert to a number.
Example:
<select id="movie">
<option value="10">Casablanca ($10)</option>
<option value="12">Rear Window ($12)</option>
<option value="8">Vertigo ($8)</option>
<option value="9">Rosemary's Baby ($9)</option>
</select>
const movieSelect = document.getElementById('movie');
const ticketPrice = +movieSelect.value;