user2035552 user2035552 - 1 month ago 8
HTML Question

Populating two separate input fields with unique text values passed in by multiple buttons using javascript

Working on a small personal project with jQuery and JavaScript. This is a one page app on a static website.

The game (if you can call it that) asks the user to select 2 characters from the selection area and pressing enter transfers the input to the "battle-area" where when you hit the "fight" button random numbers are subtracted form the characters hitpoints as attack dmg.

I am stuck on the selection part. I need two separate input fields populated with unique names. I am able to write text into the field and transfer it but I want the input fields to be populated by clicking on the individual pictures on the screen. My code seems to populate both fields at once. I can hardcode two buttons to each populate one input field, the problem is that I have about 15 image buttons and I need to be able to click either of those to populate the fields.

function selectFighter(name) {


var x = name;

var input = $('#fighter1_name').val();

$('#fighter1_name').val(x);

if ($('#fighter1_name').val() != "") {
$('#fighter2_name').val(x);
}
}


I have tried to add a condition that checks the first input field for a value and if it is NOT empty, to instead write the input into the second field. But that is causing one button click to populate both fields. I need one button click to populate one field, and then when I click another button to populate the other, empty field.

I am passing in a name with an onclick event: onclick="selectFighter('bob');"

Problem is when I click the image, both fields are populated with the same name. I want to be able to click an image to populate one input field, and then click a different image and put that name in the input field.

Answer Source

This should do the trick. We're checking if the first field has a value - if so, we populate the second one - otherwise the first one.

function selectFighter(name) {
  if ($('#fighter1_name').val()) {
    $('#fighter2_name').val(name);
  } else {
    $('#fighter1_name').val(name);
  }
}