how to get the selected option id in jquery - javascript

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"));
});

Related

Capture value of a hidden input element jQuery

I have the following input element:
<input type="hidden" id="input_2_204_data" name="input_2_204_data" value>
I need to capture an event when it is changed and value is not empty. I have looked over older SO's questions, however nothing seemed to work.
Here is the latest snippet I have come up with, however it does not work either, and there are no errors in console:
jQuery(document).ready(function(){
var $sign = jQuery('[id$=input_2_204_data]');
$sign.on("change", function(){
alert('hey');
});
});
Any help or guidance is much appreciated.
jQuery(document).ready(function(){
var $sign = jQuery('#input_2_204_data');
alert($sign.val())
});
You have wrong selector to target element, You need to use ID selector # here to target element by id:
var $sign = jQuery('#input_2_204_data');
$sign.on("change", function(){
console.log($(this).val());
});
You have to use the correct selector #input_2_203_data. Using .change() works just fine.
jQuery(document).ready(function(){
var $sign = jQuery('#input_2_204_data');
$sign.change(function() {
if($sign.val() != '') {
alert( "Handler for .change() called." );
}
});
});

Hide a div based on a select input box

I was helped with some code here. I tweaked it to try and hide a whole div instead of an element. It was only a small tweak but I seem to have done something to stop it working.
HTML
<input type="text" name="text-708" value="" class="wpcf7-validates-as-required" size="40">
<div id="added_fields">
<select name="menu-168" class="wpcf7-validates-as-required">
<option value="Residential">Residential</option>
<option value="Commercial">Commercial</option>
</select>
</div>
JS
if ($("select[name='menu-168']").val() == "Commercial") {
$("#added_fields").addClass("hidden");
}​
Would someone be kind enough to tell me where I have gone wrong?
You need to do the check of the select value when it changes.
I want to hide the input box not the select box im afraid
In that case you need to change the #added_fields selector. Try this:
$("select[name='menu-168']").change(function() {
if ($(this).val() == "Commercial") {
$('#added_fields').addClass("hidden");
}
else {
$('#added_fields').removeClass("hidden")
}
});
Example fiddle
You did not write the code on change event of select and your selected value at load is not commercial so your statement under if does not execute.
Live Demo
$("select[name='menu-168']").change(function() {
if ($("select[name='menu-168']").val() == "Commercial") {
$("input[name=text-708]").addClass("hidden");
}
else
$("input[name=text-708]").removeClass("hidden");
});​
Try changing the following line
$("#added_fields").addClass("hidden");
to
$("#added_fields").hide();
Try this :
$("select[name='menu-168']").change(function() {
if ( $(this).val() == "Commercial") {
$("#added_fields").hide();
}
});​
try
$("#added_fields").hide();
you can find more information here: http://api.jquery.com/hide/
Updated: If you want to refer to the change event of your select you have to either fire your function in the onselectedindexchanged attribute of your select or add a change event on it via jQuery:
$("select[name='menu-168']").change(function() {
if ($(this).val() == "Commercial") {
$("#added_fields").hide();
}
});
more info about change: http://api.jquery.com/change/
Make sure you have the option:selected property in the change event of the select list
$("select[name='menu-168']").bind("change",function(e){
if ($("select[name='menu-168'] option:selected").val() == "Commercial") {
$("#added_fields").hide();
}
});
hay yomiss to call the change event of the select box.
check this fiddle.
http://jsfiddle.net/K9zGP/44/
$("select[name='menu-168']").change(function(){
alert($(this).val());
if ($(this).val() == "Commercial") {
$("#added_fields").addClass("hidden");
}
});
Try this:
$("select").change(function(){
if($("select option:selected").val() == "Commercial")
$("input[name=text-708]").hide();
else
$("input[name=text-708]").show();
});
​
​ DEMO
You have to "attach" to a event "hide".
So you can do this with click() (or change()) event like in this fiddle.
Your code is only executing once, on $(document).ready();. Wrap it in a .change() event handler.
$("select[name='menu-168']").change(function(e) {
if ($(this).val() == "Commercial") {
$("#added_fields").addClass("hidden");
}
});​
Updated fiddle: http://jsfiddle.net/K9zGP/36/
UPDATE:
To make the text-input reappear in jsfiddle.net/K9zGP/46, use .toggleClass() instead:
$("select[name='menu-168']").change(function(e) {
var isCommercial = $(this).val() == "Commercial";
$("#added_fields").toggleClass("hidden", isCommercial);
});​
YAF: http://jsfiddle.net/K9zGP/71/

jQuery click event not working on option element

Why doesn't the following code work?
$('select option').live('click', function(){
alert('hello')
})
html:
<select class="ok">
<option>5</option>
</select>
EXAMPLE: http://jsfiddle.net/fQxj7/2/
Do this instead:
$('select').change(function(){
alert('hello');
});
If you need to know the selected value inside the event handler, then you can do this:
$('select').change(function() {
var selectedOption = $(this).val();
});
http://jsfiddle.net/FishBasketGordo/2ABAh/

jQuery: set selected value of dropdown list?

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");
}
});

jQuery - How to select dropdown list item by text?

How would I select my dropdown list item by text rather than value?
I want to select a dropdown item by text with jQuery.
use :contains()(link)
$("select option:contains(text)").attr('selected', true);
demo
There is a filter function on jQuery that you can use to get elements with something more specific
$("select option").filter(function() {
return $(this).text() == "text_to_select";
});
This is going to return all options with the "text_to_select" in the text.
i think this will do the trick for you...
$("#selectId").find("option:contains('text')").each(function(){
if( $(this).text() == 'Text that should be matched' ) {
$(this).attr("selected","selected");
}
});
Here's the code I use (it's not quite the same as the other suggestions here, and works with jQuery v1.8.3)
var userToSearchFor = 'mike'; // Select any options containing this text
$("#ListOfUsers").find("option:contains('" + userToSearchFor +"')").each(function () {
$(this).attr("selected", "selected");
});
<select id="ListOfUsers" ></select>
Hope this helps.
I had a similar scenario with dropdowns for country, state and city. Country had "India" as well as "British Indian Ocean Territory". The issue with :contains() is that it attempts on both matches. I did something like:
$('#country option').each(function(){
if($(this).text() == 'India'){
$(this).prop('selected', true).trigger('change');
}
});
$("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected');

Categories