Search code examples
javascripthtmlimagedictionaryarea

Fill in an input field through an image map area


I am making an application that fills in scores for a player that plays a game in real life. A spectator keeps track of his score by clicking on what he did hit in each turn. I came across two problems:

  • How do I fill in my input fields by clicking on an area.
  • How do I go from turn 1 to turn 2 etc.

The image is mapped in four sectors

This is the script: ( I had an alert('test'); on the ??? space, but that didn't work either. )

$("#test").on("click", function(e) {
  e.preventDefault();
  console.log("here");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="goal" src="http://pngimg.com/uploads/football_goal/football_goal_PNG24.png" usemap="#goal-map">

<map name="goal-map">
        <area id="test" href="#" alt="300 points" title="300" coords="483,50,584,146" shape="rect" />
        <area class="a" href="" alt="300 points" title="300" coords="110,49,11,145" shape="rect" />
        <area class="a" href="" alt="200 points" title="200" coords="13,148,110,238" shape="rect" />
        <area class="a" href="" alt="200 points" title="200" coords="484,149,584,237" shape="rect" />
    </map> 
    <br/>
    
This is the input field that needs to be filled:

<p>Turn 1:
  <input type="text" id="turn1"></p>
<p>Turn 2:
  <input type="text" id="turn2"></p>
<p>Turn 3:
  <input type="text" id="turn3"></p>


Solution

  • Almost there - you needed to jQuerify the target:

    var cnt = 0;
    $("#map").on("click", function(e) {
      e.preventDefault();
      cnt++;
      if (cnt > 3) {
        alert("You had your 3 gos");
      }  
      else {
        var $tgt = $(e.target);
        // console.log($tgt.attr("alt"));
        $("#turn"+cnt).val($tgt.attr("title"))
      }  
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img id="goal" src="http://pngimg.com/uploads/football_goal/football_goal_PNG24.png" usemap="#goal-map">
    
    <map name="goal-map" id="map">
            <area id="test" href="#" alt="300 points" title="300" coords="483,50,584,146" shape="rect" />
            <area class="a" href="" alt="300 points" title="300" coords="110,49,11,145" shape="rect" />
            <area class="a" href="" alt="200 points" title="200" coords="13,148,110,238" shape="rect" />
            <area class="a" href="" alt="200 points" title="200" coords="484,149,584,237" shape="rect" />
        </map> 
        <br/>
        
    This is the input field that needs to be filled:
    
    <p>Turn 1:
      <input type="text" id="turn1"></p>
    <p>Turn 2:
      <input type="text" id="turn2"></p>
    <p>Turn 3:
      <input type="text" id="turn3"></p>