Reputation: 267
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
Upvotes: 0
Views: 533
Reputation: 243
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>
Upvotes: 0
Reputation: 89
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")
.
Upvotes: 0
Reputation: 337560
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>
Upvotes: 3