Selecting Option in Select2 - Disable / Enable action not triggering - javascript

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>

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>

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

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

How to toggle bootstrap DatePicker by setting readonly attribute?

I tried to set datepicker to be enable or disable datepicker according first selection. If user select option "Applied", I would like to set readonly attribute to field datepicker and not allow it to be popup calendar.
My sample below produce two fields: Application Selection and DatePicker Fields:
$(document).ready(function(){
$('#NextFollowDate').datepicker({
format:"yyyy-mm-dd"
});
$('#ActivityType').on('change',function()
{
var actType = $(this).val();
if (actType=='3')
{
$('#NextFollowDate').attr('readonly','readonly');
}
else
{
$('#NextFollowDate').removeAttr('readonly');
}
});
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.js"></script>
<select class="form-control" id="ActivityType" name="ActivityType">
<option selected="" value="__None">--None--</option>
<option value="1">1 - First Appoinment</option>
<option value="2">2 - Second Appoinment</option>
<option value="3">3 - Applied</option>
</select>
<div class="form-group">
<label for="NextFollowDate" class="col-sm-2 control-label"><label for="NextFollowDate">Next Date</label></label>
<div class="col-sm-10">
<input class="form-control" id="NextFollowDate" name="NextFollowDate" type="text" value="" style="width: 214px;">
</div>
</div>
From readonly attribute does not stop DatePicker field from popup at all. Yet, setting $('#NextFollowDate').attr('disabled','disabled');, it would working fine. However, it is problematic when I submitted the form; therefore, I would like it to be readonly and prevent calendar from pop up.
Is there any way that I can archived that with readonly attribute? Thanks.

Show a specific dropdown box after select a option from another dropdown box

I have dropdown box list and have some forms .i want to show specific form against dropdown box value. suppose dropdown box contains two list such as: (i)Man (ii)Animal. when Man option is selected then it enters into a form which contains two option male and female.On the other hand(for animal) it enters into a form which contains three option lions,tigers,cow.
how to write this statement in a html and javascripts code ???
This is pretty simple, you can do this with a few lines of jquery, you just need to bind a select's onchange event to hide each form type, then show the right form based on the select's new value.
Here is an example of this working:
https://codepen.io/jcapinc/pen/YrJobM
JQuery/Javascript
$(function(){
var hidestuff = function(){
$(".man-form,.animal-form").hide();
}
$("select[name='formtype']").change(function(){
hidestuff();
var value = $(this).val();
if(value == "man"){
$(".man-form").show();
}
if(value == "animal"){
$(".animal-form").show();
}
});
hidestuff();
});
HTML
<div class="container">
<div class="col-md-offset-3 col-md-6">
<form>
<h1>Creature Form</h1>
<div class="form-group">
<label for="formtype">Choose Creature Type</label>
<select class="form-control" name="formtype">
<option value="">- Choose - </option>
<option value="man">Man</option>
<option value="animal">Animal</option>
</select>
</div>
<div class="man-form">
<div class="form-group">
<label for="manstuff">Man Stuff</label>
<input class="form-control" type="text"/>
</div>
</div>
<div class="animal-form">
<div class="form-group">
<label for="animalstuff">Animal Stuff</label>
<input class="form-control" type="text"/>
</div>
</div>
</form>
</div>
</div>
use this sample :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<select id="formSelector">
<option value="0">select form type</option>
<option value="humanForm">human</option>
<option value="animalForm">animal</option>
</select>
<div id="humanForm" style="display:none;">
<input type="radio" name="humanSelector" />Man
<input type="radio" name="humanSelector" />Woman
</div>
<div id="animalForm" style="display:none;">
<input type="radio" name="animalSelector" />cat
<input type="radio" name="animalSelector" />dog
<input type="radio" name="animalSelector" />lion
</div>
<script>
var formSelector = document.getElementById("formSelector");
var humanForm = document.getElementById("humanForm");
var animalForm = document.getElementById("animalForm");
formSelector.addEventListener("change", function (event) {
humanForm.style.display = "none";
animalForm.style.display = "none";
switch (formSelector.value) {
case "humanForm":
humanForm.style.display = "block";
break;
case "animalForm":
animalForm.style.display = "block";
break;
}
});
</script>
</body>
</html>
I assumed this was two selects, but I see you want to show/hide a form, in which case, I'd recommend Jeffrey's answer.
There needs to be some relation between the first select and the second select. One way would be to add an attribute called data-relation which connects both selects. On any change, the select will be updated. You will need to add things like initial display and displaying only non-hidden options, but I'll leave that for you.
var cat = document.getElementsByTagName('select')[0];
var opt = document.getElementsByTagName('select')[1];
cat.addEventListener('change', function(s) {
for (var i = 0; i < opt.options.length; i++)
opt.options[i].hidden = opt.options[i].dataset.relation !== s.target.value;
});
<select>
<option>man</option>
<option>animal</option>
</select>
<select>
<option data-relation=man>male</option>
<option data-relation=man>female</option>
<option data-relation=animal>lions</option>
<option data-relation=animal>tigers</option>
<option data-relation=animal>cow</option>
</select>

Categories