Can I use if else statement with onclick?

html if else tag
onclick if statement react
if else javascript
html conditional statements
onclick if else jquery
javascript program to find grade of a student using if else
javascript if onclick true
javascript else do nothing

I want to Sort array of objects by string property value. So if I click a button, the values will be sorted. But only the first if statement works. if I change the else if statement into the first if statement, it works but no matter what I do only the first if statement works. What should I change to make all three buttons work?

var members = [{
  name: "jar",
  join: "2017-2",
  sex: "f",
  age: "29"
}, {
  name: "hrk",
  join: "2017-8",
  sex: "f",
  age: "21"
}, {
  name: "jjk",
  join: "2014-6",
  sex: "m",
  age: "27"
}, {
  name: "jsh",
  join: "2016-5",
  sex: "m",
  age: "37"
}, {
  name: "kks",
  join: "2014-4",
  sex: "f",
  age: "42"
}];
var list = "";


function func() {
  for (var i = 0; i < members.length; i++) {
    var val = document.getElementById('form').ans.value;

    if (members[i].join >= val || members[i].name == val || members[i].sex == val || members[i].age == val) {

      for (var key in members[i]) {
        if (key === "name" || key === "join" || key === "sex") {

          if (document.getElementById("namebtn").onclick) {
            var namesort = function(a, b) {
              if (a.name > b.name) {
                return 1;
              } else if (a.name < b.name) {
                return -1;
              }
              return 0;
            }
            members.sort(namesort);
          } else if (document.getElementById("joinbtn").onclick) {
            var joinsort = function(a, b) {
              if (a.join > b.join) {
                return 1;
              } else if (a.join < b.join) {
                return -1;
              }
              return 0;
            }
            members.sort(joinsort);
          } else if (document.getElementById("joinbtn").onclick) {
            var agesort = function(a, b) {
              if (a.age > b.age) {
                return 1;
              } else if (a.age < b.age) {
                return -1;
              }
              return 0;
            }
            members.sort(agesort);
          }
          br = " ";
        } else {
          br = "<br>";
        }
        list += members[i][key] + br;

      }
    }
  }
  document.getElementById("title").innerHTML = title;
  document.getElementById("who").innerHTML = list;
  return false;
}
<p id="title"></p>
<p id="who"></p>
<form action="#" id="form">
  <input type="text" name="ans" placeholder="year">
  <input type="submit" value="search" id="sub">
</form>
<br>
<input type="submit" onclick="func()" id="namebtn">
<input type="submit" onclick="func()" id="joinbtn">
<input type="submit" onclick="func()" id="agebtn">

if (document.getElementById('namebtn').onclick) will always be true since the attribute is truthy.

Are you trying to check which button was clicked? If that's the case, your func should probably have an id or event parameter (function func(btnId or e) { ... }) and then pass this.id to func:

<input type="submit" onclick="func(this.id or event)" id="namebtn">

Simple if else onclick then do?, You should use onclick method because the function run once when the page is loaded and no button will be clicked then. So you have to add an even which  My code is not yet complete. My problem is, that I can't put an OnClickListener inside an IF Statement. I need to randomize the questions so I put random generator then use if statements to present the question that is given by the random number. I use for loop so that the game will not end until all the games have been played. Here's my code in my

Rather than checking document.getElementById("elementid").onclick, you can find the target of the current click event. Look this example.

var members = [{name: "jar",join: "2017-2",sex: "f",age: "29"}, 
               {name: "hrk",join: "2017-8",sex: "f",age: "21"},
               {name: "jjk",join: "2014-6",sex: "m",age: "27"},
               {name: "jsh",join: "2016-5",sex: "m",age: "37"},
               {name: "kks",join: "2014-4",sex: "f",age: "42"}];
var list = "";


function func(e) {
    for (var i = 0; i < members.length; i++) {
        var val = document.getElementById('form').ans.value;
        if (members[i].join >= val || members[i].name == val || members[i].sex == val || members[i].age == val) {

            for (var key in members[i]) {
                if (key === "name" || key === "join" || key === "sex") {

                    if (e.currentTarget.id == "namebtn") {
                        var namesort = function (a, b) {
                            if (a.name > b.name) {
                                return 1;
                            } else if (a.name < b.name) {
                                return -1;
                            }
                            return 0;
                        }
                        members.sort(namesort);
                    } else if (e.currentTarget.id == "joinbtn") {
                        var joinsort = function (a, b) {
                            if ((new Date(a.join)).getTime() > (new Date(b.join)).getTime()) {
                                return 1;
                            } else if ((new Date(a.join)).getTime() < (new Date(b.join)).getTime()) {
                                return -1;
                            }
                            return 0;
                        }
                        members.sort(joinsort);
                    } else if (e.currentTarget.id == "agebtn") {
                        var agesort = function (a, b) {
                            if (parseInt(a.age) > parseInt(b.age)) {
                                return 1;
                            } else if (parseInt(a.age) < parseInt(b.age)) {
                                return -1;
                            }
                            return 0;
                        }
                        members.sort(agesort);
                    }
                    br = " ";
                } else {
                    br = "<br>";
                }
                list += members[i][key] + br;

            }
        }
    }
    document.getElementById("title").innerHTML = title;
    document.getElementById("who").innerHTML = list;
    return false;
}
<p id="title"></p>
<p id="who"></p>
<form action="#" id="form">
    <input type="text" name="ans" placeholder="year">
    <input type="submit" value="search" id="sub">
</form>
<br>
<input type="submit" onclick="func(event)" value="name" id="namebtn">
<input type="submit" onclick="func(event)" value="join" id="joinbtn">
<input type="submit" onclick="func(event)" value="age" id="agebtn">

JavaScript if/else Statement, If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different <img id="myImage" onclick="changeImage()" src="pic_bulboff​.gif"  Note that the above code will virtually always run the else case because the click event will not fire before execution reaches the if statement. While this answer may be technically correct, you should make sure that you understand the broader concept of event driven programming. – jncraton Jul 8 '11 at 19:21

You can separate the logic by defining the sort functions outside of func function, attach event handlers to each element using .addEventListener() or .onclick. Call func() within an event handler attached to the element. Use var to define variables, specifically br and list

var members = [{
  name: "jar",
  join: "2017-2",
  sex: "f",
  age: "29"
}, {
  name: "hrk",
  join: "2017-8",
  sex: "f",
  age: "21"
}, {
  name: "jjk",
  join: "2014-6",
  sex: "m",
  age: "27"
}, {
  name: "jsh",
  join: "2016-5",
  sex: "m",
  age: "37"
}, {
  name: "kks",
  join: "2014-4",
  sex: "f",
  age: "42"
}];

var namesort = function(a, b) {
  if (a.name > b.name) {
    return 1;
  } else if (a.name < b.name) {
    return -1;
  }
  return 0;
}

var joinsort = function(a, b) {
  if (a.join > b.join) {
    return 1;
  } else if (a.join < b.join) {
    return -1;
  }
  return 0;
}

var agesort = function(a, b) {
  if (a.age > b.age) {
    return 1;
  } else if (a.age < b.age) {
    return -1;
  }
  return 0;
}

document.getElementById("joinbtn").onclick = function() {
  members.sort(joinsort);
  func();
};

document.getElementById("agebtn").onclick = function() {
  members.sort(agesort);
  func();
}

document.getElementById("namebtn").onclick = function() {
  members.sort(namesort);
  func();
};

function func() {
  var br = "";
  var list = "";
  for (var i = 0; i < members.length; i++) {
    var val = document.getElementById('form').ans.value;

    if (members[i].join >= val || members[i].name == val || members[i].sex == val || members[i].age == val) {

      for (var key in members[i]) {
        if (key === "name" || key === "join" || key === "sex") {
          br = " ";
        } else {
          br = "<br>";
        }
        list += members[i][key] + br;

      }
    }
  }
  // document.getElementById("title").innerHTML = title;
  document.getElementById("who").innerHTML = list;
  return false;
}
<p id="title"></p>
<p id="who"></p>
<form id="form">
  <input type="text" name="ans" placeholder="year">
  <input type="button" value="search" id="sub">
</form>
<br>
<input type="button" id="namebtn" value="name">
<input type="button" id="joinbtn" value="join">
<input type="button" id="agebtn" value="age">

If statement in onclick event - PHP, Well, then that means $qty_oak is always < 1 and you should find out why that is. There's no point in using a javascript confirm if the logic behind it is How do I get php to recognize that something was put in the text box  Definition and Usage. The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

How To Write Conditional Statements in JavaScript, How do you check whether a button is clicked or not in JavaScript? But only the first if statement works. if I change the else if statement into the first if statement. Because onclick value is not falsey and else is unlikely to be executed. What should I change to make all three buttons work? You can simplify by passing the property by which sorting should happen, here is a demo of the same

But only the first if statement works. if I change the else if statement into the first if statement

Because onclick value is not falsey and else is unlikely to be executed.

What should I change to make all three buttons work?

You can simplify by passing the property by which sorting should happen, here is a demo of the same

var members = [
    { name: "jar", join: "2017-2", sex: "f", age: "29" },
    { name: "hrk", join: "2017-8", sex: "f", age: "21" },
    { name: "jjk", join: "2014-6", sex: "m", age: "27" },
    { name: "jsh", join: "2016-5", sex: "m", age: "37" },
    { name: "kks", join: "2014-4", sex: "f", age: "42" }
];

var list = "";

function func( prop ) 
{
  sortObjByProp(members, prop);
  list = members.map( function( memberObj ){  
     return Object.keys( memberObj ).map( function( key ){
        return "<span class='cell'>" + memberObj[ key ] + "</span>";
     }).join( "  " );
  }).join( "<br>" );
  
  document.getElementById("who").innerHTML = list;
  return false;
}

function sortObjByProp(obj, prop) 
{
  obj.sort(function(a, b) {
     return a[prop].localeCompare(b[prop]); //will work for numerics like age if the number of digits are same for all ages.
  });
}
.cell
{
   display :inline-block;
   width: 80px;
}
<p id="who"></p>
<form action="#" id="form">
  <input type="text" name="ans" placeholder="year">
  <input type="submit" value="search" id="sub">
</form>
<br>
<input type="submit" onclick="func('name')" id="namebtn" value="sort by name">
<input type="submit" onclick="func('join')" id="joinbtn" value="sort by join">
<input type="submit" onclick="func('age')" id="agebtn" value="sort by age">

elseif/else if - Manual, Use the optional else clause to execute another group of statements. name="​text1" value=" " /> <input type="button" value="Marks check" onclick='marksgrade​()' /> </form> <script For multiple conditions, we can use else if. In this video I create two IF statements to handle each of the two buttons and compare them with the parameter in the OnClick() method. This video is part of a series on Android Development.

JavaScript if else statements, onclick and if else. Hi,. Still quite a lot of work to do to finish this off, however Ive come Ive put a note in the code next to the if statement. You can't write your code inline for the OnClick property, it has to be the name of a method on the page. Here is an example: Protected Sub btnTest_Click(sender As [Object], e As EventArgs) If Something = somethingElse Then 'do something Else 'do something else End If 'or like the others said just put this in. Response.Redirect(WTSRadioList1.Selectedvalue) End Sub

onclick and if else, The variable I am trying to use to check for value is set. var unitPurpose = document.getElementById('q67_unitPurpose');. Then I check if that  Annnd, it works fine up until the 4th item. Then it starts printing out 2, and 3, and then if I try to print out 5 it goes crazy and prints out a hundred iterations of all the other print statements. I tried doing this with an if statement, 3 else if statements, and an else statement with the same result.

Javascript if/else with onClick event ?, Then you can use javascript to hide all of the tabs and unhide the one that should show. function hideTabs() { [document.querySelectorAll('.tab')].map(function(  When using ifelse if..else statements, there are few points to keep in mind − An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Syntax. The syntax of an if

Comments
  • Can you indent your code properly? It is hard to read right now.
  • What do you expect that if( document.getElementById("namebtn").onclick ) would check?
  • if (document.getElementById("joinbtn").onclick) {...} else if (document.getElementById("joinbtn").onclick) {...} Code inside this else if will never be reached.
  • Where is title defined?
  • I erased title in the snippet because it is written in another language.
  • Is it just me or 2nd and 3rd conditions are same?
  • @Rajesh not just you, 3rd condition will never be reached, I pointed that out in a comment to OP.
  • It should be agebtn. Seems like a typo
  • Yes, it is. I have corrected that typo. Also, you can use some better comparison methods for date and age. I have updated that in my code.
  • "Try to use better naming conventions. func is a bad function name. A function name should denote its purpose." How are "naming conventions" and "bad function name" related to the Question? While you were busy editing this users' Answer you could have removed opinion irrelevant to the actual Question from your own Answer.
  • Hey, lets take it easy. I tried to give few suggestions that in my POV were apt. If anything is wrong with them, please highlight it.
  • The last bullet point at your Answer is entirely opinion wholly unrelated to the Question. You must be aware of that fact.
  • @guest271314 Giving helpful advice on question code is encouraged. See this meta topic.
  • @ModusTollens Have no concern for what is "encouraged" at meta. Meta has a culture onto itself. Why do you consider the "advice" "helpful"? func being used as a function name is not an issue at this Question nor any other Question. There is no review guild for function names being used in code, perhaps at codereview, not at SO. There is pseudo code abound in both questions and answers at SO.