How to hide select2 with options jQuery - javascript

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();
}
});

Related

Does not load for loop data in the dynamically created fields

I can see the list of components normally but when I use the "Add more" functionality it refuses to load the data. Any idea why?
Normal select which loads data from for loop (HTML page):
<select name="component" data-live-search="true" id="component" class="form-control" title="Dropdown field">
{% for i in component %}
<option value="{{i.id}}">{{i.name}}</option>
{% endfor %}
(Inspect page)
<select name="component" data-live-search="true" id="component" class="form-control" title="Dropdown field">
<option value="2">test2</option>
<option value="3">sdf</option>
<option value="4">qwerty</option>
<option value="5">qwerty</option>
<option value="6">example</option>
</select>
Now I'm dynamically creating fields using createElement and setAttribute
(HTML page)
var field = document.createElement('select');
field.setAttribute('name','component');
field.setAttribute('data-live-search','true');
field.setAttribute('id','component');
field.setAttribute('class','form-control');
field.setAttribute('title','Dropdown field');
survey_options.appendChild(field);
But this does not contain the data from the for loop similar to the normal select function. Am I missing something?
(Inspect page)
<select name="component" data-live-search="true" id="component" class="form-control" title="Dropdown field"></select>
You need to create dynamic element with different id and append the options from rendered element. Check the below snippet
function appendNewDynamicComponent() {
var survey_options = document.querySelector("#survey_options");
var field = document.createElement('select');
// Create a random number
var random = +(Math.random() * 1e5).toFixed(0) + Date.now();
field.setAttribute('name', 'component');
field.setAttribute('data-live-search', 'true');
// Append random number to id to make it unique for newly created element
field.setAttribute('id', 'component_' + random);
field.setAttribute('class', 'form-control');
field.setAttribute('title', 'Dropdown field');
survey_options.appendChild(field);
// Below two lines would update the options for dynamicay created elements from the already rendered element
field.innerHTML = document.querySelector('select#component').innerHTML;
field.selectedIndex = -1;
}
#survey_options [name="component"] {
margin: 8px;
}
<div id="survey_options">
<select name="component" data-live-search="true" id="component" class="form-control" title="Dropdown field">
<option value="2">test2</option>
<option value="3">sdf</option>
<option value="4">qwerty</option>
<option value="5">qwerty</option>
<option value="6">example</option>
</select>
</div>
<br/>
<button onclick="appendNewDynamicComponent()">
Add Dynamic Component
</button>

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>

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

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);
});

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 ??

Selecting Option in Select2 - Disable / Enable action not triggering

I have a single select Select2 drop down box and a blank textbox next to it that is disabled by default.
When the user selects an option, namely "ServiceNow" I would like the text box to set disabled to false.
Currently, the functionality seems random. Two of the four available options enable the field, two disable it. Not even the one I want enables it. What am I doing incorrectly here?
The form HTML
<div>
<label for="feature">Feature</label>
<select class="form-control select2" style="width: 100%;" name="feature" id="feature">
<option selected="selected" disabled="disabled">-Select-</option>
<option name="ServiceNow" value="ServiceNow">Service Now</option>
<option>Epic Upgrade</option>
<option>Alarais Interop</option>
<option>Pyxis Upgrade</option>
</select>
</div>
<div class="col-xs-4">
<label for="serviceNowID">ServiceNow ID</label>
<input type="text" class="form-control" name="serviceNowID" id="serviceNowID" disabled="disabled" placeholder="ServiceNow ID (This doesn't work yet.)">
</div>
Related JS
<script>
//Get the ServiceNow thing to unlock on option select
//Evaluate if option is selected
$('#feature').on("select2:selecting", function(e) {
var choice = $(this).find('option').val();
if ($(this).val() == 'ServiceNow') {
document.getElementById("serviceNowID").disabled = false;
} else {
document.getElementById("serviceNowID").disabled = true;
}
});
</script>
Thanks!
When the user selects an option, namely "ServiceNow" I would like the text box to set disabled to false.
Maybe you should use the 'select' event instead of 'selecting'?
$('#feature').on("select2:select", function(e) {
...
Here is an example which may help you:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="feature">Feature</label>
<select class="form-control select2" style="width: 100%;" name="feature" id="feature">
<option selected="selected" disabled="disabled">-Select-</option>
<option name="ServiceNow" value="ServiceNow">Service Now</option>
<option>Epic Upgrade</option>
<option>Alarais Interop</option>
<option>Pyxis Upgrade</option>
</select>
</div>
<div class="col-xs-4">
<label for="serviceNowID">ServiceNow ID</label>
<input type="text" class="form-control" name="serviceNowID" id="serviceNowID" disabled="disabled" placeholder="ServiceNow ID (This doesn't work yet.)">
</div>
<script>
//Get the ServiceNow thing to unlock on option select
//Evaluate if option is selected
$('#feature').on("change", function(e) {
if ($(this).val() == 'ServiceNow') {
$("#serviceNowID").attr('disabled',false);
} else {
$("#serviceNowID").attr('disabled',true);
}
});
</script>

Categories