0

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

1
  • 1
    $(obj).closest('td').next('td').find('.select').on("change",function() { if (this.value==="i") functionName() }) Commented Sep 29, 2020 at 13:58

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

I guess there is also a .select method in jquerry , maybe it could also help
jQuery does have a select() method, but it's not relevant to this case at all
0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.