Home > database >  js "Void function return value is used" meaning
js "Void function return value is used" meaning

Time:01-20

I have the following code where the alert is working but when I select the option with the given id, nothing happens. JS:

var connType = (function() {
  alert("test");
  $("#connType").change(function() {
    if ($(this).css("value") === 2 {
      $(".mgconn").css("display", "block");
    }
  });
})();

HTML

<div >
  <div >
    <select  id="connType" name="connection_type">
      <option selected value="1">first op</option>
      <option value="2">something</option>
    </select>
  </div>
</div>
<div  style="display: none">
     <div >
          <input  placeholder="" type="text"/>
                                           
                                    
</div>

In ide I have the void function highlight, and I don't understand what it means. I don't see what return I should have in here. I'm sorry for the simplicity of my question, I realize it must be something basic and I can't figure really what to look after in the console, to test it.

CodePudding user response:

Your IDE warning is because you are assigning the result of a function that returns undefined to a variable.

It's not a javascript error, it's just an IDE warning. Depending on your IDE, you'll probably get the same warning with this code:

function example() {
}
var x = example()

You can confirm this with console.log(connType) (===undefined) in your code.

You can safely remove the var connType = part of your code and have the IIFE run without needing to assign to a variable.

CodePudding user response:

I have found out that the function was loading before the html because I have another file where is a load() event for the js and I was supposed to call the function there. If the IIFE is removed. the ide warning disappears.

CodePudding user response:

Here is the working code

<!DOCTYPE html>
    <html>
       <head>
      <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
       </head>
       <body>
          <div >
             <div >
                <select  id="connType" 
                   name="connection_type">
                   <option selected>first op</option>
                   <option value="something">something</option>
                </select>
             </div>
             <div  style="display:none"> Show on change</div>
          </div>
          <script>
             $("#connType").change(function(){
                 if($(this).val() === "something"){
                     $(".mgconn").css("display","block");
                  }else{
                     $(".mgconn").css("display","none");
                  }
             });
          </script>
       </body>
    </html>
  • Related