0

On a javascript homework assignment for my javascript class, the assignment requires a ".js" for loop iteration to list the names of the pets a user inputs (3 is the limit).

There are three horizontally spaced text-input boxes and regardless of what text boxes the user inputs pet names into, the "message" (id) output below the submit button will display pets' names inputted up to the limit imposed by the user (<= 3). Once the pets' names are inputted and submit button clicked, the page will display the pets' names starting from the left most text box the user has inputted in and going towards the right, until the user's chosen input limitation (<= 3) has reached its limit; therefore, if a user selects 2 as the limitation, only the left-most text boxes with pet names inputted will be displayed below the submit button.

So far I have tried referring to the pet id's and pet names as memberid ('pet' + 'cntr'), membername, and together in the for loop iteration they are given the id of members += membered + membername;

if (myNumPets == '' || myNumPets > 3) {
  $('numpets_error').innerHTML = " Please enter the number of
  pets you have ";
  myTruth = true;
} else {
  if (myNumPets < '4') {
    $('numpets_error').innerHTML = "";
    myTruth = false;
  }
}

if (myNumPets == 0) {
  myNumPetsEntered = 0;
} else {
  if (myNumPets == 1) {
    myNumPetsEntered = 1;
  } else {
    if (myNumPets == 2) {
      myNumPetsEntered = 2;
    } else {
      if (myNumPets == 3) {
        myNumPetsEntered = 3;
      }
    }
  }
}

cntr = '';

members = "";

for (cntr = 1; cntr <= myNumPetsEntered; cntr++) {
  var memberid = "pet" + cntr;
  console.log("MID " + memberid);
  var membername = $(memberid).value;

  members += memberid + membername;
}

$('message').innerHTML = members;

In this present code, when the number limitation is '1', only the first input box displays the inputted pet's name in the 'message' area below the submit button; however, I would like the inputted pet's name to appear there regardless of whether the inputted pet's name is in the first and left-most input box or one of the two that are to the right of it, and I want the same to be true of the other number limitations (2 and 3).

adiga
  • 34,372
  • 9
  • 61
  • 83

3 Answers3

0

In your for loop you're just blindly grabbing the value of N text inputs, where N = myNumPetsEntered.

If myNumPetsEntered == 1 and you've typed the pet's name into the second input box, the loop will never see that value. You'll want to do some validation to make sure you've actually grabbed a value.

I don't know how involved this homework assignment is, but you might also be interested in validating whether or not the number of text boxes with values is at least equal to (or greater than) the number of pets names the user said they were going to input.

You can also clean up those nested if statements - assuming you've got logic in place preventing myNumPets from being a negative value, you could just use:

if (myNumPets <= 3) {
  myNumPetsEntered = myNumPets;
}
ryanm
  • 451
  • 2
  • 7
0

Just an observation: This entire block is unnecessary. Why not just myNumPetsEntered = myNumPets? Or better yet, eliminate myNumPetsEntered altogether and use myNumPets in the loop?

if (myNumPets == 0) {
  myNumPetsEntered = 0;
} else {
  if (myNumPets == 1) {
    myNumPetsEntered = 1;
  } else {
    if (myNumPets == 2) {
      myNumPetsEntered = 2;
    } else {
      if (myNumPets == 3) {
        myNumPetsEntered = 3;
      }
    }
  }
}

Anyway. Here's one way to do it. Not sure it satisfies the requirements of your homework assignment, but then I shouldn't be doing your homework anyway.

function onButtonClick () {
  // get the pet name inputs
  const inputs = document.querySelectorAll('input[name=petname]');
  
  // get the max names value
  const max = document.querySelector('input[name=max]').value;
  
  const names =
    Array.from(inputs.values()) // convert the 'inputs' NodeList to an array
      .map(i => i.value.trim()) // extract the value of each input and strip white space
      .filter(Boolean) // filter out anything 'falsy' to eliminate empty values
      .slice(0, max); // chop off anything beyond the max number
    
  // string the values together, separated by a comma, and insert the result into the message box.
  document.getElementById('message').innerHTML = names.join(', ');
}
label, button {
  display: block;
}

input {
  margin: 1rem 0;
}
<div>
  <label>Number of Pets: <input type="number" min="1" max="3" name="max" value="3" /></label>
  
  <input name="petname" />
  <input name="petname" /> 
  <input name="petname" />
  <button onClick="onButtonClick()">Go.</button>
  <div id="message" />
</div>
ray
  • 26,557
  • 5
  • 28
  • 27
0

For a start, this chunk code can be cleaned up a lot. The current logic is messy. Just imagine if the limit was 8 instead of 3.

if (myNumPets == 0) {
  myNumPetsEntered = 0;
} else {
  if (myNumPets == 1) {
    myNumPetsEntered = 1;
  } else {
    if (myNumPets == 2) {
      myNumPetsEntered = 2;
    } else {
      if (myNumPets == 3) {
        myNumPetsEntered = 3;
      }
    }
  }
}

My suggestion is to change to a range like this:

if ((myNumPets >= 0) && (myNumPets <= 3)) {
  myNumPetsEntered = myNumPets;
}

To be honest, I am trying to make sense of the rest of the question. Think you are after something like the following:

var petCount = 0;
function petAdd(e) {
  // stop the default button function
  e.stopPropagation();
  e.preventDefault();
  // make sure only 3 pet names are entered.
  if (petCount >= 3) {
    alert("There is a max of 3 pet names");
    return;
  }
  // do we have a new pet name?
  var pet = document.getElementById("petNameInput");
  if ((pet.value) && (pet.value.trim())) {
    // we do have a name, add the name to the display
    var displayName = document.getElementById("petNameDisplay");
    // is it the first name?
    if (petCount == 0) {
      displayName.textContent = "My pet name(s) are: "+ pet.value.trim();
    } else {
      displayName.textContent += ", "+ pet.value.trim();
    }
    // keep track of the number of names
    petCount++;
    // clear the old name, ready for the next
    pet.value = "";
  }
  // have we reached 3 names yet? if so, remove the input
  if (petCount >= 3) {
    var petRow = document.getElementById("petNameRow");
    if (petRow) {
      petRow.style.display = "none";
    }
  }
}

// add the method call when the button is pressed
window.onload = function() {
  var d = document.getElementById("petAddButton");
  if (d) {
    d.addEventListener("click",petAdd,false);
  }
}
What are you pets' names? <i>max of 3</i><br />
<div id="petNameRow">
  <input type="text" id="petNameInput" placeholder="Enter a name here" /> 
  <button id="petAddButton">Add pet</button>
</div>
<div id="petNameDisplay"></div>
Tigger
  • 8,980
  • 5
  • 36
  • 40