I want to invoke javascript function when value in the dropdown list changes. I dont want to hardcode dropdown list id .
Hence not using document.getElementById
My Code:
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
function jsFunction(value)
{
alert(value);
}
This is giving error ReferenceError: jsFunction is not defined
Fiddle : http://jsfiddle.net/6uyz4b8x/1/
Your code is working just fine, you have to declare javscript method before DOM ready.
I don't know why do you need this onmousedown event here, but what you have to do is put your function above actual usage. Look at the snipplet below:
<script type="text/javascript">
function jsFunction(value)
{
alert(value);
}
</script>
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
using jQuery
$("#ddl").change(function () {
alert($(this).val());
});
jsFiddle
You just try this, Its so easy
<script>
$("#YourDropDownId").change(function () {
alert($("#YourDropDownId").val());
});
</script>
jsFunction is not in good closure. change to:
jsFunction = function(value)
{
alert(value);
}
and don't use global variables and functions, change it into module
Related
I have a jQuery Code, see below please.
$(document).ready(function () {
$('select').on('change', function () {
var test = this.value;
console.log(test);
})
});
which is working perfectly.
Now what I would like to do is, I want to save this code as a function so I can use it somewhere else. Can you help me please?
update
as you can see on the photo, there is a dropdownlist.
src="https://maps.googleapis.com/maps/api/js?
key=MYAPIKEY&
callback=initAutocomplete
&language=fr"
what I want to update is, whenever I choose the language from the dropdownlist the src attribute should get updated. In the src attribute you can see the value and in that value the last parameter is language.
I want to update the language parameter according to the dropdownlist.
Create a function like this:
function onChange() {
var test = this.value;
console.log(test);
});
Then, use that function as the change event handler:
$(document).ready(function () {
$('select').on('change', onChange);
});
Now you can reuse this function for any event handler.
There's multiple answer to store what you've done.
You can just store your action into a function, or you can create and attach the result action function into one function.
$(".my-select").on("change",function(){
actionAfterChange($(this).val())
});
//Just action
function actionAfterChange(value){
console.log("function actionAfterChange > ",value)
}
//Create event listener and attach a function
function attachEventAndAction(element,event,action){
$(element).on(event,function(){
action($(this).val())
});
}
attachEventAndAction(".my-select2","change",actionAfterChange)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="my-select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select class="my-select2">
<option value="1">1</option>
<option value="2">2</option>
</select>
I have an select option menu which I want to use for multiple functions, but instead of wrapping this code around each function I thought way an I not making a variable outside of it so I can use that. Now I am trying to that with returning the variable and calling that function but it only works the first one and isn't being triggered when I select an other option.
what is the best way to achieve this?
<select id="level_select" onchange="LevelName()">
<option select disabled>Select Level</option>
<option value="2d" id="high_water_pass_1">Highwater Pass 1</option>
<option value="2e" id="high_water_pass_2">Highwater Pass 2</option>
</select>
var name = LevelName();
function LevelName() {
level = $('#level_select').find(":selected").attr("id");
return level;
}
console.log(name);
Here's a working fiddle: https://jsfiddle.net/gdb2xod8/2/.
I really didn't change anything except for the location of the script itself, Click the javascript gear, and you'll notice I've put it in the head
You need to put your script before your html, the head is a good location:
<html>
<head>
<script>
//script here, or better, reference your script in the src attribute
var name = LevelName();
function LevelName() {
level = $('#level_select').find(":selected").attr("id");
console.log(level)
return level;
}
console.log(name);
</script>
</head>
<body>
<select id="level_select" onchange="LevelName()">
<option selected disabled>Select Level</option>
<option value="2d" id="high_water_pass_1">Highwater Pass 1</option>
<option value="2e" id="high_water_pass_2">Highwater Pass 2</option>
</select>
</body>
</html>
Also, I changed your "select" attribute to "selected". Should give you the behavior you're expecting.
You should call console.log inside your function:
function LevelName() {
level = $('#level_select').find(":selected").attr("id");
console.log(level);
return level;
}
Your console.log is triggered once actually.
I'm a little bit confused about how to get an index of a selected option from a HTML <select> item.
On this page there are two methods described. However, both are always returning -1. Here is my jQuery code:
$(document).ready(function(){
$("#dropDownMenuKategorie").change(function(){
alert($("#dropDownMenuKategorie option:selected").index());
alert($("select[name='dropDownMenuKategorie'] option:selected").index());
});
});
and in html
(...)
<select id="dropDownMenuKategorie">
<option value="gastronomie">Gastronomie</option>
<option value="finanzen">Finanzen</option>
<option value="lebensmittel">Lebensmittel</option>
<option value="gewerbe">Gewerbe</option>
<option value="shopping">Shopping</option>
<option value="bildung">Bildung</option>
</select>
(...)
Why this behavior? Is there any chance that the select is not "ready" at the moment of assigning its change() method? Additionally, changing .index() to .val() is returning the right value, so that's what confuses me even more.
The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.
Just use the selectedIndex property of the DOM element:
alert($("#dropDownMenuKategorie")[0].selectedIndex);
Update:
Since version 1.6 jQuery has the prop method that can be used to read properties:
alert($("#dropDownMenuKategorie").prop('selectedIndex'));
Good way to solve this in Jquery manner
$("#dropDownMenuKategorie option:selected").index()
You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.
var savedIndex = $(selectElement).prop('selectedIndex');
This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:
$(selectElement).prop('selectedIndex', savedIndex);
I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.
var vOptionSelect = "#productcodeSelect1";
The index is returned with:
$(vOptionSelect).find(":selected").index();
try this
alert(document.getElementById("dropDownMenuKategorie").selectedIndex);
selectedIndex is a JavaScript Select Property. For jQuery you can use this code:
jQuery(document).ready(function($) {
$("#dropDownMenuKategorie").change(function() {
// I personally prefer using console.log(), but if you want you can still go with the alert().
console.log($(this).children('option:selected').index());
});
});
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
Actually just reiterating what has already been stated a little differently:
$("#dropDownMenuKategorie").change(function() {
var Selection = $("#dropDownMenuKategorie option:selected");
alert(Selection.index());
alert(Selection.val());
});
Assume You have jquery loaded. So
HTML :
<select id="dropDownMenuKategorie">
<option value="gastronomie">Gastronomie</option>
<option value="finanzen">Finanzen</option>
<option value="lebensmittel">Lebensmittel</option>
<option value="gewerbe">Gewerbe</option>
<option value="shopping">Shopping</option>
<option value="bildung">Bildung</option>
</select>
JS:
$(document).ready(function(){
$("#dropDownMenuKategorie").change(function(){
var selIndex = $(this).prop('selectedIndex');
var selVal = $("#dropDownMenuKategorie option:selected").val();
var selText = $("#dropDownMenuKategorie option:selected").text();
console.log(selIndex + selVal + selText );
});
});
I looked for a solution for this, but couldn't find it.
I have a simple select like this:
<select id="sltFiltroPedidos">
<option value="todos">Todos</option>
<option value="hoje">de hoje</option>
<option value="semana">da semana</option>
<option value="periodo">Período</option>
<option value="pedido">Número do pedido</option>
</select>
Always the user clicks on an option, a javascript event must be fired.
The onChange event in the select doesn't work for me, because the user can choose the same option, and the event must be fired as well.
I tried the onClick event on options. It works on IE and FF, but doesn't work on Chrome.
Any ideas how can I do it?
I wrote a code but it is not working on IE, just give it a try: http://jsfiddle.net/shahe_masoyan/scuhb/1/
<select id="sltFiltroPedidos">
<option value="todos">Todos</option>
<option value="hoje">de hoje</option>
<option value="semana">da semana</option>
<option value="periodo">Período</option>
<option value="pedido">Número do pedido</option>
</select>
var isOpen = false;
$('#sltFiltroPedidos').on('mouseup', function () {
if (isOpen){
alert(this.value);
}
isOpen = !isOpen;
});
As per your question you can do following :-
<select id="sel" onblur="showme()">
<option value="todos" >Todos</option>
<option value="hoje" >de hoje</option>
<option value="semana" >da semana</option>
<option value="periodo" >Período</option>
<option value="pedido" >Número do pedido</option>
</select>
But i don't know this right option or not. But this will work as you told.
function showme()
{
alert(document.getElementById('sel').value);
}
You can try onclick like,
var prevValue=$('select').val();
$('select').on('click',function(){
if(prevValue==this.value) // code for same values
// your code to run
});
I had the same issue. In my task, I needed to get the value of the selected option. This helped me:
let selectedOption = "";
<select>.addEventListener("change", event => {
selectedOption = event.target.value
});
The select variable is, obviously, the tag .
It might look strange, but select takes the value of the chosen option, that's why the code works.
Use:
$('#sltFiltroPedidos').on('change', function() {
alert( this.value );// or this.val()
});
Hope this will work for you
I was wondering what am I doing wrong here?
I have the following HTML:
<select name="somename" id="DropDownList1">
<option value=""></option>
<option value="1" valp="7700000000000000">Item 1</option>
<option value="2" valp="7C08000000000000">Item 2</option>
<option value="3" valp="5800000000000000">Item 3</option>
</select>
And the following JS/JQuery code that is called when the page loads:
$('#DropDownList1').change(function () {
onChangeDropDownList1(this);
});
function onChangeDropDownList1(obj) {
var vP = $(obj).attr('valp');
alert("valp=" + vP);
};
As the result I get "valp=undefined"
this in context of the .change() refers to the <select> rather than the <option>, so you're not getting the node with the valp attribute.
$('#DropDownList1').change(function () {
onChangeDropDownList1(this);
});
function onChangeDropDownList1(obj) {
// Get the selected option
var vP = $(obj).find(':selected').attr('valp');
alert("valp=" + vP);
};
Here is a demonstration.
The change function is providing you the select which was updated not the option. You need to query the :selected value out of it. Once you have the selected option you can query for the valp attribute
function onChangeDropDownList1(obj) {
var vP = $(obj).find('option:selected').attr('valp');
alert("valp=" + vP);
};
Fiddle: http://jsfiddle.net/Jpfs3/
Pass the option, not the select:
onChangeDropDownList1($(this).children(':selected'));
or, grab the option from the passed select:
var vP = $($(obj).children(':selected')).attr('valp');
Just put the JS code before the end of the body