7

I have a jQuery function that is executed by two different buttons.

$("#btnSearch, #btnDirectorSearch").click(function () {

Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:

var div = $(this).data("str");

And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?

if div = "choice1" {
    html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';

} else {
    html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}

That seems cumbersome and I'm hoping there is a better jQuery way of doing this.

Thanks!

Jai
  • 74,255
  • 12
  • 74
  • 103
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

4 Answers4

29

you have a syntax error

if div = "choice1" 

should be

if (div == "choice1")

Anyway, the pattern you're looking for is:

div == "choice1" ? <code for true> : <code for false>
Ian
  • 50,146
  • 13
  • 101
  • 111
benams
  • 4,308
  • 9
  • 32
  • 74
3

you can use condition ? code when true: code when false

but i would suggest you to stick with curley braces only, as it looks better and easier to debug. one more thing , do it as below

if(div==="choice1"){

}
else{
}

use ===

Community
  • 1
  • 1
Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
  • I don't know - I think inline is nicer on the eye and for value assignment much quicker to read and understand. Seems more intuitive to me anyway. – Dave Lawrence May 03 '17 at 08:43
2

Since it's only the number that changes in the output, you could do this:

var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

If your choices are limited, you could add a small lookup array:

var choices = {
    choice1: {
        str: "str1",
        data: "dataItem1"
    },
    choice2: { ... }
};

html += '<tr data-str="' + choices[div].str 
    + '" data-dataItem="' + choices[div].data
    + '" data-result-title="' + name + ... etc;
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309