0

So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).

Here is my code:

var ingrCount = 0

$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);

var ingrClose = $("<button>");

ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");

// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);

// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);

// Clear the textbox when done
$("#ingredients").val("");

// Add to the ingredient list
ingrCount++;

if (ingredientInput === "") {

}
});

So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.

2 Answers 2

2

If you're testing if ingredientInput is empty, can you just return from within the click event?

$("#addIngrButton").on('click', function() {
  var ingredientInput = $("#ingredients").val().trim();
  if(ingredientInput === '') { return; }
  // rest of code
Sign up to request clarification or add additional context in comments.

1 Comment

That worked! I just decided to wrap an if statement around the action of the function to only fire when there is an input
0

Simply use :

$("#addIngrButton").on('click', function() {
    var ingredientInput = $("#ingredients").val().trim();
    if (ingredientInput.length == 0) {
        return false;
    }
    // ..... your code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.