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>
Related
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()
I am trying to target a select2 element from the DOM and attach to its input field a keyup event. Because the element its hidden and created after the selection is pressed I cannot set any id or class name to the input. I made it work with event delegation using this code:
$('body').on('keyup', '.select2-search__field', function() {
//TODO: do some work here
});
This works fine, however it works for all the select2 elements I have on the page. I want to target a specific select2 element. I tried also to get the parent of the input so I can check which select2 element is currently used but it is not possible since select2 creates the elements directly at the body and not at the selection element. So all the select2 elements have parents with same classes and cannot be differentiated.
I am using the 4.0.4 version of the select2 and as I read so far the documentation there is no option to attach a custom event to the input.
You can use index() and .select2-container--open class to find the item.
$(document).ready(function(){
$('select').select2();
})
$('body').on('keyup', '.select2-search__field', function() {
var selectItem = $('.select2-container--open').prev();
var index = selectItem.index();
var id = selectItem.attr('id');
alert('index of the item =' + index +' and the id = '+ id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select id="first">
<option value="a">aaaaaaaaaaaaaaa</option>
<option value="b">bbbbbbbbbbbbbbb</option>
<option value="c">ccccccccccccccc</option>
</select>
<select id="second">
<option value="1">111111111111</option>
<option value="2">222222222222</option>
<option value="3">333333333333</option>
</select>
<select id="third">
<option value="q">qqqqqqqqqq</option>
<option value="w">wwwwwwwwww</option>
<option value="e">eeeeeeeeee</option>
</select>
You can find the select that is being clicked by $(".select2-container--open").prev(); and check if it has specific data-attribute you added to determine whether to do the stuff or not.
$(document).ready(function() {
$('.my-select').select2();
});
$('body').on('keyup', '.select2-search__field', function() {
let $select = $(".select2-container--open").prev();
if($select.data("show")) {
// TODO: do some work here
console.log(this.value)
}
});
select {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<div>
<select class="my-select">
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
</div>
<div>
<select class="my-select" data-show="true">
<option value="3">Option3</option>
<option value="4">Option4</option>
</select>
</div>
You could use :eq in the selector; https://api.jquery.com/eq-selector/
eq(1) because you want the second, index starts at 0
$('body').on('keyup', '.select2-search__field:eq(1)', function() {
//TODO: do some work here
});
Do run the snippet and change the value of the select fields;
$(document).on("change", ".select2-search__field:eq(1)", function() {
alert("Hello World!");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select2-search__field">
<option>A1</option>
<option>A2</option>
<option>A3</option>
</select>
<select class="select2-search__field">
<option>B1</option>
<option>B2</option>
<option>B3</option>
</select>
<select class="select2-search__field">
<option>C1</option>
<option>C2</option>
<option>C3</option>
</select>
I have several 'page' options in select element, each option has values derived from database.
<select name="page_id" title="page id" class="form-control" id="page">
#forelse($pages as $page)
<option data-slug="{{$page->slug}}" {{($page->id==$c_page->id) ? 'selected' : ''}} value="{{$page->id}}">{{$page->title}}</option>
#empty
<option value=""> No Pages Found</option>
#endforelse
</select>
I'm trying to get 'slug'value of 'clicked/chosen' option into javascript.
$(function () { /* DOM ready */
$("#page").change(function () {
alert($('option').data('slug'));
});
});
But this only returns the 'slug' value of 'page' option that is at the top. How can I get the value from other option elements?
You need to use :selected selector and use this the current element context (for which event handler is attached).
$("#page").change(function () {
var slug = $('option:selected', this).data('slug');
});
As a runnable snippet:
$(function() {
$(".page").change(function() {
var slug = $('option:selected', this).data('slug');
console.log('slug: ' + slug);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="page">
<option data-slug="first option">first
<option data-slug="second option">second
<option data-slug="third option">third
</select>
<select class="page">
<option data-slug="first option of second page">first
<option data-slug="second option of second page">second
<option data-slug="third option of second page">third
</select>
How can I convert this JavaScript into jQuery?
The purpose of this is to auto-select the value of a dropdown that matches.
JS code :
window.onload = function(){
document.getElementsByName("title")[0].value="the_title_value";
}
You can select the elements by their name attribute, then get the :first of them before setting the current val(), like this:
$(window).on('load', function() {
$('select[name="title"]:first').val('the_title_value')
});
$(document).ready(function(){
$('select[name="title"]').first().val("the_title_value");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="title">
<option value='the_title_value1'>1</option>
<option value='the_title_value'>2</option>
<option value='the_title_valu3'>3</option>
</select>
$(document).ready(function(){
$('[name="title"]').val("the_title_value");
})
you only need first() if you have many elements with name="title" on the page. The reason why you have to put [0] in vanila javascript is because
document.getElementsByName("title")
returns an array of elements, even if there is only one with this name.
window.onload = function() {
// document.getElementsByName("title")[0].value="the_title_value";
// get all items with name "title" and then reduce the result set to the first element and then set the value
$('[name="title"]').first().val("the_title_value");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="title">
<option value='the_title_value_1'>the_title_value_1</option>
<option value='the_title_value'>the_title_value</option>
<option value='the_title_value_3'>the_title_value_3</option>
</select>
You could use :eq and name selector inside ready function to achieve that , check the example bellow.
Hope this helps.
$(function(){
$("select[name='title']:eq(0)").val('second');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="title">
<option value='first'>First 1</option>
<option value='second'>Second 2</option>
<option value='third'>Third 3</option>
</select>
I am using counties.js form here and using select-2 plugin for drop down.
code for selecting country from the country drop down
<select class="select2 dep" name="country" id="country_list">
<optgroup label="Country">
<option value="">Select Country</option>
<script src="<?=base_url()?>assets/js/countries_states.js"></script>
<script language="javascript">
populateCountries("country_list");
var country_select = document.getElementsByName('country');
for(var m=0;m<country_select[0].options.length;m++)
{
if(country_select[0].options[m].value == '<?=$bhandar_details[0]['country']?>')
{
country_select[0].options[m].setAttribute("selected","true");
}
}
</script>
</optgroup>
</select>
and the code for default selection of states is as follows
<select class="select2 dep" name="state" id="state_list">
<optgroup label="State">
<option value="">Select State</option>
<script language="javascript">
populateStates("country_list", "state_list");
var state_select = document.getElementsByName('state');
for(var m=0;m<state_select[0].options.length;m++)
{
if(state_select[0].options[m].value == '<?=$bhandar_details[0]['state']?>')
{
state_select[0].options[m].setAttribute("selected","true");
}
}
</script>
</optgroup>
when the country is changed its respective states should change for that following script is written
<script type="text/javascript">
$( "#country_list" ).change(function() {
populateStates("country_list", "state_list");
});
</script>
everything works well and fine and when country is changed its respective states are populated in the state drop down. but the display text in state dropdown remains the same even though that state doesnot exists, until not changed manually to some other text.
Ideally as soon as country is changed the state list should change to default selection.
thank you all in advance. waiting for response...
I think what you do to the main select (behind the graphical select2) does not affect the select2 user interface.
In fact, you have to change the value of your select using the plugin itself.
Use this:
$("#state_list").select2().val(0); // any value you like
Working code:
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/select2.min.js"></script>
<script src="js/countries_states.js"></script>
<link href="css/select2.css" rel="stylesheet"/>
<select class="select2 dep" name="country" id="country_list" style="width: 260px;">
<optgroup label="Country">
<option value="">Select Country</option>
</optgroup>
</select>
<select class="select2 dep" name="state" id="state_list">
<optgroup label="State">
<option value="">Select State</option>
</optgroup>
<script type="text/javascript">
$( "#country_list" ).change(function() {
populateStates("country_list", "state_list");
$("#state_list").select2().val(0); //----- added this code
});
$(document).ready(function() {
populateCountries("country_list", "state_list");
$("#country_list").select2();
$("#state_list").select2();
});
</script>
Try this this can help you by just doing a small effort
https://rubygems.org/gems/country_state_select