How to get the selected text of options in multiple select? - javascript

I am trying to get the selected option in multiple select, I can get the value in the form of an array, but I can't get the text of the option.
$(function() {
$('#sizeAddCategory').change(function(e) {
var selected = $(e.target).text();
console.log("selected " + selected);
$('#textAreaAddCategory').val(selected.join(','));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-6">
<label for="sel1">Select Sizes (hold ctrl or shift (or drag with the mouse) to select more than one):</label>
<br/>
<select required class="form-control" id="sizeAddCategory" multiple>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="name">Selected Sizes</label>
<br/>
<textarea required disabled rows="4" class="form-control" id="textAreaAddCategory"></textarea>
</div>
On $(e.target).text(), I am getting all the options text, I need the text of only selected options, so I can display it in the textarea.

Using .text() on a select will give the text of the control - i.e. all of the options, not just the selected ones.
To get the selected text (not value as you pointed out you can already get), you can use:
$(this).find("option:checked").map((i,e)=>$(e).text()).toArray();
Here, $(this).find("option:checked") will give you the option elements that have been selected while the .map will return the .text() for each of those values into a jquery array, with .toArray() to convert to a normal js array.
$(function() {
$('#sizeAddCategory').change(function() {
var selected = $(this).find("option:checked").map((i,e)=>$(e).text()).toArray();
console.log("selected", selected);
$('#textAreaAddCategory').val(selected.join(','));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-6">
<label for="sel1">Select Sizes (hold ctrl or shift (or drag with the mouse) to select more than one):</label>
<br/>
<select required class="form-control" id="sizeAddCategory" multiple>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="name">Selected Sizes</label>
<br/>
<textarea required disabled rows="4" class="form-control" id="textAreaAddCategory"></textarea>
</div>

It's because the target that you're defining is in the select tag. Instead of using:
$('#sizeAddCategory').change(function(e) {
use:
$('.option-category').click(function(e) {
and add a class in the options:
<option value="{{$size->id}}" class="option-category">{{$size->name}}</option>

you write :
var selected = $(e.target).text();
you should get the value of selectbox and
you should write
var selected = $(e.target).val();

oh my god
i right now understand what did you mean
ok
write :
$("#selectBox").change(function(e){
var x = $(e.target).find("option:checked").text();
console.log(x);
});

Related

Remove error text when input is unlocked in jquery

I have a form with a select, input and a function that locks my input when an option is selected.
I added a warning that inputs are locked when someone selects an option. I would like to add a function to remove this warning when someone chooses an option with value="".
It's removing my warning but for example when I choose option text 1 then text 2 my warning displays twice and then when I choose a selection with first option it removes warning but only first.
How to change it so that the warning displays only once, and not more times, and removes it after select with option first.
$(function() {
$('#stato').change(function() {
var value = $(this).val(); //Pobranie wartości z tego selecta
if (value == "") {
$('#data_consegna').prop('disabled', false);
$("#error").remove();
} else {
$('#data_consegna').prop('disabled', true);
$('#data_consegna').after('<div id="error" style="color:red;">Input locked</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-4">
<label>Enabled </label>
<select name="stato" id="stato" class="form-control">
<option value="">Choose</option>
<option value="Text1">Text1</option>
<option value="Text2">Text2</option>
<option value="Text3">Text3</option>
<option value="Text4">Text4</option>
</select>
</div>
<div class="col-4">
<label>Disabled when choose option in select</label>
<input id="data_consegna" type="text" class="form-control" name="data_consegna" placeholder="Data Consegna" />
</div>
my warning displays twice
You don't check if it's already there or remove it.
removes only first
IDs must be unique, so $("#error").remove(); will only remove the first one. Use classes instead of IDs to remove multiple elements. If you only add once, this would not be an issue; just explaining why it removes only the first.
As noted in the other answer, the best solution is to simply .show()/.hide(), so I won't repeat that here.
To update your code, you can always remove the error, then add it back if needed - this isn't the most efficient as noted above.
Updated snippet:
$(function() {
$('#stato').change(function() {
var value = $(this).val(); //Pobranie wartości z tego selecta
// always remove any existing error
$("#error").remove();
if (value == "") {
$('#data_consegna').prop('disabled', false);
} else {
$('#data_consegna').prop('disabled', true);
$('#data_consegna').after('<div id="error" style="color:red;">Input locked</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-4">
<label>Enabled </label>
<select name="stato" id="stato" class="form-control">
<option value="">Choose</option>
<option value="Text1">Text1</option>
<option value="Text2">Text2</option>
<option value="Text3">Text3</option>
<option value="Text4">Text4</option>
</select>
</div>
<div class="col-4">
<label>Disabled when choose option in select</label>
<input id="data_consegna" type="text" class="form-control" name="data_consegna" placeholder="Data Consegna" />
</div>
Also note, as it's using an ID, it can only be used for a single error message.
The simple way to achieve what you require is to have the notification div always contained in the DOM, but hidden, and then hide/show it depending on the state of the select, like this:
jQuery(function($) {
$('#stato').change(function() {
var value = $(this).val();
if (value == "") {
$('#data_consegna').prop('disabled', false);
$("#error").hide();
} else {
$('#data_consegna').prop('disabled', true);
$('#error').show();
}
});
});
#error {
color: red;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-4">
<label>Enabled </label>
<select name="stato" id="stato" class="form-control">
<option value="">Choose</option>
<option value="Text1">Text1</option>
<option value="Text2">Text2</option>
<option value="Text3">Text3</option>
<option value="Text4">Text4</option>
</select>
</div>
<div class="col-4">
<label>Disabled when choose option in select</label>
<input id="data_consegna" type="text" class="form-control" name="data_consegna" placeholder="Data Consegna" />
<div id="error">Input locked</div>
</div>

HTML Form Select Dropdown Options and Hidden Form Fields Not showing in PHP Form using JS Script

Recently i set up a script in JS with help from Stack to show a Form Row labled "other" when i select an option called "Other" from a dropdown option above. Example is below. This works well for one dropdown. But as soon as I add another dropdown Menu and "other" form row the JS code breaks and neither the 1st or 2nd Form Dropdown Options get posted to the Database and the form row "other" does not show. I hope i have explained the issue correctly. I essentially want one JS script to repeat for all dropdown forms so when "other" option value is selected i want the form row "other" to display below so custom data can be typed in. Using Bootstrap 4.3.1 with all JS querir plugins working. The datbase is connected with no issues posting data when its just a text field. So i was hoping someone might have work around and i will have a lot of dropdowns with the "Other" form row posting different form data in to the database. Many thanks.
<script>
function handleSelect() {
document.getElementById("other").value = document.getElementById("mySelect").value;
var selected = document.getElementById("mySelect").value;
var details = document.getElementById("other-details");
if (selected === "") {
details.classList.remove("d-none");
details.classList.add("d-block");
} else {
details.classList.remove("d-block");
details.classList.add("d-none");
}
}
</script>
<div class="form-row">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<label class="control-label custom_label col-xs-12">Cemetery</label>
<select name="cemetery" class="form-control" id="mySelect" onchange="handleSelect();">
<option value="select" selected="selected">Select Cemetery</option>
<option value="Akatarawa">Akatarawa</option>
<option value="Taita">Taita</option>
<option value="Wainuiomata">Wainuiomata</option>
<option value="Whenua Tapu">Whenua Tapu</option>
<option value="Makara">Makara</option>
<option value="Karori">Karori</option>
<option value="St Johns">St Johns</option>
<option value="Awa Tapu">Awa Tapu</option>
<option value="Paraparaumu">Paraparaumu</option>
<option value="">Other</option>
</select>
</div>
</div>
<div class="form-row d-none" id="other-details">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<input type="text" id="other" class="form-control" name="cemetery" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<label class="control-label custom_label col-xs-12">Headstone - Stone Color</label>
<select name="headstone_color" class="form-control" id="mySelect" onchange="handleSelect();">
<option value="headstone_color" selected="selected">Select Headstone - Stone Color</option>
<option value="Black">Black</option>
<option value="African Grey">African Grey</option>
<option value="Platinum Blue">Platinum Blue</option>
<option value="Blue Pearl">Blue Pearl</option>
<option value="Emerald Pearl">Emerald Pearl</option>
<option value="White Pearl">White Pearl</option>
<option value="Imperial Red">Imperial Red</option>
<option value="Balmoral Red">Balmoral Red</option>
<option value="G603-Chinese White/Grey">G603-Chinese White/Grey</option>
<option value="">Other</option>
</select>
</div>
</div>
<div class="form-row d-none" id="other-details">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<input type="text" id="other" class="form-control" name="headstone_color" />
</div>
</div>
Please check the select id. both of the select has the same id as myselect. The id must be unique. So please make your code generic and use some unique ids.
Thanks
Something like this?
<script>
function handleSelect() {
document.getElementById("other1").value = document.getElementById("mySelect1").value;
var selected = document.getElementById("mySelect1").value;
var details = document.getElementById("other-details1");
document.getElementById("other2").value = document.getElementById("mySelect2").value;
var selected = document.getElementById("mySelect2").value;
var details = document.getElementById("other-details2");
if (selected === "") {
details.classList.remove("d-none");
details.classList.add("d-block");
} else {
details.classList.remove("d-block");
details.classList.add("d-none");
}
}
</script>
and so on ??

How to hide select2 with options jQuery

I have select form with options, for search by keywords. I'm using select2 lib.
But my select form is created dynamically, and I want to hide and show some select form depending on user's choice.
Now the problem is that, if I choose something from the list:
For ex Production plant, it will appear new select form in which I have options. (it's working good)
If I again go to Production resources and choose another type:
Now I chose Production segment and prev select form is hidden, but in case if I want to go back to the Production plant, it will not appear:
My code:
$("#productionResources").change(function () {
var prodRes = $("#productionResources :selected").html();
$("#selectedProdRes").html(prodRes);
var id = $(this).val();
if (id != "") {
$('#' + id).select2().next().show();
}
idChanging(id);
});
function idChanging(id) {
$("#productionResources").change(function () {
$('#' + id).select2().next().hide();
});
}
HTML:
<div class="display-in-row">
<label>Production resources</label><br>
<select class="form-control" id="productionResources">
<option selected></option>
<option value="productionPlant">Production plant</option>
<option value="productionSegment">Production segment</option>
<option value="valueStream">Value stream</option>
<option value="workCenterGroup">Work center group</option>
<option value="workCenter">Work center</option>
<option value="station">Station"</option>
</select>
</div>
<div class="display-in-row">
<div class="col-12">
<label id="selectedProdRes"></label><br>
<select asp-for="ProductionPlantId" asp-items="Model.ProductionPlant" class="form-control content" id="productionPlant"></select>
<select asp-for="ProductionSegmentId" asp-items="Model.ProductionSegment" class="form-control content" id="productionSegment"></select>
<select asp-for="ValueStreamId" asp-items="Model.ValueStream" class="form-control content" id="valueStream"></select>
<select asp-for="WorkCenterGroupId" asp-items="Model.WorkCenterGroup" class="form-control content" id="workCenterGroup"></select>
<select asp-for="WorkCenterId" asp-items="Model.WorkCenter" class="form-control content" id="workCenter"></select>
<select asp-for="StationId" asp-items="Model.Station" class="form-control content" id="station"></select>
</div>
</div>
The problem comes from your function idChanging():
As soon as you change the 1st select, the event of idChanging() is set and remains. So everytime you select #productionResources, all the events defined by idChanging() will get triggered, so all the previously selected selects will be hidden.
The following should work:
I add a class secondary-select to all the secondary selects to facilitate, but this is not required:
<div class="display-in-row">
<div class="col-12">
<label id="selectedProdRes"></label><br>
<select asp-for="ProductionPlantId" asp-items="Model.ProductionPlant" class="form-control content secondary-select" id="productionPlant"></select>
<select asp-for="ProductionSegmentId" asp-items="Model.ProductionSegment" class="form-control content secondary-select" id="productionSegment"></select>
<select asp-for="ValueStreamId" asp-items="Model.ValueStream" class="form-control content secondary-select" id="valueStream"></select>
<select asp-for="WorkCenterGroupId" asp-items="Model.WorkCenterGroup" class="form-control content secondary-select" id="workCenterGroup"></select>
<select asp-for="WorkCenterId" asp-items="Model.WorkCenter" class="form-control content secondary-select" id="workCenter"></select>
<select asp-for="StationId" asp-items="Model.Station" class="form-control content secondary-select" id="station"></select>
</div>
</div>
$("#productionResources").change(function () {
// Define title
var prodRes = $("#productionResources :selected").html();
$("#selectedProdRes").html(prodRes);
// Make sure none of the 2nd select is visible
$('.secondary-select').select2().next().hide();
// Display the select according to the ID
var id = $(this).val();
if (id !== '') {
$('#' + id).select2().next().show();
}
});

Getting the name of a drop-down selection using JavaScript

I'm using JavaScript to pull in some information into a list and I'm not sure how to target a drop-down selection.
This is what I'm using to grab the result of a checked radio button:
RequestType: $("input[name=requestType]:checked").val(),
How would I be able to use the same format to grab the selection of a drop-down?
SessionType:
You don't need to call the function on every click, just a listener for the change-event is normally enough.
If you also want to get the value of the select-input at other moments, you can save the selected value in an variable or query the input-selects with the :selected-option.
$('#rChoices').on('change', function(event) {
let value = event.target.value;
console.log(value);
});
$('#btnGetValue').on('click', function(event) {
let value = $('#rChoices option:selected').val();
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group row rChoices">
<label for="rChoices" class="col-form-label">Please choose a application below:</label>
<select class="form-control" id="rChoices">
<option class="" selected disabled>---------</option>
<option value="onedrive" id="onedrive">OneDrive</option>
<option value="teams" id="teams">Teams</option>
<option value="outlook" id="outlook">Outlook</option>
<option value="officesuite" id="officesuite">Office Suite</option>
<option value="planner" id="planner">Planner</option>
<option value="sharepoint" id="sharepoint">SharePoint</option>
<option value="stream" id="stream">Stream</option>
<option value="yammer" id="yammer">Yammer</option>
</select>
<div class="help-block with-errors"></div>
</div>
<button id="btnGetValue">Get Value</button>
This worked for my current situation:
SessionType: $('#rChoices :selected').text()

jQuery Check Other Select Elements Once This Is Selected

I have 3 HTML select under 1 div :
<div id="kurir_list">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
</div>
and I have this jquery :
$(".tarif").change(function() {
if ($(".tarif").is(':disabled')) {
alert ("yes you still have disabled element, next button disabled");
} else {
alert ("no, you don't have disabled element");
// check the other select value
$(".tarif").each(function() {
alert($(this).val());
});
}
});
every time a .tarif is selected, I need to check the other two select element value. whether it's still empty or not. but, my jquery code alert all 6 values from all select elements.
how to make jquery to be able to inform me, whether in #kurir_list still have empty select or not. thank you.
Perhaps you can try something like this, look at every select in your wrapper, if any have an empty val() then your variable will be true, in which case you can do something
var emptySelect = false;
$('#kurir_list select').each(function(){
if (!$(this).find('option:selected').val()) {
emptySelect = true;
}
});
alert(emptySelect);

Categories