display option value in div on change - javascript

how to display selected value of option in an empty div with jquery?
$(document).ready(function() {
let from_select = $('#from_select');
let from_text = $('#from');
//example#1
from_select.on('change', function() {
from_text.append($("option:selected").val());
})
//example#2
from_select.on('change', function() {
from_text.append($("#test option:selected").val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="from_select">
<option id="test" value="gel" selected data-buy="1" data-sell="1">GEL</option>
<option id="test" value="usd" data-buy="" data-sell="">USD</option>
<option id="test" value="eur" data-buy="" data-sell="">EUR</option>
<option id="test" value="rub" data-buy="" data-sell="">RUB</option>
</select>
<div id="from"></div>
in example#1 it works, but then i cant remove last value which was passed in #from div.
but in example#2 it doesn't work, i dont know why but it's not gettind id #test.

Example#1
You could read the selected value from $(this).val().
you should use .html instead of .append.it will replace the previously added value from the form
Example#2
And second one not working because id of #tornike element not there in your markup. And this not necessary. because already you are in onchange event so you will get the value from the event . So id target was unnecessary
$(document).ready(function() {
let from_select = $('#from_select');
let from_text = $('#from');
//example#1
from_select.on('change', function() {
from_text.html($(this).val());
})
//not necessary
//example#2
// from_select.on('change', function() {
// from_text.append($("#tornike option:selected").val());
//})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="from_select">
<option id="test" value="gel" selected data-buy="1" data-sell="1">GEL</option>
<option id="test" value="usd" data-buy="" data-sell="">USD</option>
<option id="test" value="eur" data-buy="" data-sell="">EUR</option>
<option id="test" value="rub" data-buy="" data-sell="">RUB</option>
</select>
<div id="from">
</div>

You can use any of the below option
$(this).val()
from_select.val()

Related

JQuery select options on change not displaying value

When I select an option in my website, it should alert the option's value, but in this situation, the value is not alerted.
However when I tried it in JSFiddle, it works.
I am using jQuery 3.4.1 with jQuery loading at head tag.
My javascript script file is located at the bottom of body tag
HTML code
<div class = 'custom-select'>
<select id = 'choice'>
<option value = ''></option>
<option value = 'one' selected>One</option>
<option value = 'two'>Two</option>
</select>
</div>
Javascript code
$(function() {
$('#choice').change(function() {
alert($('#choice option:selected').text());
});
});
Please advise me on what I am missing or doing wrong, thank you.
Please check if you have Jquery included in the html. I added it and it worked.
Try adding
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Your code works.
1. Check your console for any errors.
2. Check if it is the first script that is included.
3. Check if javascript is enabled in your browser.
Option 1 with jquery:
$(function() {
$('#choice').change(function() {
alert($('#choice option:selected').text());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = 'custom-select'>
<select id = 'choice'>
<option value = ''></option>
<option value = 'one' selected>One</option>
<option value = 'two'>Two</option>
</select>
</div>
Option 2 without jquery:
function alert_dropdown(value){
alert(value);
}
<div class = 'custom-select'>
<select id = 'choice' onchange="alert_dropdown(this.value)">
<option value = ''></option>
<option value = 'one' selected>One</option>
<option value = 'two'>Two</option>
</select>
</div>
In case your content is being added dynamically you could try the following. In addition use val() to get the select box option.
$(document).on('change', '#choice', (e) => {
alert($(e.target).val());
});
If your content is not being added dynamically then simply use:
$('#choice').on('change', (e) => {
alert($(e.target).val());
});
$(document).on('change', '#choice', (e) => {
alert($(e.target).val());
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class='custom-select'>
<select id='choice'>
<option value=''></option>
<option value='one'>One</option>
<option value='two'>Two</option>
</select>
</div>
alert($("#choice > option:selected").val());
$("#choice").on("change", (e) => {
alert(($(e.target).val().length ? $(e.target).val() : "Select Something!"));
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class='custom-select'>
<select id='choice'>
<option value=''></option>
<option value='one' selected>One</option>
<option value='two'>Two</option>
</select>
</div>

How to trigger an Event using an ID in a Select list

I have a select list that triggers DIV tag visibility, which works great, but once I added a new select list it started conflicting with the first list. I need to be able to use the first list to trigger the toggle event independently of any other lists in the code.
I'm to use the select list using a specific ID to properly toggle the DIV visibility but I can't seem to get it right.
$(document).ready(function () {
$("select").change(function () {
$(this).find("option:selected").each(function () {
var optionValue = $(this).attr("value");
if (optionValue) {
$(".divToggle").not("." + optionValue).hide();
$("." + optionValue).show();
} else {
$(".divToggle").hide();
}
});
}).change();
});
This is the select options:
<select id="transferOptions" class="form-control" name="transferoptions" aria-label="Transfer Options" tabindex="">
<option value="fundTransferOption" selected>Select an Option</option>
<option value="achTransfer">ACH Transfer</option>
<option value="flashFundsTransfer">Flash Transfer</option>
</select>
<select id="ConflictingSelectOptionsAlsoCausingDIVToggling">
<option>Choose</option>
<option>Blah</option>
<option>Blah 2</option>
</select>
<div class="achTransfer divToggle">On select show Thing 1</div>
<div class="flashFundsTransfer divToggle">On select show Thing 2</div>
I want to use the Javascript above to specifically work the select list that use the "id="transferOptions", so as I add other select lists to the code it won't conflict with the transferOptionselect list, thus triggering the DIV's in the page.
Use the select ID with its CSS selector #transferOptions. Also changed some logic for you to check out:
$(document).ready(function() {
$("#transferOptions").change(function() {
var optionValue = $(this).val(); // or use javascript: this.value
$(".divToggle").hide(); // hide all .divToggle elements
if (optionValue) { // in your example this is always true
$("." + optionValue).show(); // show the matching element
}
}).change(); // trigger change after document is ready
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="transferOptions" class="form-control" name="transferoptions" aria-label="Transfer Options" tabindex="">
<option value="fundTransferOption" selected>Select an Option</option>
<option value="achTransfer">ACH Transfer</option>
<option value="flashFundsTransfer">Flash Transfer</option>
</select>
<select id="ConflictingSelectOptionsAlsoCausingDIVToggling">
<option>Choose</option>
<option>Blah</option>
<option>Blah 2</option>
</select>
<div class="achTransfer divToggle">On select show Thing 1</div>
<div class="flashFundsTransfer divToggle">On select show Thing 2</div>
You can get the element that event is referring to using event.target instead of using this which in your case refers to the callback function, see example below:
$('select').change(event => {
console.log(event.target.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select1">
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
<select id="select2">
<option>quux</option>
<option>xyzzy</option>
</select>

Get div html with select value of dynamically created select in jquery

I dynamically created a div with select options in jQuery. Here's a sample.
<div id="myDiv">
<select id="mySelect">
<option selected value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
</select>
</div>
0 is the default selected value.
When I get html of the div like this $("#myDiv").html(), it gets the below.
<div id="myDiv">
<select id="mySelect">
<option selected value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
</select>
</div>
It's the same as the above code which is normal.
However, when I change the selected value to 2, $("#myDiv").html() is still getting same code. 0 is still the selected value.
How can I get the html of the div, with the dynamically changed value?
You can do this :
$('#yourSelect option:selected').val()
Maybe like this:
function create_select(){
var select=$('<select/>').attr('id','mySelect');
var option0=$('<option/>').val(0).text('A').attr('selected', true);
select.append(option0);
var option1=$('<option/>').val(1).text('B');
select.append(option1);
var option2=$('<option/>').val(2).text('C');
select.append(option2);
var option3=$('<option/>').val(3).text('D');
select.append(option3);
$('#myDiv').empty().append(select);
}
function change_select_value(_new_val){
$('#mySelect option').removeAttr('selected');
$('#mySelect').val(_new_val).change();
}
$(document).on('change', '#mySelect', function(){ //conctruction for Dynamically created element
alert('change value to =>'+this.value); //or $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="myDiv"></div>
<input type="button" value="Create Select" onclick="create_select();" /></br>
<input type="button" value="Set option C (value=2)" onclick="change_select_value(2);" /></br>
$('#myDiv').find("#mySelect").change(function () {
alert($("#mySelect option:selected").text());
alert($("#mySelect option:selected").val());
});

Get the name of all selected items from select multiple="multiple" options dropdown

I am trying to get the name of all selected items from select multiple="multiple" options dropdown.
In my html page, I have the following code snippet:
<select id="ddlCategory" ng-model="myCategory.myCategoryName" multiple>
<option selected="selected" value="1">Washroom</option>
<option value="2">Restaurant</option>
</select>
In my JS file, I have the following code snippet:
var categoryNameArray = $('#ddlCategory').val();
console.log("category = " + categoryNameArray[0];
However, the variable categoryNameArray only gives me the array of the selected items, what I want is the name of the selected items. Can someone tell me a way how I can make this work? Thanks!
Since val isn't giving you what you want, I'm going to assume you want an array of the text of the selected items.
You can get that like this:
var selectedTextArray = $("#ddlCategory option:selected").map(function() {
return $(this).text();
}).get();
That finds all the selected items, then uses map to get the text of each of them (wrapped in a jQuery object), then uses get to turn that jQuery object into an array.
You can probably use return this.text; rather than return $(this).text();, since HTMLOptionElement has a text property (which most elements don't), but I'd be sure to test with my target browsers to be sure.
Example:
$("#btn").on("click", function() {
var selectedTextArray = $("#ddlCategory option:selected").map(function() {
return $(this).text();
}).get();
console.log(selectedTextArray);
});
Select some items, then click
<input type="button" id="btn" value="here">
<br>
<select id="ddlCategory" ng-model="myCategory.myCategoryName" multiple>
<option value="1">Washroom</option>
<option value="2">Restaurant</option>
<option value="3">Service Station</option>
<option value="4">Drive-Thru</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Example with this.text instead of $(this).text():
$("#btn").on("click", function() {
var selectedTextArray = $("#ddlCategory option:selected").map(function() {
return this.text;
}).get();
console.log(selectedTextArray);
});
Select some items, then click
<input type="button" id="btn" value="here">
<br>
<select id="ddlCategory" ng-model="myCategory.myCategoryName" multiple>
<option value="1">Washroom</option>
<option value="2">Restaurant</option>
<option value="3">Service Station</option>
<option value="4">Drive-Thru</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
val() returns the values on the selected options, in your case 1, 2 .... You should use text() to get the names of the selected options. You can loop through all selected options using each() method and get the selected values using text():
$('a').on('click', function(e) {
e.preventDefault();
$('#ddlCategory option:selected').each(function(i, selected) {
console.log($(selected).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlCategory" ng-model="myCategory.myCategoryName" multiple>
<option selected="selected" value="1">Washroom</option>
<option value="2">Restaurant</option>
</select>
Send
You can read more on how val() works here.
You can read more on how text() works here.
Try this:
var categoryNameArray =
$('#ddlCategory option:selected').map(function(){
return this.text;
}).get();
console.log("category = " + categoryNameArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlCategory" ng-model="myCategory.myCategoryName" multiple>
<option selected="selected" value="1">Washroom</option>
<option selected="selected" value="2">Restaurant</option>
<option value="3">Coffee Shop</option>
<option value="4">Hotels</option>
</select>
Easy way to get all selected value is $('#ddlCategory').val();

How to change a border color of html select tag if value is empty or 0

I have 4 select tag with class name select2 assigned to it. I want to make the border turn to red if there's no selected options or has an value equal to empty or 0. I've tried to add class using jquery but it makes all select.select2 border turns red.
Style
<style>
.errorType {
border-color: #F00 !important;
}
</style>
HTML
<select name="category" class="form-control select2" id="category" onChange="search_Operator(this.value)">
<option value="0"> Select Operator Category</option>
<option value="1">one</option> <option value="2"> two</option>
</select>
<select name="operatorName" class="form-control select2" id="operatorName" onChange="">
<option value="0"> Select operator Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="regionName" class="form-control select2" id="regionName">
<option value="0"> Select region Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="type" class="form-control select2" id="type">
<option value="0"> Select type </option>
</select>
JQUERY
$(function () {
$(".select2").select2();
});
$(".select2-selection").addClass('errorType');
Any idea?
Thanks in advance.
I've attached a function to the click event of the submit button, in order to check the value of every select element on the page:
$(function () {
$('.form-control-select2').select2();
$('#submit_btn').on('click', function(){
var submit_form = true;
$(".form-control-select2").each(function(){
var selected_value = $(this).val();
if (selected_value==0 || selected_value=='') {
$(this).next().find('.select2-selection').addClass('errorType');
submit_form = false;
} else {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
return submit_form;
});
});
Fiddle here: https://jsfiddle.net/64a41thz/21/.
Also, if you want to remove the red border when valid selection is made, add the following code:
$('.form-control-select2').on('change', function(){
if ($(this).val()!=0 && $(this).val()!='') {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
Fiddle here: https://jsfiddle.net/64a41thz/24/.
This does the trick. You just need to replace #yourButton with the actual ID you use.
$(document).on("click", "#yourButton", function() {
$(".select2").each(function(index, element) {
$(element).removeClass("errorType");
if ($(element).val() === "0") {
$(element).addClass("errorType");
}
});
});
Put your select tag inside a form with an id="submit" as shown
<form class="" action="" method="post" id="submit">
and add a button below the 4 select tags with this attribute
onclick="return submit_form('form#submit')"
the button should be like this,
<button type="button" class="btn btn-default" onclick="return submit_form('form#submit')">Submit</button>
In your jquery
function submit_form (form_id) {
$(form_id).find('select[name]').each(function (index, node) {
if (node.value == 0) {
var id = "select#" + node.id;
$(id).addClass('errorType');
}
});
}
This will search select tag with name as attribute, if found, it will get the value of the name and check of its empty or not. If found empty it will add new class that turns that select tag into a red border.
Hope this will help

Categories