Musa Muaz
Musa Muaz

Reputation: 714

First time running but not working from 2nd time

I am working with a javascript function which works first time but not from the 2nd time.The console shows: Uncaught TypeError: pizza_name is not a function

My html is :

<div class="pizza_name_div">
    <input type="text" name="pizza_name" id="pizza_name" placeholder="Enter your pizza name as u like. i.e : my-pizza" value=""> 
    <input type="submit" value="Go" id="pizza_name_submit" onclick="pizza_name()">
</div>

And My js

function pizza_name() {
  if( pizza_name != "" ) {
     .........
  }else{
    alert( "please enter a name" );
  }
}

It shows alert properly for 1st time.But not form 2nd

Upvotes: 0

Views: 261

Answers (4)

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

Don't re-use names, you're probably overwriting your function to be a string instead.

(that's what I'm assuming happens in the code you didn't show since you're trying to test pizza_name as a string)

function pizza_name() {
    if( pizza_name != "" ) 

You'd be better off naming the function something like getPizzaName. Name the function for what it does, not what it returns.

Upvotes: 0

SVK
SVK

Reputation: 2197

Link
js code:

   function pizza_name() {
    var pizzaName=document.getElementById("pizza_name").value;
  if(!pizzaName ) {
   alert("no value");
  }else{
    alert( "please enter a name" );
  }
}

Upvotes: 2

Farhan
Farhan

Reputation: 1483

You can use jquery for this too

HTML

<div class="pizza_name_div">
    <input type="text" name="pizza_name" id="pizza_name" placeholder="Enter your pizza name as u like. i.e : my-pizza" value=""> 
    <input type="submit" value="Go" id="pizza_name_submit" >
</div>

JQUERY

$(document).ready(function(){
$("#pizza_name_submit").on("click", function(){
if( $("#pizza_name").val()) {
    alert( $("#pizza_name").val());
  }else{
    alert("enter value");
  }
});
});

demo

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

Change your code with:

function pizza_name() {
  var pizzaName = document.getElementById('pizza_name').value;
  if(pizzaName != "") {
     //.........
  } else {
    alert( "please enter a name" );
  }
}

It's very important to not assign any value to a possible pizza_name variable inside the function.

Upvotes: 1

Related Questions