windsurf88
windsurf88

Reputation: 109

Display only 1 image out of 3 images, function use?

Having difficulty with the function showResults () which generates the table. I would like to display 1 image from a choice of 3 images depending on if the key:value data has a 1 between "HasPDF", "HasMobile" or "apponly". SO I tried to use an if-then-else statement to sift through the 3 possibilities. Any advise? thank you. been going round and round..

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
table {
    margin: 3px;
}
table th {
    font-weight: bold;
    cursor: pointer;
}
table th, table td {
    padding: 3px;
    border: 1px solid #000;
}

</style>
<script>

var arr = [

    {
      "Inn_ID": "2292522",
      "Event_Name": "Jaguars ",
      "Event_Date": "2017-11-19 00:00:00",
      "ticket_total": "76.0",
      "HasPDF": "1",
      "HasMobile": "0",
      "apponly": "0"
    },
    {
      "Inn_ID": "2292523",
      "Event_Name": "Pelicans",
      "Event_Date": "2018-01-16 00:00:00",
      "ticket_total": "50.0",
      "HasPDF": "0",
      "HasMobile": "1",
      "apponly": "0"
    },
    {
      "Inn_ID": "2292524",
      "Event_Name": "Owls",
      "Event_Date": "2018-01-16 00:00:00",
      "ticket_total": "60.0",
      "HasPDF": "0",
      "HasMobile": "0",
      "apponly": "1"
    }

];

$(function() {
    $('#headings th').click(function() {
        var id = $(this).attr('id');
        var asc = (!$(this).attr('asc')); // switch the order, true if not set

        // set asc="asc" when sorted in ascending order
        $('#headings th').each(function() {
            $(this).removeAttr('asc');
        });
        if (asc) $(this).attr('asc', 'asc');

        sortResults(id, asc);
    });

    showResults();
});

function sortResults(prop, asc) {
    arr = arr.sort(function(a, b) {
        if (asc) return (a[prop] > b[prop]);
        else return (b[prop] > a[prop]);
    });
    showResults();
}

function image(thisImg) {
    var img = document.createElement("IMG");
    img.src = thisImg;
    document.getElementById('imageDiv').appendChild(img);
}

function showResults () {
    var html = '';
    for (var e in arr) {
        html += '<tr>'
            +'<td>'+arr[e].Event_Date+'</td>'
            +'<td><a href="https://www.thexx.com/orders/view-invoice/'+arr[e].Inn_ID+'" target="_blank">'+arr[e].Inn_ID+' </a></td>'
            +'<td>'+arr[e].ticket_total+'</td>'
            +'<td>'+if (arr[e].HasPDF == "1") {
                       image('pdf.png');
                        } else if (arr[e].HasMobile == "1"){
                        image('mobile.jpeg');
                        } else {image('link.png');} 
                        +'<div id="imageDiv" style="width=20"></div></td>'
        +'</tr>';
    }
    $('#results').html(html);
}

</script>

</head>

<body>

Click on the table headings to sort the results.
<table>
    <thead id="headings">
        <tr>
            <th id="Event_Date">Event Date</th>
            <th id="Inn_ID">Inn ID</th>
            <th id="ticket_total">Amount</th>
            <th id="order">Order Type</th>

        </tr>
    </thead>
    <tbody id="results">
        <!-- this will be auto-populated -->
    </tbody>
</table>



</body>

</html>

Upvotes: 0

Views: 616

Answers (3)

Michel Engelen
Michel Engelen

Reputation: 573

I have a rewritten your function since there were some caveats which could cause your code to crash. I will explain them later, but first the code:

function showResults(arr) {
  var html = '';

  for (var i = 0; i < arr.length; i++) {
    var image = arr[i].hasPDF ? 'pdf.png' : (arr[i].hasMobile ? 'mobile.jpeg' : 'link.png');

    html += '<tr>';
    html +=   '<td>' + arr[i].Event_Date + '</td>';
    html +=   '<td>';
    html +=     '<a href="https://www.aceticket.com/orders/view-invoice/' + arr[i].Invoice_ID + '" target="_blank">';
    html +=       arr[i].Invoice_ID;
    html +=     '</a>';
    html *=   '</td>';
    html +=   '<td>';
    html +=     arr[i].ticket_total;
    html +=   '</td>';
    html +=   '<td>';
    html +=     '<div id="imageDiv" style="width=20">';
    html +=       '<img src="' + image + '" />';
    html +=     '</div>';
    html +=   '</td>';
    html += '</tr>';

  }

  $('#results').html(html);
}

First thing I did was structuring the HTML for better readability, just like you would with plain HTML. Luckily JavaScript is very "white-space-friendly" which makes this possible.

Second thing I did was ditching the image() function. This function was mixing document methods with HTML string creation. That was the cause your code was not running as expected.

It was (knid of) a race condition. Let me explain it like this:

  1. You create a String containing HTMLmarkup.
  2. In the midst of creating it you tried to append the image tag from the image() function to a div (also this div was only existent inside the string and even after the image() function was called.)
  3. with the html() function from jQuery you finally create the DOM from the markup you created inside the string.

Your approach was not entirely false, but had some downsides to it. After the third step you could have accessed the DOM to append() something to it.

An alternative to the image() function was simply to create an img tag inside your string as well and pass it a variable which holds the image filename. I did this with a nested ternary operator to save some space.

I hope you like my solution to your problem and if I can be of any help please comment! ;)

Upvotes: 2

Aniruddha Gohad
Aniruddha Gohad

Reputation: 253

Your image function does not return anything and you are appending to a div (#imageDiv) that does not currently exist on the DOM. You are also assigning the same id (#imageDiv) to multiple divs.

you would want to try this :

 function image(thisImg) {
    var img = document.createElement("IMG");
    img.src = thisImg;
    return img;
}

and

 function showResults () {
   var html = '';
   for (var e in arr) {
    html += '<tr>'
        +'<td>'+arr[e].Event_Date+'</td>'
        +'<td><a href="https://www.aceticket.com/orders/view-invoice/'+arr[e].Invoice_ID+'" target="_blank">'+arr[e].Invoice_ID+' </a></td>'
        +'<td>'+arr[e].ticket_total+'</td>'
        +'<td>'+if (arr[e].HasPDF == "1") {
                   '<div id="imageDiv" style="width=20">'+ image('pdf.png');+'</div></td>'
                  } else if (arr[e].HasMobile == "1"){
                   '<div id="imageDiv" style="width=20">'+ image('mobile.jpeg');+'</div></td>'
                  } else {
                    '<div id="imageDiv" style="width=20">'+ image('mobile.jpeg');+'</div></td>'
                  } 
        +'</tr>';
       }
       $('#results').html(html);
  }

Upvotes: 0

Harikant
Harikant

Reputation: 277

Use this search and image function here is running example https://plnkr.co/edit/3Sx3wnzFDFj4wKrv06qS?p=preview

function showResults () {
    var html = '';
    for(var e =0; e< arr.length; e++)
      {
        var x=""

        html += '<tr>'
            +'<td>'+arr[e].Event_Date+'</td>'
            +'<td><a href="https://www.aceticket.com/orders/view-invoice/'+arr[e].Invoice_ID+'" target="_blank">'+arr[e].Invoice_ID+' </a></td>'
            +'<td>'+arr[e].ticket_total+'</td>'
            +'<td><div id="imageDiv'+e +'" style="width=20"></div></td>'
        +'</tr>';
    }
    $('#results').html(html);
     for(var e =0; e< arr.length; e++)
     {
        if(arr[e].HasPDF == "1")
        {
          x='pdf.png';
         } 
         else if (arr[e].HasMobile == "1")
         {
                       x='mobile.jpeg';
        } 
        else
        {
          x='link.png';

        } 
         image(x ,e);
     }
}

function image(thisImg,e) {
    var img = document.createElement("IMG");
    img.src = thisImg;
    document.getElementById('imageDiv'+e).appendChild(img);
}

Upvotes: 0

Related Questions