Problem using jQuery change function on a select element - javascript

I am using a simple select element. On selecting a option in the select menu, I want to use jQuery's post method to update the div.
<select class="article">
<option value="title1">title1</option>
<option value="title2">title2</option>
<option value="title3">title3</option>
</select>
I want to bind the change event to the select element.
$(document).ready(function() {
$(".article").change(function() {
var src = $(this).val();
alert(src);
});
});
This does not work. I don't see the alert box on changing the select box.
I appreciate any help.

It does work fine
Working demo

This should work fine, have you included jQuery files. Please check that jQuery is included properly.
$(document).ready(function() {
alert('hello');
});
This should give an alert, in case this does not, then jQuery is not working properly.

$('select.foo option:selected').val(); // get the value from a dropdown select
More about the subject;
http://api.jquery.com/val/
http://api.jquery.com/selected-selector/
jQuery - setting the selected value of a select control via its text description

Related

Does html option supports mouseover events? [duplicate]

I want to alert an option when the mouse-cursor is over it. I use this code:
$("select > option").hover(function ()
{
alert($(this).attr("id"));
});
Unfortunately, this is neither working in IE nor in FF.
Can someone give me a hint please?
You can try this.
$("select").hover(function (e)
{
var $target = $(e.target);
if($target.is('option')){
alert($target.attr("id"));//Will alert id if it has id attribute
alert($target.text());//Will alert the text of the option
alert($target.val());//Will alert the value of the option
}
});
If you make a "listbox" type select box by adding a "size=x" attribute like this:
<select size="3">
<option>...</option>
<option>...</option>
</select>
The hover event will work on the option elements:
$('option').hover(function(){
//code here
});
Here's a workaround (quite decent I guess)-
Use mouseover event to set the size of the select box equal to the no. of its children
Use mouseenter event to get the options. mouseenter works on options perfectly when size attribute is there (we all know that now)
Use mouseout event to set the size of the select box back to 1, to get our normal select box back :)
JSFiddle

attr('selected','selected') not working in selectpicker bootsrap with ajax [duplicate]

I am attempting to retrieve and set the selected value of a select element (drop down list) with jQuery.
for retrievel i have tried $("#myId").find(':selected').val(), as well as $("#myId").val() but both return undefined.
Any insight into this problem would be much appreciated.
to get/set the actual selectedIndex property of the select element use:
$("#select-id").prop("selectedIndex");
$("#select-id").prop("selectedIndex",1);
The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.
Check the Id of the element and also check your markup validates at here at W3c.
Without a valid dom jQuery cannot work correctly with the selectors.
If the id's are correct and your dom validates then the following applies:
To Read Select Option Value
$('#selectId').val();
To Set Select Option Value
$('#selectId').val('newValue');
To Read Selected Text
$('#selectId>option:selected').text();
$('#myId').val() should do it, failing that I would try:
$('#myId option:selected').val()
When setting with JQM, don't forget to update the UI:
$('#selectId').val('newValue').selectmenu('refresh', true);
$("#myId").val() should work if myid is the select element id!
This would set the selected item: $("#myId").val('VALUE');
Suppose you have created a Drop Down list using SELECT tag like as follows,
<select id="Country">
Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..
var result= $("#Country option:selected").text();
it will work fine.
I know this is old but I just had a bear of a time with Razor, could not get it to work no matter how hard I tried. Kept coming back as "undefined" no matter if I used "text" or "html" for attribute. Finally I added "data-value" attribute to the option and it read that just fine.
<option value="1" data-value="MyText">MyText</option>
var DisplayText = $(this).find("option:selected").attr("data-value");
$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding
<select id="myId">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>`
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
Try this
$('#your_select_element_id').val('your_value').attr().add('selected');

Jquery Click select box option not work on Chrome [duplicate]

I'm having a problem in Chrome with the following:
var items = $("option", obj);
items.each(function(){
$(this).click(function(){
// alert("test");
process($(this).html());
return false;
});
});
The click event doesn't seem to fire in Chrome, but works in Firefox.
I wanna be able to click on a option element from a combo, if I do instead another kind of element, lets say <li> it works fine. Any ideas? Thanks.
I don't believe the click event is valid on options. It is valid, however, on select elements. Give this a try:
$("select#yourSelect").change(function(){
process($(this).children(":selected").html());
});
We can achieve this other way despite of directly calling event with <select>.
JS part:
$("#sort").change(function(){
alert('Selected value: ' + $(this).val());
});
HTML part:
<select id="sort">
<option value="1">View All</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
<option value="4">Last Modified</option>
<option value="5">Ranking</option>
<option value="6">Reviewed</option>
</select>
The easy way to change the select, and update it is this.
// BY id
$('#select_element_selector').val('value').change();
another example:
//By tag
$('[name=selectxD]').val('value').change();
another example:
$("#select_element_selector").val('value').trigger('chosen:updated');
I've had simmilar issue. change event was not good for me because i've needed to refresh some data when user clicks on option. After few trials i've got this solution:
$('select').on('click',function(ev){
if(ev.offsetY < 0){
//user click on option
}else{
//dropdown is shown
}
});
I agree that this is very ugly and you should stick with change event where you can, but this solved my problem.
I found that the following worked for me - instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));
<select id="myselect">
<option value="0">sometext</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
</select>
$('#myselect').change(function() {
if($('#myselect option:selected').val() == 0) {
...
}
else {
...
}
});
Looking for this on 2018.
Click event on option tag, inside a select tag, is not fired on Chrome.
Use change event, and capture the selected option:
$(document).delegate("select", "change", function() {
//capture the option
var $target = $("option:selected",$(this));
});
Be aware that $target may be a collection of objects if the select tag is multiple.
I use a two part solution
Part 1 - Register my click events on the options like I usually would
Part 2 - Detect that the selected item changed, and call the click
handler of the new selected item.
HTML
<select id="sneaky-select">
<option id="select-item-1">Hello</option>
<option id="select-item-2">World</option>
</select>
JS
$("#select-item-1").click(function () { alert('hello') });
$("#select-item-2").click(function () { alert('world') });
$("#sneaky-select").change(function ()
{
$("#sneaky-select option:selected").click();
});
What usually works for me is to first change the value of the dropdown, e.g.
$('#selectorForOption').attr('selected','selected')
and then trigger the a change
$('#selectorForOption').changed()
This way, any javascript that is wired to
Maybe one of the new jquery versions supports the click event on options. It worked for me:
$(document).on("click","select option",function() {
console.log("nice to meet you, console ;-)");
});
UPDATE: A possible usecase could be the following: A user sends a html form and the values are inserted into a database. However one or more values are set by default and you flag this automated entries. You also show the user that his entry is generated automatically, but if he confirm the entry by clicking on the already selected option you change the flag in the database. A rare sue case, but possible...
I know that this code snippet works for recognizing an option click (at least in Chrome and FF). Furthermore, it works if the element wasn't there on DOM load. I usually use this when I input sections of inputs into a single select element and I don't want the section title to be clicked.
$(document).on('click', 'option[value="disableme"]', function(){
$('option[value="disableme"]').prop("selected", false);
});
Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use
$('#yourSelect option:selected').html();
You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.
$ ('#yourSelect' ).change(() => {
process($('#yourSelect option:selected').html());
});
If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()
Workaround:
$('#select_id').on('change', (function() {
$(this).children(':selected').trigger('click');
}));

populate and disable text field depending on dropdown

Unfortunately i'm not too familiar with javascript/jQuery. I have a form with a dropdown. What i need to do is to populate a text field depending on the selection of the dropdown. First voice of the dropdown is "other" so the text field must be writable, then from the second i want to assign a value automatically and disable the text field.
The value of the dropdown will be saved in the db so it must remains the name of the option.
I found several solutions with google but none of them fits my needs...hope someone could help me.
To create the functionality you're looking for, there are a few basic things you'll need to learn.
jQuery Selectors
First, if you aren't already familiar with jQuery's selector syntax, learn about it here.
The .change() Event
Next, you'll need to know how to bind to the dropdown menu's .change event. One way to do this is $('#dropdownId').change(function() { ... });, which is just a shortcut for $('#dropdownId').on('change', function() { ... }); . Within the callback functions, you can access the dropdown element with this and as a result, the jQuery object with $(this).
We can then grab the dropdown's value with $(this).val() and use some basic logic to enable/disable the textbox and set its value.
Enabling/Disabling the textbox
In order to enable/disable the textbox, you can use: $('#txt').removeAttr('disabled');and$('#txt').attr('disabled', 'true');` respectively.
Example
I've combined all of these for you in an example fiddle to show you how you can put these together in this jsFiddle. Let me know if you have any questions about how it works :)
Here is the fiddle for you...
http://jsfiddle.net/G3V3v
HTML:
<select id="ddl">
<option value="0">[ Other ]</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<input id="txt" />
jQuery:
$('#ddl').change(function() {
if ($(this).val() == 0) {
$('#txt').val('').removeAttr("disabled").focus();
} else {
$('#txt').val($(this).children('option:selected').text());
$('#txt').attr("disabled", "disabled");
}
});

When trying to remove any selected option in an select element, Safari shows it as blank

Examine this code. I'm using jQuery, but I think it is probably irrelevant.
JavaScript
​$(function() {
$('button').click(function() {
$('select option[selected]').removeAttr('selected');
});
});
HTML
<select>
<option>a</option>
<option selected="selected">b</option>
<option>c</option>
</select>
<button>give me a click</button>
This was working fine for having the button reset the select to the first option. I just tested it in Safari, and it blanks the select instead of selecting the first.
This isn't an issue, until I got it up and running on an iPad, which is where the majority of this web app will be used. The problem with the iPad is, after then selecting an option, the select refuses to display the option selected. It still displays as blank.
What is the best way to get around this?
​
You can fix the behaviour by explicitly setting the index using JavaScript's native selectedIndex property.
$(function() {
$('button').click(function() {
$('select option[selected]').removeAttr('selected');
$('select')[0].selectedIndex = 0;
});
});​
If you have more than one select element, you will need to iterate through with jQuery's each and set the property on this.
What about:
$('select option:first-child').attr('selected', 'selected');

Categories