-1

I'd like to accomplish what is being done here except with one twist: I want each event to target different elements.

The use case is a select box that should fire an event if anything but the first "choose your option" option is selected

$(document).on('change', 'select:nth-child(1)', function(e) ){
  do_stuff();
});


$(document).on('click', 'select:not(:first-child)', function(e) ){                         
  do_stuff();
});

Is there a combined, cleaner way to do this, without having to create do_stuff()?

How can this be done without the event firing twice?

Community
  • 1
  • 1
ahnbizcad
  • 10,491
  • 9
  • 59
  • 85
  • Inspect the target in the handler. – Evan Davis Dec 16 '15 at 21:16
  • 1
    what is the purpose of the first event on there? seems the second one will fire on all events except the first one already... – omikes Dec 16 '15 at 21:19
  • @oMiKeY in my code, i have a swatch that triggers a dropdown selection change as well. But I don't want it to do stuff if the first option is selected. I also have code existing in the 'change' event. The portion relies on state variables that i'd like to have available. – ahnbizcad Dec 16 '15 at 21:44

2 Answers2

1

Test the position in the function.

$(document).on("change click", "select option", function(e) {
    if ($(this).index() == 0) {
        // do stuff for first child
    } else {
        // do stuff for other children
});

However, I don't think the change event is fired on <option> elements, it just fires on the <select> itself. So your basic premise seems to be wrong, because the change event would never fire on select:nth-child(1).

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • one thing is that it is not the `option` that changes. the `select` changes. so I guess that means within, we have to do something like `$(this).find(">:first-child").index()` instead. – ahnbizcad Dec 17 '15 at 00:14
1

You have an answer but you could also use some combination of this:

NOTE: tab to the element on the page to trigger the focusin event

$('#selectcontainer').on('change focusin manual', ".myselectthing", function(e) {
  var selectionIndex = $(this).prop('selectedIndex');
  $('#results').text("this type " + e.type + ":" + $(this).val() + " : " + selectionIndex);
});

$('#selectcontainer').find('.myselectthing').val("ralf").trigger("manual");

Some sample markup:

<div id="results">
  empty
</div>
<div id="selectcontainer">
  <select class="myselectthing">
    <option value="me">choose me</option>
    <option value="ralf">choose ralf</option>
    <option value="charlie">choose charlie</option>
  </select>
</div>

Play with it: https://jsfiddle.net/96mgswas/1/

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100