Conditional on Multi Select for certain options only - javascript

I have a multiselect where I need to show/hide another select based on options selected in the first select. There are 3 options that should cause the other select to appear - all other options should not cause anything to change.
I have it working if individually the options are selected. However if one of the options is selected along with any other options it doesn't work.
DUE to CMS constraints I am unable to add classes to the options.
This is my current jQuery code.
$('#freeform_how_would_you_best_describe_your_companys_research_activity').change(function() {
var selectedItems
if ($(this).val() == 'Drug Discovery/Development' || $(this).val() == 'Therapeutics' || $(this).val() == 'Vaccines' ) {
$('label[for="freeform_tell_us_more_about_your_research_activity"], select#freeform_tell_us_more_about_your_research_activity').slideDown();
} else {
$('label[for="freeform_tell_us_more_about_your_research_activity"], select#freeform_tell_us_more_about_your_research_activity').slideUp();
}
});
Please advise

Multiselect .val() returns array not a single value. Take it in account.
$('#sel').change(function() {
var arr = $(this).val();
if (arr.indexOf('one') > -1 || arr.indexOf('two') > -1 || arr.indexOf('three') > -1) {
console.log('do this');
} else
console.log('do that');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel" multiple size="5">
<option>one</option>
<option>two</option>
<option>three</option>
<option>else</option>
</select>

Some additionaly googling and expermenting later I found a solution
$('#freeform_how_would_you_best_describe_your_companys_research_activity').change(function() {
var values = $(this).val();
console.log(values)
if(values.includes("Vaccines")|| values.includes("Therapeutics") || values.includes("Drug Discovery/Development")){
$('label[for="freeform_tell_us_more_about_your_research_activity"], select#freeform_tell_us_more_about_your_research_activity').slideDown();
} else {
$('label[for="freeform_tell_us_more_about_your_research_activity"], select#freeform_tell_us_more_about_your_research_activity').slideUp();
}
});

Related

Angular custom filter with multiple dropdown conditions

I am trying to filter with multiple dropdowns conditions. I am able to figure out how to filter them one by one. I want them to show all when nothing is chosen, value = "".
<select class="form-control" ng-model="filter.grade">
<option ng-repeat="grade in product_grades" value="{{grade}}">{{grade}}</option>
</select>
<select class="form-control" ng-model="filter.slump">
<option ng-repeat="slump in product_slumps" value="{{slump}}">{{slump}}</option>
</select>
<select class="form-control" ng-model="filter.flow">
<option ng-repeat="flow in product_flows" value="{{flow}}">{{flow}}</option>
</select>
<select class="form-control" ng-model="filter.last_delivered">
<option ng-repeat="last_delivered in product_last_delivereds" value="{{last_delivered}}">{{displayDate(last_delivered)}}</option>
</select>
<tr ng-repeat="job_product in job_products | filter : customFilter">
For one drop down, I use this.
$scope.customFilter = function (data) {
if (data.Grade === $scope.filter.grade) {
return true;
} else if ($scope.filter.grade === '') {
return true;
} else {
return false;
}
};
But when I use this for multiple dropdowns, it works.
$scope.customFilter = function (data) {
if (data.Grade === $scope.filter.grade &&
data.Slump === $scope.filter.slump &&
data.Flow === $scope.filter.flow &&
data.LastDlvDate === $scope.filter.last_delivered) {
return true;
} else if ($scope.filter.grade === '') {
return true;
} else {
return false;
}
};
When I choose a drop option now it doesn't show anything.
Here's a plunker:
http://plnkr.co/edit/elwmuqLvhYhIw3rUrEO1?p=preview
I am not sure why $filter for the date is not working.
But I want to show concrete A when choosing grade = "1".
Here is a working example - http://plnkr.co/edit/VTnbqchrdsrN5w0mflji?p=preview
What was wrong?
The $scope.customFilter conditionals were wrong - data.grade === $scope.filter.grade. The default value for each $scope.filter.* was empty string '' and because you used && them all together, while data.grade was selected, the others were '' === undefined which ends up being false. So I changed the conditionals to !$scope.filter.grade || data.grade === $scope.filter.grade && .... This works because I check if the select has not changed at all, I ignore it by returning true and then if the selected one equals to the data. That also made } else if ($scope.filter.grade === '') { irrelevant.
Additional notes on the implementation:
You do not have to initialize the scope variables $scope.filter.grade = "";, Angular will on first select change.
Fixed the date filter part, the $scope.displayDate is not needed. You can apply the filter in template {{last_delivered | date: 'dd-MM-yyyy'}}

how to dynamically add REQUIRED attribute to input tags based on output of select tag using jquery?

I have a select tag with two options 'new' and 'edit'
when someone selects the 'new' option all the input tags in that form should be marked required and when someone selects 'edit' only a few should be marked required.
<select name="todo" id="todo" required>
<option value="">---</option>
<option value="new">Add</option>
<option value="edit">Edit</option>
</select>
Now I tried some functions but they don't seem to work
<script>
var todo = $('#todo option:selected').text();
if (todo == "new") {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
</script>
and
<script>
function req() {
var selectBox = document.getElementById('todo');
var userInput = selectBox.options[selectBox.selectedIndex].value;
if (userInput == 'new') {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
}
</script>
where
<select name="todo" id="todo" onchange="return req();" required></select>
just to be sure if it works I put a alert() method in the if condition, but that alert is never fired.
PS. one of the input tags is
<input type="text" id="Name" name="Name">
Thank you for your time in advance...
EDIT
As pointed out by #Maximillian Laumeister in second snippet there was a typo error (which I have corrected here). (sorry for that)
This should be ebough to get you going.
onchange detects whenever a different selection is made. Then based on what option is selected you perform the different instructions.
jQuery(document).ready(function(){
jQuery('#todo').on('change', function(event){
alert(this.value);
if(this.value === 'edit'){
}
else if(this.value === 'new'){
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select name="todo" id="todo" required>
<option value="">---</option>
<option value="new">Add</option>
<option value="edit">Edit</option>
</select>
In your script here you have a typo that throws a console error:
function req() {
var selectBox = document.getElementById('todo');
var userInput = selectBox.options[selectbox.selectedIndex].value;
if (userInput == 'new') {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
}
Where it says
selectBox.options[selectbox.selectedIndex].value
selectBox needs a capitalization like this:
selectBox.options[selectBox.selectedIndex].value
It seems to be working for me with that one change.
Also, since you asked, your first script isn't working because it needs to be bound to run when the select changes, just like with the first one. In addition, you need to use jQuery's val instead of text to get the value of an option tag. Here is a working version of your second script:
$("#todo").change(function () {
var todo = $('#todo option:selected').val();
if (todo == "new") {
$('#Name').attr('required',true);
} else if (todo == "edit") {
//code
}
});
Try this:
$("select").change(function(){
if($(this).val() === "new")
$("#Name").attr("required","required");
});
You used the option text which is "Add" but in your if statement you compared it to the string "new". That's the reason your code didnt work as expected.

How do I show a message for a specific dropdown selection using javascript?

I would like to show a message when someone makes a specific selection from an HTML dropdown list. I have this so far:
<select name="configoption[56]" onchange="recalctotals()">
<option value="235"">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
And the script:
$(document).ready(function() {
$('#configoption[56]').change(function() {
var selectedValue = $('#configoption[56]').find(":selected").text();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
The above does not appear to be working for me, any suggestions? I would also like to be able to show the message on multiple selected values.
Well your .change function is specifically binded to an element with id="configoption[56]" So just add id to your select element as below
<select name="configoption[56]" id="configoption[56]" onchange="recalctotals()">
//Options
</select>
UPDATE
As per #T.J.Crowder's suggestion on invalid selector I would like to modify a slight change on the id. You can use configoption56 as id and write your select.change as follows:
<select name="configoption[56]" id="configoption56" onchange="recalctotals()">
<!--Options-->
</select>
.change
$('#configoption56').change(function() {
//other codes
});
$('#configoption[56]') is looking for an element with the id, not name, configoption[56] (or it would be, but the selector is invalid, you'd have to escape those brackets).
To use the name:
$('select[name="configoption[56]"]')...
Separately, you can just use val, you don't have to use find to get the selected option. You can also use toggle for show/hide:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
$('.message').toggle($(this).val() == '235');
});
});
Re your comment about toggling based on || and two values:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
var value = $(this).val();
$('.message').toggle(value == '235' || value == '123');
});
});
I should be doing it like this: http://jsfiddle.net/nmn17cr6/
HTML:
<select name="configoption[56]" id="configoption" onchange="recalctotals()">
<option value="1">Dummy</option>
<option value="235">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
CSS:
.message {
display:none;
}
jQuery:
$(document).ready(function() {
$('#configoption').change(function() {
var selectedValue = $(this).val();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
Your approach needs a little modification. All you had to do these changes
$(document).ready(function() {
$("select[name=configoption[56]]").change(function() { // change jquery selector for name
var selectedValue = $('#configoption[56]').val(); // and val to get the value
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
And with the same jQuery code. below has to be
<select name="configoption[56]" >
// onchange="recalctotals()"> was not required

form select option dynamic attr

I need to make Select name with option value, to select a specific value or index. the data where comes from db in a value "{{design}}".
I do get the value currectly, but I dont manage to set "selected" on the currect option value.
here is the code:
console.log("{{design}}");
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( options[i].innerHTML==="{{design}}")
{
options.selectedIndex=i;
}
}
});
the html is :
<select name="design" required id="design" >
<option value="1">flowers</option>
<option value="2">classic</option>
<option value="3">roses</option>
</select>
I need to make to currect {{design}} value, lets say it's 2, so it will be <option value="2" selected>classic</option>`
thanks!
SOLVED
Hi, found the solution to the issue, if anyone eles goes into trouble.
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( $('select').children('option')[i].value === "{{design}}")
{
$('select').children('option')[i].selected=true;
}
}
});
the currect way is to find the right option value and then-> [i].selected=true
goodluck
Try this
var selectedvalue=2; //option with value 2 should be selected
$("#design option[value=selectedvalue]").attr("selected","selected");
Hope this helps...
If I understood right, you are on the right path just taking a minor detour. Try this:
if ( options[i].innerHTML==="{{design}}")
{
options.attr('selected', 'selected');
}
The example of .each() usage:
$(document).ready(function(){
$('select option').each(function(i){
if( i.value === "{{design}}"){
$(this).attr('selected','selected');
}
});
});
try this:
$(document).ready(function(){
$('select option').each(function(i){
//if this option contains the word "{{design}}" Then this is selected
if( $(this).html().indexOf("{{design}}") != -1)
$(this).attr('selected',true);
});
});

How to get checkbox value in multiselect onchange event

I implement jquery multiselect and its working properly now i need to add extra feature that when a user select another option in dropdown ( check another checkbox ) then i want to get the value of the related option
in above picture in did not insert checkbox it is automatically inserted by jquery now i want that if i select the check =box with XYZ then i want to get the value of XYZ which is the id of XYZ
here is how i implemented it
<select multiple="multiple" id="CParent" name="parent" class="box2 required">
#foreach (var item in Model.Categories.OrderBy(c => c.Name))
{
if (Model.Coupon.Categoryid.Id == item.Id)
{
<option selected="selected" value="#item.Id">#item.Name</option>
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
</select>
and it is how it looks like after rendering in browser source
Thanks in advance for helping me .
what i tried yet
$('#CParent input:checked').change(function () {
var parentid = $(this).val()+'';
var array = parentid.split(",");
alert(array);
getchildcat(array[array.length -1]);
});
});
Edit
Code to initialize multiselect
$("#CParent").multiselect({
header: "Choose only THREE items!",
click: function () {
if ($(this).multiselect("widget").find("input:checked").length > 3) {
$(warning).show();
warning.addClass("error").removeClass("success").html("You can only check three checkboxes!");
return false;
}
else if ($(this).multiselect("widget").find("input:checked").length <= 3) {
if ($(warning).is(":visible")) {
$(warning).hide();
}
}
}
});
try this
$('#CParent').val();
this will give you the selectbox value
OR
from docs
var array_of_checked_values = $("#CParent").multiselect("getChecked").map(function(){
return this.value;
}).get();

Categories

Resources