Adding onclick attribute to a dynamically created option - javascript

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>

Related

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

How Can I Interact With <option>

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...

Getting second value in jQuery dropdown

How would I get the second value in a dropdown list using javascript or jquery?
<select id='dropdown'>
<option selected>Any</option>
<option>2</option>
<option>3</option>
</select>
e.g. i would like to get the value of number 2 in the dropdown
Neither of those options has a value. (Actually, see note below.) You can get the text like this:
var text = $("#dropdown")[0].options[1].text;
Or without jQuery:
var text = document.getElementById("dropdown").options[1].text;
Live Example | Live Source
Or you can use .value instead of .text, as the option elements will default their value property if you don't give them a value attribute. (You can't select them using a value= selector, but the property is defaulted.)
To get the second value in a dropdown list using jquery, you can do this using .eq():
var text = $("#dropdown option").eq(1).text();
In order, to get the n th number value in the dropdown list, you can do this:
var text = $("#dropdown option").eq(n - 1).text();
Try this
JS CODE
$(function(){
alert($('#dropdown option').eq(1).val());
});
LIVE DEMO
Why not try this so easy to understand then :eq(n)
http://jsfiddle.net/q9qCR/2/
$('#dropdown option:nth-child(2)').val()
Try
$(document).ready(function() {
alert($("#dropdown option").eq(1).text());
});

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