jQuery: set selected value of dropdown list? - javascript

What's wrong with this code?
jQuery
$(document).ready(function() {
$("#routetype").val('quietest');
)};
HTML
<select id="routetype" name="routetype">
<option value="fastest">Fastest</option>
<option selected="true" value="balanced">Balanced</option>
<option value="quietest">Quietest</option>
</select>
Fiddle
It gives me 'Balanced' as the selected option, not 'Quietest'.

UPDATED ANSWER:
Old answer, correct method nowadays is to use jQuery's .prop(). IE, element.prop("selected", true)
OLD ANSWER:
Use this instead:
$("#routetype option[value='quietest']").attr("selected", "selected");
Fiddle'd: http://jsfiddle.net/x3UyB/4/

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

You can select dropdown option value by name
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});

Related

jQuery collection gets broken inside each loop (remove elem, restore innerHTML)

I expected the following code to iterate through a select options and remove options having a certain value, otherwise restore the select html
var initialHTML = $('#myselect').html();
$('#myselect option').each(function(){
if($(this).val() === 'b'){
$(this).remove();
console.log('matching. removed.');
return false;
}else{
$('#myselect').html(initialHTML);
console.log('not matching. html restored.');
}
});
Expected select would be:
<select id="myselect">
<option value="a">a</option>
<option value="c">c</option>
</select>
but it actually is
<select id="myselect">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
What I'm doing wrong? FIDDLE
Update e.g. as someone suggested:
The $('#myselect option') constructs a list of options, and
$(this).remove() removes option b, but the list of options is no
longer linked to the HTML, because the HTML had been already changed
by $('#myselect').html(initialHTML) which was executed for option
a
so, I've realised that the actual problem is not even related to what I asked initially in my question. Sorry for that and I'll try to put it in the right section.
p.s. a working solution:
var initialHTML = $('#myselect').html();
function doIt(){
$('#myselect').html(initialHTML);
$('#myselect option').each(function(){
if($(this).val() === 'b'){
$(this).remove();
}
});
}
Thank you so much for help.
The main issue is this line:
$('#myselect').html(initialHTML);
It is executed for option a and then option b can no longer be removed because the HTML has changed even though it is actually identical. So remove that line and your code will work.
$('#myselect option') constructs a list of options, and $(this).remove() removes option b from the list, but the list is no longer associated with the HTML, because the HTML had been already changed by $('#myselect').html(initialHTML) which was executed for option a.
var initialHTML = $('#myselect').html();
$('#myselect option').each(function() {
if (this.value === 'b') {
$(this).remove();
console.log('matching. removed.');
return false;
} else {
//$('#myselect').html(initialHTML);
console.log('not matching. html restored.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
<option>a</option>
<option>b</option>
<option>c</option>
</select>
I changed $(this).val() to this.value. Both will work, but the second one is a bit more efficient because there is no point in converting the JavaScript object to a jQuery object just to get the value.
However, remember that the line:
return false;
will cause the each() loop to exit once a match is found. That's OK if there will only be one match. If there can be more that one match, remove that line so the loop can go through all options.
Here is an alternative way:
Other answers already point out the reason, as because you refresh the option list the during the first iteration, $(this).remove() no longer works because it lose contact of the original item. Thus, a simple fix here would be re-select the target based on it's value. And you can keep your original code of $('#myselect').html(initialHTML); in the loop.
var initialHTML = $('#myselect').html();
$('#myselect option').each(function(){
if($(this).val() === 'b'){
$("option[value='" + $(this).val() + "']").remove();
console.log('matching. removed.');
return false;
} else {
$('#myselect').html(initialHTML);
console.log('not matching. html restored.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>
Try this:
you don't need else part as it is already present and put your jquery inside document.ready so that it will ensure DOM is ready and you can run the jquery script.
var initialHTML = $('#myselect').html();
$(document).ready(function(){
$('#myselect option').each(function(){
if($(this).text() == 'b'){
$(this).remove();
console.log('matching. removed.');
return false;
}
});
});
JSFiddle
What is happening here is that you have something that only needs to be false once to restore the entire select. So it does remove 'b' when it finds it, but then restores the whole select once it sees that 'c' !== 'b'.
You can achive your expected behavior by removing:
else{
$('#myselect').html(initialHTML);
console.log('not matching. html restored.');
}
Depending on what your ultimate goal is, there may be better ways of approaching this, though.
Hope that helps.

Why select on change method doesn't work?

I try to call a function when a value from the select box is chosen. I would also have a default value selected and a button appear for that value on the page.
This is my select box:
<select id="messagingMode" class="bootstrap-select" >
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
This is the js:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
And the function just prints the selected value for the moment:
function showCorrespondingAuthorizationBtn(select) {
console.log(select.val());
}
Nothing is printed in the console, why doesn't this work?
Try with direct call function name not with function() .Default bind with this in change function
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn() {
console.log($(this).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="messagingMode" class="bootstrap-select">
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
You are invoking the function, not passing it as reference. Also this is not what you think it is in that context.
Try:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn(event) {
console.log($(this).val());
// or
console.log(this.value);
}
Use the jQuery event delegation:
$('#messagingMode').on('change',function(){
console.log($(this).val());
});
Here is a working fiddle.
$('#messagingMode').change(function () {
showCorrespondingAuthorizationBtn($(this).val());
});
It is not triggering because your are invoking the method on your event attachment logic.
// calling the invocation operator () triggers the method
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
In order to solve this, try the following code.
function onDropdownChanged() {
var sender = $(this);
console.log(sender.val());
}
$(document).ready(function() {
$('#messagingMode').on("change", onDropdownChanged);
})

how to get the selected option id in jquery

I'm looking for some way to print the ID, or let me select the ID from an option in a select
here my code:
$(document).ready(function() {
$("#direcciones-envio-usuario").click(function() {
alert(this.id);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker show-tick" id="direcciones-envio-usuario" data-width="85%" data-header="Eligir dirección">
<option>Mi casa</option>
<option>Casa de pepe</option>
<option data-divider="true"></option>
<option data-icon="glyphicon-plus-sign" id="nueva_direccion_btn">Nueva dirección</option>
</select>
Use change event instead of click event, here use :selected selector
$("#direcciones-envio-usuario").change(function(){
alert($(':selected', this).attr('id'));
});
I prepared this example in a fiddle, i hope will be useful https://jsfiddle.net/jgonzalez315/8znq29g7/
$(document).ready(function(){
$("#direcciones-envio-usuario").change(function(){
alert($( "#direcciones-envio-usuario option:selected" ).text());
if($( "#direcciones-envio-usuario option:selected" ).text()=="Nueva dirección")
{
//IF YOU WANT attr id
alert($( "#direcciones-envio-usuario option:selected" ).attr('id'));
}
});
})
Please check the plunk
The main code to get this to work for your example is:
$(document).ready(function(){
$("#direcciones-envio-usuario").change(function(){
alert($(this).children("option:selected").attr("id"));
});
})
I think this solves what you were tring to achieve. Let me know if you need any refinements :)
How about
$("#direcciones-envio-usuario").change(function(){
alert($(this).children(":selected").attr("id"));
});
Also, since it is a select element it would be wise to change your event to .change() instead of .click().
You can use the contextual this to select the child, which is selected, and get its ID attribute.
$("#direcciones-envio-usuario").change(function(){
alert($(this).find(":selected").attr("id"));
});

Select box option value on right-click: without using option:selected

My question is different than just "how do I get the selected option from a select box".
In select box, no option element is 'selected' prior to right-clicking on it.
On right-clicking an option, I want to get the value of that option element.
Therefore, option:selected won't work.
<select name='mySel' id='mySel' multiple>
<option value='val1'>myOption1</option>
<option value='val2'>myOption2</option>
</select>
I have bound rightclick event to the context menu:
// bind right click event to context menu
(function( $ ) {
$.fn.rightClick = function(method) {
$(this).bind('contextmenu rightclick', function(e){
e.preventDefault();
method();
return false;
})
};
})( jQuery );
The event handler code below will only work if an option is selected prior to right clicking:
$('#mySel').rightClick(function(e){
alert($('#mySel option:selected').text());
});
Without using option:selected, how do I get the value of right-clicked option?
The target property of the event parameter will refer to the element which triggered the event, in your case the option element that was right-clicked:
$('#txBase').rightClick(function(e){
alert(e.target.value); // val1 or val2
});
DEMO
A few notes about your code:
no need to return false and to e.preventDefault, both statement have the same result so just use one or the other
you might wanna check if method is not undefined and is a function before calling it, otherwise it will break
when you call method, pass the parameter e to it otherwise you won't be able to use inside your callback
Here's the modified code:
$(this).bind('contextmenu rightclick', function(e) {
e.preventDefault();
if (method && $.isFunction(method)) {
method(e); // pass the event parameter to your callback
}
})
<select name='mySel' id='mySel' multiple>
<option value='val1' oncontextmenu="getValue(this);return false">myOption1</option>
<option value='val2' oncontextmenu="getValue(this);return false">myOption2</option>
</select>
<div id="status"></div>
<script>
function getValue(t){
document.getElementById('status').innerHTML=t.value;
}
</script>
What about this?

Getting rid of the onclick when clicked with jQuery

ok so i have some select tags of cities
<select onchange="storeCity(this.value, false)" name="search[city]" id="search_city" class="left">
<option value="">== Select City ==</option>
<optgroup label="Florida"><option selected="selected" value="ft-myers-sarasota-fl">Ft. Myers / Sarasota </option>
<option value="jacksonville-fl">Jacksonville</option>
<option value="miami-fl">Miami / Ft. Lauderdale </option>
<option value="orlando-fl">Orlando</option>
<option value="tampa-fl">Tampa</option></optgroup></select>
Some cities are not available now so i needed a lightbox to popup when they are clicked...which i have working with this code
$('#search_city').change(function(e) {
e.preventDefault();
if ($(this).val() == 'jacksonville-fl' || $(this).val() == 'miami-fl' || $(this).val() == 'tampa-fl' || $(this).val() == 'ft-myers-sarasota-fl') {
}
The problem I have is that it goes to the link anyways and i need it to get rid of the link or the onchange on the select...something is getting the page to refresh...but i dont know what
storeCity(this.value, false) might have caused the refresh
BTW, you can merge the code like this:
$('#search_city').change(function(e) {
storeCity(this.value, false);
if (this.value.match(/(jacksonville-fl|miami-fl|tampa-fl|ft-myers-sarasota-fl)/i)) {
//do some stuff
}
e.preventDefault();
});
You could probably use jQuery's .one() function for this. E.g.
$('#search_city').one('change', function() {
/* Your code */
});
The change event will only execute once.
you have a method called
storeCity(this.value, false)
on change event , this might be refreshing the page. check that out.
Also a word of warning - I'd not use e.preventDefault() on a CHANGE event (unless you really need to), as it can have some weird behaviour in some browsers. Usually that's just for CLICK events.

Categories