How to receive in JS selections from html using select2 - javascript

I want to receive in JS the selected values from html. In html I'm using multi-select box with selected2 library. I was able to do it for a normal single choice such as <select class="form-control" id="companies" >.
Could anybody tell me how to do it for a multiple selects with select2?
html
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<form>
<div class="form-group">
<label>Airline companies</label>
<p>
<select class="js-example-basic-multiple" id="companies" name="states[]" multiple="multiple" style="width: 120%">
<!-- select class="form-control" id="companies" --> // if I don't use multiple select with select2, it worked
<option selected>Select companies</option>
<option value="one">First</option>
<option value="two">Second</option>
...
</select>
</p>
</div>
<button class="btn btn-primary" type='button' id="button">Refresh</button>
</form>
JS
company = getSelectedOption('companies')
function getSelectedOption(id){
/* function to get the selected value from the dropdowns */
let select = document.getElementById(id);
let value = select.options[select.selectedIndex].value;
return value
}

You can get selected value by using jQuery method .val():
var company = getSelectedOption('companies');
function getSelectedOption(id){
return $('#' + id).val();
}

Related

How to add action in HTML depending on two option combination?

How to add condition like this:
If customer chose Japan as a pickup option and England as a dropoff option, page sends him on page with prices of that destination and for some other input there is exactly one output for exact chosen destination and pickup place.
<div class="advanced-search color" id="booking">
<div class="wrap">
<form role="form" action="index.html" method="get">
<!-- Row -->
<div class="f-row">
<div class="form-group select one-third">
<label>Pick up location</label>
<select id="pickup1" name="p1">
<option value="">Select pickup location</option>
<optgroup label="Asia">
<option value="1">China</option>
<option value="2">Japan</option</optgroup>
</select>
</div>
<div class="form-group select one-third">
<label>Drop off location</label>
<select id="dropoff1" name="d1">
<option value="">Select drop-off location</option>
<optgroup label="Europe">
<option value="3">England</option>
<option value="4">Spain</option</optgroup>
</select>
</div>
<div class="form-group right">
<center>
<label>Check for informations</label>
</center>
<button type="submit" class="btn large black">Find a transfer</button>
</div>
</div>
<!-- //Row -->
</form>
</div>
</div>
You can use jquery for this,
$(#dropOffSelect).on('change',function(){
var dropOffval = $(this).val();
var pickUplocation = $('#pickUpselect').val();
//condition runs here
if(pickUplocation ==='Japan' && dropOffval === 'Europe'){
// show the information for it
}
})
This is simple using jQuery. You send the values to the pricelist page via querystring in your url. On load of the pricelist page you get the values from the query string and filter based on it.
Now you'll have to work with the values in the list and not the text. You can match the values from a database or you can still use the country name as the value.
$(function() {
$('#btnSubmit').click(function() {
$('form').attr('action', 'pricelist?pickup=' + p1.val() + '&dropoff=' + d1.val());
$('form').submit();
});
you can use window.location within your script no need to use action just add onclick="Myfunc()" event.
if(pickup == "japan" && dropoff == "england")
window.location = "url";

Adding multiple select options with jquery

I've created functionality to move items from the left -> right, and vice versa. On top of that, I am added the option values of each item into a hidden input box, so I can later submit it to the server for processing. It seems that when I try to add more than one item at a time, only the first one is being added to the hidden input box though.
In the end, my hidden input field should look like: 3233,2332,3234,1212,112
Since I'll accept the parameters in the Ruby on Rails server side to parse and do whatever to (unless there's a better option).
Here's my current code:
$("#btnLeft").click(function(){
var selectedItem = $("#hosts_assigned option:selected");
$("#hosts_available").append(selectedItem);
$("#hosts").remove(selectedItem.val());
});
$("#btnRight").click(function(){
var selectedItem = $("#hosts_available option:selected");
$("#hosts_assigned").append(selectedItem);
var current_hosts = $("#hosts").val();
$("#hosts").val(current_hosts + "," + selectedItem.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="hosts_available"size="30" multiple="multiple">
<option value="1222">1.1.2.2</option>
<option value="1232">1.1.2.2</option>
<option value="1242">1.1.2.2</option>
<option value="1252">1.1.2.2</option>
</select>
<select id="hosts_assigned" size="30" multiple="multiple">
<option value="1111">1.1.2.1</option>
</select>
</form>
<button type="button" id="btnRight">>></i></button>
<br/>
<button type="button" id="btnLeft"><<</i></button>
<br/><br/>
<input type="text" id="hosts" />
You are getting more than one.
You need to loop. you also need to loop after removing
function getHosts() {
var current_hosts=[];
$("#hosts_assigned option").each(function() {
current_hosts.push($(this).val());
});
return current_hosts.length>0?current_hosts.join(","):"";
}
$("#btnLeft").click(function() {
$("#hosts_assigned option:selected").each(function() {
$("#hosts_available").append(this);
})
$("#hosts").val(getHosts());
});
$("#btnRight").click(function() {
$("#hosts_available option:selected").each(function() {
$("#hosts_assigned").append(this);
});
$("#hosts").val(getHosts());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="hosts_available" size="30" multiple="multiple">
<option value="1222">1.1.2.2</option>
<option value="1232">1.1.2.2</option>
<option value="1242">1.1.2.2</option>
<option value="1252">1.1.2.2</option>
</select>
<select id="hosts_assigned" size="30" multiple="multiple">
<option value="1111">1.1.2.1</option>
</select>
</form>
<button type="button" id="btnRight">>></i>
</button>
<br/>
<button type="button" id="btnLeft"><<</i>
</button>
<br/>
<br/>
<input type="text" id="hosts" value="" />

Bootstrap Select Menu - Add New Option

I have a simple Bootstrap form with a select input:
<div class="form-group">
<label for="category" class="control-label col-sm-3">Category</label>
<div class="input-group col-xs-8">
<select class="form-control" name="category" id="category">
<option value="Fruit">Fruit</option>
<option value="Vegetables">Vegetables</option>
</select>
</div>
</div>
The users now have a requirement to be able to add a new option dynamically to the select menu rather than be restricted to the items on the select menu.
I'm not sure if it's possible to modify a select menu and how to make it consistent with the rest of the Bootstrap framework?
To add an option dynamically, there should be a UI button giving you that choice. To get user input, we can use the window.prompt method.
We then create an option element, set its value attribute and set its name. Then just append these elements and nodes to the DOM with appendChild
Try playing around with this. I added some items like Steak, potatoes and beer.
var addOption = document.getElementById("add-option");
var selectField = document.getElementById("category");
addOption.addEventListener("click", function() {
var item = prompt("What would you like");
var option = document.createElement("option");
option.setAttribute("value", item);
var optionName = document.createTextNode(item);
option.appendChild(optionName);
selectField.appendChild(option);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group">
<label for="category" class="control-label col-sm-3">Category</label>
<div class="input-group col-xs-8">
<select class="form-control" name="category" id="category">
<option value="Fruit">Fruit</option>
<option value="Vegetables">Vegetables</option>
</select>
</div>
</div>
<button id="add-option" class="btn btn-primary">Add a new option</button>
You mean something like this?
some select
<select id="region" class="selectpicker">
<option>region 1</option>
<option>region 2</option>
<option>region 3</option>
</select>
jquery js
$('.selectpicker').selectpicker();
$("#region").on('change', function () {
$(this)
.append('<option>region4</option><option>region5</option>')
.selectpicker('refresh');
});

only one value is equal to and selected in multiple select

I have the exact same question as this:
jQuery Hide / Show input when selected option is equal to
However, it doesn't work when you go to multiple select, when the specific option is selected it works, but when you select another option alongside it stops working.
The question again is this: I want to show a div(#showme) if option 4 was selected, and I want to to work even if option 3 & 4 were selected, so at any given time if option 4 was selected the div should show.
This is the Javascript & HTML I have so far: (please note that I have more than one select in this form)
$('select[multiple]').each(function() {
$(this).change(function() {
obj = '#' + $(this).attr('id') + '_desc';
if($(this).val() == "4") {
$(obj).parent().parent().parent().removeClass('hide');
$(obj).css('display','block');
}
else {
$(obj).parent().parent().parent().addClass('hide');
$(obj).css('display','none');
}
});
});
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1">Hello?</label>
<select class="form-control selectpicker show-tick" name="feedback_q1[]" id="feedback_q1" multiple="multiple" title="Choose...">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
</div>
<div class="row hide">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1_desc">desc <span class="glyphicon glyphicon-pencil"></span></label>
<textarea name="feedback_q1_desc" id="feedback_q1_desc" class="form-control" data-toggle="tooltip" data-placement="top" title="desc" rows="2"></textarea>
</div>
</div>
</div>
Thanks for the help
When multiple selections are made, $(this).val() will contain an array of the values. Iterate through them and check for '4'. If $(this).val() is null, then nothing has been selected.
The example below does exactly what you want, including the changes after our extensive exchange in the comments and chat, including your most recent request to handle values pre-selected when the document loads.
Additionally, you were missing the bootstrap JavaScript file, and the files you were already including were in the wrong order and wrong location. The example below includes all of the .js and .css files in the correct order and location.
HTML
<!-- These should be in head -->
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" rel="stylesheet" />
<!-- Body content -->
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1">Hello?</label>
<select class="form-control selectpicker show-tick" name="feedback_q1[]" id="feedback_q1" multiple="multiple" title="Choose...">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
</select>
</div>
</div>
</div>
<div class="row hide">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1_desc">desc <span class="glyphicon glyphicon-pencil"></span>
</label>
<textarea name="feedback_q1_desc" id="feedback_q1_desc" class="form-control" data-toggle="tooltip" data-placement="top" title="אנא פרט" rows="2"></textarea>
</div>
</div>
</div>
<!-- These should be at the end of <body> -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
JavaScript
// Check a select for a specific value and show/hide div based on selection
// Select will come in as a jQuery object
function checkSelect(control) {
// Build selector for associated description field
var selector = '#' + control.attr('id') + '_desc';
// Handle scenario where nothing is selected
if (control.val() == null) {
$(selector).parent().parent().parent().addClass('hide');
$(selector).css('display', 'none');
return;
}
// Get array containing selected values
var vals = control.val();
// Handle scenario where something is selected
for (i = 0; i < vals.length; i++) {
if (control.val()[i] == "4") {
$(selector).parent().parent().parent().removeClass('hide');
$(selector).css('display', 'block');
return; // Stop checking as we know the value we want is selected
} else {
$(selector).parent().parent().parent().addClass('hide');
$(selector).css('display', 'none');
}
}
}
// This runs when the DOM is ready
$(function () {
// Bind selectpicker
$('.selectpicker').selectpicker();
// Iterate through all multiple selects
$('select[multiple]').each(function () {
// Check for pre-selected values when page first loads
checkSelect($(this));
// Bind to change event so that values are checked after something is changed
$(this).change(function () {
checkSelect($(this));
});
});
});
Demo (third version): http://jsfiddle.net/BenjaminRay/7ckp7epf/
<div class="form-group">
<select class="form-control selectpicker show-tick" name="Status" id="Status" multiple="multiple" title="Choose...">
#foreach (SelectListItem item in ViewBag.Status)
{
if (item.Selected == false)
{
<option value="#item.Value">#item.Text</option>
}
else
{
<option value="#item.Value" selected>#item.Text</option>
}
}
</select>
</div>

How to show form input fields based on select value?

I know this is simple, and I need to search in Google. I tried my best and I could not find a better solution. I have a form field, which takes some input and a select field, which has some values. It also has "Other" value.
What I want is:
If the user selects the 'Other' option, a text field to specify that 'Other' should be displayed. When a user selects another option (than 'Other') I want to hide it again. How can I perform that using JQuery?
This is my JSP code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="otherType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
Now I want to show the DIV tag**(id="otherType")** only when the user selects Other.
I want to try JQuery. This is the code I tried
<script type="text/javascript"
src="jquery-ui-1.10.0/tests/jquery-1.9.0.js"></script>
<script src="jquery-ui-1.10.0/ui/jquery-ui.js"></script>
<script>
$('#dbType').change(function(){
selection = $('this').value();
switch(selection)
{
case 'other':
$('#otherType').show();
break;
case 'default':
$('#otherType').hide();
break;
}
});
</script>
But I am not able to get this. What should I do? Thanks
You have a few issues with your code:
you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">
should be <select name="dbType" id="dbType">
$('this') should be $(this): there is no need for the quotes inside the paranthesis.
use .val() instead of .value() when you want to retrieve the value of an option
when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function
try this:
$('#dbType').on('change',function(){
if( $(this).val()==="other"){
$("#otherType").show()
}
else{
$("#otherType").hide()
}
});
http://jsfiddle.net/ks6cv/
UPDATE for use with switch:
$('#dbType').on('change',function(){
var selection = $(this).val();
switch(selection){
case "other":
$("#otherType").show()
break;
default:
$("#otherType").hide()
}
});
UPDATE with links for jQuery and jQuery-UI:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
Demo on JSFiddle
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
You have to use val() instead of value() and you have missed starting quote id=dbType" should be id="dbType"
Live Demo
Change
selection = $('this').value();
To
selection = $(this).val();
or
selection = this.value;
I got its answer. Here is my code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="other" class="selectDBType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
And my script is
$(function() {
$('#dbType').change(function() {
$('.selectDBType').slideUp("slow");
$('#' + $(this).val()).slideDown("slow");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="1">first</option>
<option name="2"value="2">second</option>
</select>
</body>
</html>
$('#dbType').change(function(){
var selection = $(this).val();
if(selection == 'other')
{
$('#otherType').show();
}
else
{
$('#otherType').hide();
}
});

Categories

Resources