Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline if else statements in jQuery

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!

like image 288
SkyeBoniwell Avatar asked Mar 28 '13 13:03

SkyeBoniwell


3 Answers

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>
like image 117
benams Avatar answered Nov 12 '22 02:11

benams


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 ===

like image 38
Manish Mishra Avatar answered Nov 12 '22 01:11

Manish Mishra


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 + '">';
like image 3
Niet the Dark Absol Avatar answered Nov 12 '22 02:11

Niet the Dark Absol