简体   繁体   中英

How to Populate Multiple Form Fields from onClick of Multiple EJS Data Fields

I apologize if this is answered elsewhere, please point me in that direction.

From a dynamically populated list, I've figured out how to click one item in the list and have that text go to my form input.

My ejs code...

 <% for(var i=0; i<BeerList.length; i++) {%>
    <div>
      <a onclick="document.getElementById('beerName').value='<%= BeerList[i].beer.beer_name %>'" >
        <span><%= BeerList[i].beer.beer_name %></span>
      </a>
    </div>
 <% } %>

...will show a list of beer names...

Raspy Angel Bourbon Stout

MEOWSA!

Vă-da

Magnanimous IPA

B-Bomb (2019)

And when I click on a beer name, that one name will populate my form input field.

Form code...

<form>
<input type="text" id="beerName" />
</form>

This works fine, but I can't figure out how to add a separate piece of data to a separate form input. For example, if I want to include the Brewery Name in addition to the Beer Name, I try something like this...

 <% for(var i=0; i<BeerList.length; i++) {%>
    <div>
      <a onclick="document.getElementById('beerName').value='<%= BeerList[i].beer.beer_name %>'" >
        <span><%= BeerList[i].beer.beer_name %></span>
        <span><%= BeerList[i].brewery.brewery_name %></span>
      </a>
    </div>
 <% } %>


<form>
   <input type="text" id="beerName" />
   <input type="text" id="breweryName" />
</form>

This obviously won't work as my onClick isn't even able to look for id=breweryName. If I give the form the id like form id="beerANDbrewery" , I don't know how to go about getting each item into the appropriate input field.

Thank you so much for any help you can provide!

You can make a function that handles both cases. The function should take as parameters the values you want.

<% for(var i=0; i<BeerList.length; i++) {%>
    <div>
        <a onclick="addText('<%= BeerList[i].beer.beer_name %>', '<%= BeerList[i].brewery.brewery_name %>') " >
        <span><%= BeerList[i].beer.beer_name %></span>
        <span><%= BeerList[i].brewery.brewery_name %></span>
       </a>
    </div>
<% } %>

<form>
   <input type="text" id="beerName" />
   <input type="text" id="breweryName" />
</form>


<script type="text/javascript">
    var addText = function(beerName, breweryName) {
        document.getElementById('beerName').value = beerName;
        document.getElementById('breweryName').value = breweryName;
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM