Javascript, if value is a certain text and checked, show image

1.1k views Asked by At

I'm trying to automate my ribbons for my GTA ONLINE crew website, and rather than having to hand-code; I create checkboxes with "ultimate-member" and then use javascript to check if a field is checked and display the image.

Here's what I have

<script>
    if (document.getElementsByName("platform").value === "Medal Of Honor" && document.getElementsByName("platform").checked ) { {
        document.getElementByID().innerHTML ='<img src="http://www.8492nd.org/img/awards/Medal-Of-Honor.png" alt="" />';
    }
 </script>
<h1>code beta</h1>
   <input type="checkbox" name="platform[]" value="Medal Of Honor" checked />Medal of Honor


<div id="awards-ribbons">
</div>    

I tried to put the code inside the div, and simply have it write the image out based on which boxes are checked. problem I ran into is that the input doesn't have an ID or Class attribute; and I cannot change it. If I could locate the PHP of "ultimate-member" I would add an id based on the value of checkbox. Then I could use the getElementById(id).checked and I'll be good to go.

4

There are 4 answers

0
Mike Hamilton On

Inside of your if statement, the document.getElementById() expression doesn't have an argument passed to it. You should pass to it the id of the element that you want to change.

document.getElementByID('idOfElement').innerHTML ='<img src="http://www.8492nd.org/img/awards/Medal-Of-Honor.png" alt="" />';
0
vinayakj On

p = document.getElementsByName("platform")[0];
    if (p.value === "Medal Of Honor" && p.checked ) { 
        document.getElementById('awards-ribbons').innerHTML ='<img src="http://www.8492nd.org/img/awards/Medal-Of-Honor.png" alt="" />';
    }
<h1>code beta</h1>
   <input type="checkbox" name="platform" value="Medal Of Honor" checked />Medal of Honor


<div id="awards-ribbons">
</div>

0
AmmarCSE On

You are almost there but 3 mistakes need to be corrected.

  1. getElementsByName returns a HTMLCollection, so you need to access specfic items by index
  2. getElementByID is incorrect, it needs to be getElementById (lower-case d at the end)
  3. You need to pass in the id when using getElementById

if (document.getElementsByName("platform")[0].value === "Medal Of Honor" && document.getElementsByName("platform")[0].checked ) { {
        document.getElementById("awards-ribbons").innerHTML ='<img src="" alt="" />';
    }
0
Joshua Price On

Thanks, I tried all of these but it didn't seem to work.

Here's the thing with "ultimate-member" they don't use IDs, it's strictly class. so I did try getting the element by class name and nothing.

Then I noticed the input checkboxes, do not have an ID or class assigned to them?

Is it possible to say:

"if checkbox checked and value = "medal of honor" --> show image"?

that seems to be the only way for it to work.