I have a select field with all countries listed. The option val is the country code so for the United States the option value is US.
I have a few products in a list which each have a unique country codes assigned to them in the html such as:
<div class="restricted-items" data-countries="["TR","UA","AE","GB","US"]"></div>
<div class="restricted-items" data-countries="["GB","US"]"></div>
etc
What I am trying to do is that when on change event the option value is US, it finds that value in the array show shows text. The trouble i am having is that the text will show for all classes with "restricted-items"
My code or attempt is:
$(document).on('change', '.fieldset.estimate.select[name="country_id"]', function() {
var blacklistCountries = JSON.parse(jQuery('.restricted-items').attr('data-countries'));
console.log($(this).val());
console.log(blacklistCountries);
if($.inArray($(this).find(':selected').val(), blacklistCountries) > -1){
$('.restricted-items').text('This item cannot be shipped to ' + $(this).find(':selected').attr('data-title'));
} else {
if ($('.restricted-items').text().length > 0) {
$('.restricted-items').empty();
}
}
});
Any help will be great thanks
Related
I am trying to build a student catalog. I have a structure which consists in Classes -> Groups -> Students.
I already have the classes and groups in my database. Each group belongs to a class.
As an example, I go to my Class page and I create class 1. After this, I go to my group page and add a group "A" that has class 1 assigned to it. I can add multiple groups to each class.
Now I want to create a student on my student page. To do this, I want to add the student in a specific group. To be able to chose the group, the admin has to firstly select the class from a select dropdown. After the class gets selected, the next select will render only the groups assigned to the selected class.
My solution for this right now is to set the $_GET super global with the class id that was selected by the user in the first dropdown. I do this via javascript function with window.location.href url change. I set the logic of the group dropdown to look for the $_GET variable before it renders the options.
I don't think this is a clean and good approach as the page is always refreshed when the location is reset and the input values are always reset.
I just want to use whatever the user has selected from the classes dropdown to render the options in the group dropdown. Is there anything that Laravel 8 built in features can do for me regarding this issue?
As a sample of what I am doing right now:
<select name="classes" id="classes" onchange="getClassID()"> // getClassID just changes the location and adds the selected class id to the url as a query string
#php
foreach ($classes as $class) {
if(isset($_GET['classID'])){
if($_GET['classID']*1 === $class->id){
echo " <option value={$class->id} selected>{$class->classes_number}</option>";
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
}
#endphp
</select>
<script>
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let option = document.getElementById("classes").value;
window.location.href='/students/create?classID=' + option;
}
</script>
<select name="group_id" id="group">
#php
// If the user has changed the initial classes select dropdown value, we will
// get all of the groups that have the class that was selected and display them
// as options in this select
if(isset($_GET['classID'])){
$classID = $_GET['classID']*1;
foreach ($groups as $group) {
if ($group->classes_id === $classID) {
echo "<option value={$group->id}>{$group->group_name}</option>";
}
}
}
else {//another code that handles the situation in which all classes are erased}
#endphp
</select>
Images with my form when the user selects different classes and the groups are rendered differently for each selected class:
Instead of reloading the page, you can get the options via api and create the second select on client-side.
var groupIdSelect = document.getElementById('group');
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let classID = document.getElementById("classes").value;
fetch('api/students/create?classID=' + classID)
.then((res) => res.json())
.then((groups) => {
for (group of groups) {
if (group.classes_id === classID) {
var option = document.createElement('option');
option.value = group.id
option.textContent = group.group_name;
groupIdSelect.appendChild(option);
}
}
})
}
UPDATE
I am working on SharePoint and Nintex Form which allows embedding JS into the form but uses NWF$ instances e.g. (NWF$('#' + varConcept) see an example here Javascript - How to hide a drop down control if it's empty
I have now created a question in the sharepoint section
There is a fieldname (not a dropdown) named varConcept and may contain values such as Pending, In Review, Accepted, In Work.
There is a dropdown menu named varConcept which holds following options: Updated, Reviewed, Already Implemented, Duplicate, Assigned and the idea behind all this is to make a script that checks the varStatus and shows relevant options in the dropdown box aka. varConcept.
In simple context:
IF varStatus contains "Pending" then show varConcept options Updated and Duplicate
IF varStatus contains "In Review" then show varConcept options Reviewed and Already Implemented
IF varStatus contains "Accepted" then show varConcept options Assigned
else hide everything
You can generate the dropdown using javascript and based on the status you create the dropdown options.
var currentStatus = 'Reviewed'; // load the current status of the dropdown
var div = document.querySelector("#container"),
frag = document.createDocumentFragment(),
select = document.createElement("select");
if (currentStatus === 'Accepted') {
select.options.add(new Option("Rejected", "Rejected"));
} else if (currentStatus === 'Reviewed') {
select.options.add(new Option("Accepted", "Accepted", true, true));
select.options.add(new Option("Rejected", "Rejected"));
} else if (currentStatus === 'Rejected') {
select.options.add(new Option("Accepted", "Accepted", true, true));
}
frag.appendChild(select);
div.appendChild(frag);
<div id="container">
</div>
You could add a "onchange" event to the select.
When the selection changes, you can hide/show options as you wish. This can be done based on the selected value.
const filterOptions = (e) => {
const selectedValue = e.options[e.selectedIndex].value;
for(const option of e.options){
option.classList.remove('hidden');
}
// always hide the initial "select one" option
e.options[5].classList.add('hidden');
if(selectedValue === 'pending'){
e.options[1].classList.add('hidden');
e.options[3].classList.add('hidden');
e.options[4].classList.add('hidden');
}
}
.hidden{
display: none;
}
<select name="" id="dropdown" onchange="filterOptions(this)">
<option value="pending">Pending</option>
<option value="accepted">Accepted</option>
<option value="reviewed">Reviewed</option>
<option value="rejected">Rejected</option>
<option value="already_done">Already Done</option>
<option id="initial" selected >Select one</option>
</select>
Yes, you can do that. Since your question is not completed with information like what is Status and how we are getting the value of Status.
Let us assume you are getting the value of Status from some API you build and your HTML is below
<ul>
<li class="myClass" id="accepted">Accepted</li>
<li class="myClass" id="reviewed">Reviewed</li>
<li class="myClass" id="rejected">Rejected</li>
<li class="myClass" id="already-done">Already Done</li>
<ul>
Step 1: Using CSS hide all the elements of your dropdown.
Example:
.myClass{
display: none;
}
Step 2: Now lets use JavaScript to show and hide elements based on Status variable value.
switch(Status) {
case "Pending":
document.getElementById("reviewed").style.display = "block;
break;
case "Accepted":
document.getElementById("accepted").style.display = "block;
break;
case "Rejected":
document.getElementById("rejected").style.display = "block;
break;
case "Already Done":
document.getElementById("already-Done").style.display = "block;
break;
}
After many trial and errors, I got it working
NWF$(document).ready(function() {
if (NWF$('#' + varStatus).val() == 'Pending' )
{
NWF$("#"+ varConcept).find("option[value='Pending']").remove();
NWF$("#"+ varConcept).find("option[value='Reviewed']").remove();
}
if (NWF$('#' + varStatus).val() == 'In Review' )
{
NWF$("#"+ varConcept).find("option[value='Pending']").remove();
NWF$("#"+ varConcept).find("option[value='Updated']").remove();
}
});
There is no other else if to say "anything outside the above, hide everything" but if you have the answer, feel free to add a comment.
Well, I know everyone is giving you code options, because you did ask about code, but honestly, since this is in SharePoint with a Nintex Form, you can do this entirely without code.
Create a List in SharePoint that contains two columns. One column for the test values (pending, in review, accepted) and a second column for the answers (updated, reviewed, duplicate, assigned).
On the form, add a List Lookup control. Use the Filter section to point it to your varStatus control.
I have a form with 2 dropdown-lists and 1 combobox.
Dropdown-list 1 has the 'groups', the second one contains the elements
The combobox contains a collection of data of combined groups and elements.
Example:
<select ng-model="currentCombo" ng-model="currentItem.group"
ng-options="item.label for item in data.subdata.groups"></select>
<select ng-model="currentCombo" ng-model="currentItem.Elements"
ng-options="item.label for item in data.subdata.elements"></select>
<button ng-click="updateCombination()">Update combination</button>
<select multiple ng-model="selectedItem"
ng-options="(item.group.label + ' : ' + item.elements.label) for item in data.combinations"></select>
Now, when I click the button, I add the new combination or, if it exists already, change the current one.
What I'm trying to achieve now is that, when you select an element in the combobox, it autoselects those 2 elements in the 2 separate dropdownlists.
Keep in mind that not all combinations exists: it is possible that a group has no elements yet.
In JS I run this code to add/update a combination:
$scope.updateCombination = function()
{
var isUpdate = false;
for (item in $scope.data['combinations'])
{
if ($scope.data['combinations'][item]['group']['id'] == $scope.currentCombo.group['id'])
{
$scope.data['combinations'][item]['element'] = $scope.currentCombo['element'];
isUpdate = true;
break;
}
}
if (!isUpdate)
$scope.data['combinations'].push($scope.currentCombo);
$scope.currentCombo = "";
}
I'm hoping you can please help.
I have the following HTML code:
<select id='bonus1frequency'>
<option value="0">Annual</option>
<option value="1">Half Yearly</option>
<option value="2">Quarterly</option>
</select>
Depending on what option is selected, fields are displayed in a divider. For example if you select annual, a field to enter annual bonus is displayed. If you select 'Half Yearly' two fields to enter two half yearly bonuses are displayed.
The trouble I'm having is that if you select 'Half yearly' for example, then enter what the half yearly bonus into the fields, then you change your mind and decide you want to enter an annual bonus instead, the values that you enter into the half yearly bonus are retained. I need them to be set to zero when you switch between options in the html select box.
I tried the following code to help with this but it's not working and i'm not sure why. All it does is prevent me from putting anything at all into the half year boxes.
var bonus_val_1 = document.getElementById("bonus1frequency");
var strUser = bonus_val_1.options[bonus_val_1.selectedIndex].value;
if (strUser = "0") //if annual bonus is selected
{
document.getElementById("halfyear_bonus_one").value = 0.00;
}
Edit:
I'm using the following JQUERY in the main HTML document to actually switch what fields are displayed when the user selects each option. So if the user selects option value 0 'annual' in the select box, the following code will show the annual bonus divider containing the annual bonus field, and hide the dividers that show half yearly and quarterly bonus fields.
Based on comments about how I need to tie resetting these fields to the change event, I just thought maybe I can reset the fields to zero within the following jquery code. However I'm even less familiar with JQUERy and not sure how to do that...any help would be much appreciated.
$('#bonus1frequency').on('change', function() {
if ( this.value == '0')
//.....................^.......
{
$("#annual").show();
$("#halfyearly").hide();
$("#quarterly").hide();
}
if ( this.value == '1')
//.....................^.......
{
$("#annual").hide();
$("#halfyearly").show();
$("#quarterly").hide();
}
EDIT 2
I have updated the code as follows:
$('#bonus1frequency').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#annual").show();
$("#halfyearly").hide();
$("#quarterly").hide();
$("#halfyear_bonus_one").val("0");
This prevents me from entering a value into the halfyear bonus one field. It just keeps resetting the value to zero. I've added an empty 'choose' option to the select box but it hasn't made a difference. Any ideas?
Please refer following for help and add code for quarterly. Use jquery instead of using javascript code to get elements.
<select id="bonus1frequency">
<option value="0">Annual</option>
<option value="1">Half Yearly</option>
<option value="2">Quarterly</option>
</select>
<div id="annual" style="display: none;">
<input type="text" id="a1">
</div>
<div id="half" style="display: block;">
<input type="text" class="b2">
<input type="text" class="b2">
<script>
$('#half').hide()//Same as this hide quarterly div
$("#bonus1frequency").change(function(){
var strUser = $(this).val()
if (strUser === "0") //if annual bonus is selected
{
$('#annual').show()
$('#half').hide()
$(".b2").val(0);
}else{
$('#half').show()
$('#annual').hide()
$('#a1').val(0)
}
})
</script>
</div>
The problem with your code is that you're not binding it to the select's change event. It will run when loading the page, and since the default option in the dropdown is "Annual", the value which will appear as the value of #halfyear_bonus_one would be 0.00 and won't change, even if the user will choose another option in the dropdown.
You should create a js function which contain your code (with few corrections)
and then bind it to a change event of the dropdown.
Moreover, you should add conditions to handle the other scenarios: "half yearly" and "quarterly".
var bonusval1 = document.getElementById("bonus1frequency");
bonusval1.onchange = function () {
var strUser = bonusval1.options[bonusval1.selectedIndex].value;
if (strUser == "0"){ //if annual bonus is selected
document.getElementById("halfyear_bonus_one").value = "0.00";
} else if(strUser == 1){ //Half yearly is selcted
document.getElementById("halfyear_bonus_one").value = "1.00";
} else { //quertly is selected
document.getElementById("halfyear_bonus_one").value = "2.00";
}
}
Now, there's another problem - the default value is the first value - but the "onchange" event won't trigger. We can run the function outside of the onchange event in order to handle the default value or you can add a blank option to the dropdown as the first option, something like "Choose:" or whatever.
Jsfiddle
Regarding the second question
I didn't understand why would you use jQuery all of a sudden when you already
wrote pretty good js code. Those kind of decisions should be considered in the beginning of the process.
Anyway, You can use the .val() function to change the value of the input fields. I don't have the code of your form and the dividers but it should be pretty much like the following:
if ( this.value == '0')
//.....................^.......
{
$("#annual").show();
$("#halfyearly").hide();
$("#quarterly").hide();
$("#id_of_input_for_halfyearly").val("0");
$("#id_of_input_for_quarterly").val("0");
}
I think this will help you out.
jQuery('#bonus1frequency').on('change',function(){
if(this.value==1){
jQuery('.yearly').val('').show();
jQuery('.half-yearly').val(0).hide();
jQuery('.quarterly').val(0).hide();
}else if(this.value==2){
jQuery('.yearly').val(0).hide();
jQuery('.half-yearly').val('').show();
jQuery('.quarterly').val(0).hide();
}else if(this.value==3){
jQuery('.yearly').val(0).hide();
jQuery('.half-yearly').val(0).hide();
jQuery('.quarterly').val('').show();
}
})
Check this Demo
i am using a multi select box in javascript as given here:
i want to get the list of selected items in the multi select text box (the left list)
what can i do to achieve that?
my select box is as follows:
<select id="userList" class="multiselect" multiple="multiple" name="users[]" style="width: 75px;">
//List
</select>
i guess users[] stores the selected users at a point in time. but i can't figure out how to retrieve that variable.
Doing this will work:
$('[name="user[]"]').val()
PS: You need to have jQuery included in your webpage.
from the demo at http://www.quasipartikel.at/multiselect/, doing $('[name="countries[]"]').val() will give sample output:
["ARM", "AUS", "AUT"]
Get a list of values with jQuery:
var values = $select.find('option:checked').map(function() {
return this.value || this.text;
});
// or $select.val() of course, like lemarc says
// => ['ABC', 'DEF']
var prefix = encodeURIComponent($select.attr('name')) + '=';
var httpQuery = values.length ? prefix + values.map(function() {
return encodeURIComponent(this);
}).join('&' + prefix);
// => users[]=ABC&users[]=DEF
I didn't test it.
This will return array of selected values
$('#userList').val();
DEMO
You can directly target $(".multiselect") Object, by doing this:
$("input[type='submit']").click(function(e){
e.preventDefault();
_selValue = $(".multiselect").val(); //You will have variable of selected values
for(var i=0;i<_selValue.length;i++){
alert(_selValue[i]);
//You can iterate it individually in loop
}
});