How to pass jquery $(this) .to a function? Javascript or Jquery

How to pass jquery $(this) .to a function? Javascript or Jquery
or it could be another way of working the dropdown

<html lang="en"><head>
    </head>
    <body translate="no">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

        <select name="Australian-Brother">
            <option>not</option>
            <option>yes</option>
        </select>

        <select name="Australian-Brother">
            <option>Not</option>
            <option>Yes</option>
        </select>


        <script>
            $("[name='Australian-Brother']").on('change', function () {
        var selectedTextDisplay = $(this).children(':selected').text();
        
        function USA_Brothers(){
            if (selectedTextDisplay === 'yes') {
                $(this).html("<option>not</option><option>yes</option>");
            } else {
                $(this).html("<option>yes</option><option>not</option>");
            }
              } 
          USA_Brothers();
    });
        </script>

    </body></html>

Not really sure what you are doing as it doesn’t seem to make sense but you could save $this to a variable at the start.

e.g.
var myEl = $(this);

$("[name='Australian-Brother']").on("change", function () {
  var selectedTextDisplay = $(this).children(":selected").text();
  var myEl = $(this);

etc.......

Then you can call it like this:

  function USA_Brothers() {
    if (selectedTextDisplay === "yes") {
      myEl.html("<option>not</option><option>yes</option>");
    } else {
      myEl.html("<option>yes</option><option>not</option>");
    }
  }

Or you could pass it in the function instead of a variable.

 function USA_Brothers(myEl) {
    if (selectedTextDisplay === "yes") {
      myEl.html("<option>not</option><option>yes</option>");
    } else {
      myEl.html("<option>yes</option><option>not</option>");
    }
  }
  USA_Brothers($(this));

I don’t know what you are expecting to achieve though as it seems you are just stopping the first select from being selected as yes. Note that on your second select you have Yes with a capital Y so that won’t match ‘yes’.

I’m sure a JS guru will be along in a minute to offer something better than my basic JS :slight_smile:

1 Like

Worked, thank you

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.