How Can I Interact With <option> - javascript

Lets say I have
<select>
<option value="longSleeve">Long Sleeve</option>
<option value="shortSleeve">Short Sleeve</option>
</select>
how can I make my code do something when one is pressed.
For example how can I make a variable set to 1 when 'Long Sleeve' is chosen and set the variable to 2 when 'Short Sleeve' is chosen and then if 'Long Sleeve' is chosen again set it back to 1.
Also pardon my noobyness at coding

What you are looking for is the onchange event handler, in jQuery you can use .change() or .on('change', handler) like this:
var someVariable;
$('select').on('change', function(){
someVariable = this.selectedIndex + 1;
});

with jquery you can always add listeners like
.click()
to any tag on your html code, maybe you can add an id to that tag
<option id="firstOption" value="longSleeve">Long Sleeve</option>
and have something like
$("#firstOption").click(function(){
alert("click First option!");
});
hope this help : )
link to jquery reference...

Related

Adding onclick attribute to a dynamically created option

I have a script where I am appending options to a select item and would add the onclick method to them.
My piece of code is this:
$(obj).closest('td').next('td').find('.select').append(new Option("i", "i"));
and this is how it looks when I inspect them:
<option value="i">i</option>
but I want them to be
<option onclick="functionname" value="i">i</option>
Is there anyway to do it with jQuery? Thanks in advance
A much better idea would be to put a click event handler on the select itself, then read the value which was selected.
This is for two reasons. Firstly inline event attributes, such as onclick, are no longer good practice and should be avoided where possible. Secondly, event handlers on option elements are unreliable at best and just plain don't work at worst.
The best way to achieve what you need is to add a change event handler to the select and read the selected value from the chosen option at that point, something like this:
let $foo = $('#foo').on('change', e => {
console.log(e.target.value);
});
$('button').on('click', () => {
let ts = (new Date()).getTime();
$foo.append(`<option value="${ts}">${ts}</option>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add option</button>
<select id="foo"></select>
I wouldn't do it for an onclick attribute since, as already stated, there are faster and better ways to reference it directly from JS. But for future reference or if you need to set other attributes, you can use the built in setAttribute. An example would be yourelement.setAttribute("class","classname").
After adding a new option, you could create a listener for that select like this:
jQuery('select').change(function(){
const value = jQuery(this).val();
console.log(value);
});
jQuery('select').append(new Option('New Option', 'value'));
jQuery('select').change(function(){
const value = jQuery(this).val();
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>

jQuery find all attr rel

I have a this select dropdown:
<select id="category">
<option value="cat1">Category 1</option>
<option value="cat2">Category 2</option>
</select>
and I have this code that everytime I select something form the dropdown it takes the value and find the same class and show it on the last line
$('#category').change(function () {
var selected_category = $(this).val();
$('#sub-category').find('.option').hide();
$('#sub-category').find('.'+selected_category).show();
});
I just want to change instead of class so it will find the attribute rel
** edited **
You definitely don't need jQuery for this. Here's the code to find all option tags with a rel attribute of "sub-cat1":
document.querySelectorAll('option[rel="sub-cat1"]')
The above will work in IE8 and up, which should satisfy all browsers you need to support. The jQuery solution is similar, and uses the same selector string:
$('option[rel="sub-cat1"]')
Furthermore, you don't need to add a class of "option". Simply select using the option tag name.
There can be an alternate way to your answer.
Using jquery try ,
$ (".classname").each(function(){
//iterate over similar *classname* elements one by one
$(this).someFunc(); //it will help you to preform operation at current value while iteration
});
With rel if you want to iterate over rel tag values , try
$("[rel='sub-cat-1']").each(function(){
//Some operation
});

jQuery display none a option in a form

I want to display none a option of a form.
HTML:
<option class="level-0" value="top-10-villen-de">Top-10-Villen</option>
jQuery:
if(jQuery('option').attr('value') == 'top-10-villen-de'){
jQuery(this).css('display', 'none');
}
I've a issue in my if statement but I can't figure out where is my issue.
Can somebody helps me?
Thank you.
Hiding the dropdown option isn't compatible with all browser.
I've got a better option.
wrap the option into span and when you need it back unwrap it
Fiddle link : http://jsfiddle.net/xms2uydx/
You are using wrong this see this example for THIS Scope
http://jsfiddle.net/kevalbhatt18/r2m2ucgv/2/
The above example is give you difference between two this.
1. which is out of Jquery.
2. which is inside jquery function.
so as you can see in example first console i.e console.log(this) will return window object.
2 . $(this) which is inside click function will give you different value it is related to your button it will gives you button scope
you can also use
jQuery('option').find('.level-0').css('display', 'none')
if you know the class of option.
HTML
<button>option 1</button>
<button>option 2</button>
<select>
<option class="level-0" value="top-10-villen-de">Top-10-Villen</option>
<option class="level-1" value="top-1">Top-20</option>
</select>
Jquery
console.log(this)
$('button').click(function () {
if ($(this).text() === "option 1") {
if (jQuery('option').attr('value') == 'top-10-villen-de') {
console.log('inside')
console.log(jQuery('option[class="level-0"]'))
jQuery('option[class="level-0"]').css('display', 'none');
}
} else {
jQuery('option[class="level-0"]').toggle()
}
})
That is because context this in if statement do not refer to option element.Correct way to achieve this would be to find element with attribute value equal to top-10-villen-de along with .hide():
jQuery('option[value="top-10-villen-de"]').hide();
FYI, the hiding of option elements do not work. a good workaround for this would be to disable the option by setting its disabled property to true.
In jQuery , whenever you have more than one element in DOM , then to access all elements you have to use $('selector').each(function(index,Obj){}).
Use this code to hide the options you want
$('#temp').find('option').each(function(index,Obj){
if($(this).attr('value')=='2')
$(this).css('display', 'none');
})
Demo
You can set display none when it the value is top-10-villen-de
jQuery( "select" ).change(function() {
if(jQuery(this).val() == 'top-10-villen-de'){
jQuery(this).find("option[value='top-10-villen-de']").css('display', 'none');
}
});
Here the fiddle
https://jsfiddle.net/jva8ju1s/

How to get the value of a select box element by its option in javascript?

My select box is as follows:
<select id='list'>
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
</select>
I want to get the value of option - B without selecting it.
With jQuery I can do the opposite i.e get the text when I know the value through following:
$("#list option[value='2']").text();
But I want the reverse. I tried with following but not working:
$("#owner option['B']").val();
How can I do this?
Use the :contains selector.
Assuming "owner" really is the ID of your <select> (it's "list" in your example), you can use:
$("#owner option:contains('B')").val() // 2
You can use the :contains(text) selector, to only get the elements that contain certain text:
$("#list option:contains('B')").val();
You can use .filter to get the right option element:
$("#list option").filter(function() {
return $(this).text() == "B";
}).val();
http://jsfiddle.net/JWjKf/
try this
var b = $("#list").find('option:contains("B")').val();
see here : http://jsfiddle.net/MxpTZ/1/
Try this script
$('#list option:contains("B")').prop('value') //jquery 1.6 or later
oR
$('#list option:contains("B")').attr('value');
If you wanted to get the element by position, you can do this:
$('#list').children().eq(1).val();

jQuery set click handler with per-element information

I have a onclick attribute ontag now that gets set serverside with the REQUIRED_ID for when the user clicks on it.
The problem now is that I am trying a more jQuery-like approach where I do set the click handlers on document ready but now I don't have the REQUIRED_ID at hand to set it.
I'm wondering what would be the jQuery way of doing this, perhaps setting another tag with the REQUIRED_ID and reading it on ready?
NOW:
$.ready(
$('select.attr_satus>option:not(:selected)').each(
/* I AM MISSING REQUIRED_ID, WHERE DO I GET THIS VVVVVV*/
$(this).click(function(){ statusChanged(this,REQUIRED_ID,$(this).val()); })
);
);
BEFORE:
<select class="attr_status">
<option onClick='statusChanged(this,REQUIRED_ID,"draft");' value='draft'>Draft</option>
<option value='publish' selected="true">Published</option>
</select>
REQUIRED_ID is an id that changes per row, as I have several of those select tags one after each other.
You can store your extra information in "data-" attributes:
<select class="attr_status">
<option data-requiredId='REQUIRED_ID' value='draft'>Draft</option>
Then in your event handler you can get it with ".data()":
$(this).click(function() {
statusChanged(this, $(this).data('requiredId'), this.value);
});
edit — Now "data-" attributes are standardized with HTML5. Another approach is to use the "class" string, which can contain pretty much anything. What I've done is use a "name:value" notation:
<select class="attr_status">
<option class='requiredId:REQUIRED_ID' value='draft'>Draft</option>
Then in the handler:
$(this).click(function() {
var id = this.className.replace(/^.*\brequiredId:(\S+).*/, '$1');
statusChanged(this, id, this.value);
});

Categories

Resources