Input field undefined

I am having strange error in javascript. I defined and input text field on a form and I am trying to test if the field is blank or not. But it is showing that the field is is undefined. I have through the script and I find what I have done wrong. below is the sample script in php.

I have the sample php script.
adokliAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
You need to show us your code for us to help you.
adokliAuthor Commented:
Iam assigning the input field DiscountText to variable DiscountTx and then display it. But it is saying undefined. below is the sample script.

I don't knowwhy the attachment file is not showing up. I will try to upload it again
SampleScript.php
Ray PaseurCommented:
Looks like your script is very out-of-date.  MySQL has been deprecated for several years and PHP is doing away with support for that extension.  Whatever else you do, get off the MySQL extension as soon as possible.  This article explains why you must do that, and what you must do to keep your scripts running in the future.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Ray PaseurCommented:
Stripped of all the irrelevant code, here is what the validateForm function is doing:

function ValidateForm()
{
   var DiscountTx = document.getElementsByName("DiscountText").value;
   alert("Display " +DiscountTx);
   return false;
}

Open in new window

Since it unconditionally returns FALSE, the form will not get submitted.
Ray PaseurCommented:
I cut this down a little bit to show how to get the information into a JavaScript variable.  Using getElementById() is a better practice because the Id is only on the client side.  The Name is both client side and server side, so it creates a tight coupling between the JavaScript and the PHP action script on the server.  Generally speaking we try to avoid tight couplings!  Also, the "Name" usage has been deprecated in HTML5, so it makes more sense to use the currently supported Id to make reference to the element.
http://www.w3schools.com/jsref/met_doc_getelementsbyname.asp

<?php // demo/temp_adokli_1.php

/**
 * http://www.experts-exchange.com/questions/28693528/Input-field-undefined.html
 */
error_reporting(E_ALL);
session_start();

?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />

<script>
function ValidateForm()
{
   var DiscountTx = document.getElementById("MyDiscountText").value;
   alert("Display " +DiscountTx);
}
</script>

<form id="ChargeForm" name="ChargeForm" method="post" action="" onsubmit="return ValidateForm(this)" >

<input type='text' id='MyDiscountText' name='DiscountText'>

<input type='submit' name='submit' value='Generate Sheet'>
<input type='reset' name='Reset' value='Reset'>

</form>

</body>
</html>

Open in new window

adokliAuthor Commented:
Hi Ray, I am a bit frustrated here. I tried using the getElementById() but it the forms will even submit at all. I changed it  and validating my quantity field as per the screen shot attached. I have also attached the full screen script. This is straight forward but I don't why it is working for one field not the others.
SampleScript-Message-Screen.png
Sample-Script-v2.txt
Ray PaseurCommented:
The best suggestion I can offer at this point is to deconstruct the problem into some things that are smaller and can be addressed and tested individually, then rebuild the application from the tested parts.  When we have a dependency on the database wired into the PHP and HTML we have a script that only you can run, and as a result I can't even test it at all.  In software development, there is a concept called the SSCCE.  The idea behind the SSCCE is to make questions atomic, complete, portable and repeatable.  

I'll try to do something with the new example script, but obviously its JavaScript issues will have to be considered separately from the PHP and SQL parts.
Ray PaseurCommented:
This article has some ideas about how to use checkboxes.  It's old, but mostly still useful.
http://www.experts-exchange.com/articles/5450/Common-Sense-Examples-Using-Checkboxes-with-HTML-JavaScript-and-PHP.html

You may want to validate more information than what this script captures, but it should provide something of a starting point.  I used jQuery to make it a bit easier to do the validation of the checkboxes.  Please post back if you still have questions.
http://iconoun.com/demo/temp_adokli_2.php
<?php // demo/temp_adokli_2.php

/**
 * http://www.experts-exchange.com/questions/28693528/Input-field-undefined.html
 */
error_reporting(E_ALL);

// SHOW THE POST REQUEST, IF ANY
if (!empty($_POST))
{
    echo '<pre>';
    var_dump($_POST);
    echo '</pre>';
}

?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
function ValidateForm()
{
    var numBox = $('.required:checked').length;
    if(numBox > 0)
    {
        alert(numBox + ' checkbox(s)');
    }
    else
    {
        alert('No checkbox input');
    }

    // var DiscountTx = document.getElementById("MyDiscountText").value;
    var DiscountTx = $("#MyDiscountText").val();
    alert("Discount: " +DiscountTx);

}
</script>

<form id="ChargeForm" name="ChargeForm" method="post" action="" onsubmit="return ValidateForm(this)" >

<input type="checkbox" class="required"    name="cBox[3]" value="Three" />
<input type="checkbox" class="required"    name="cBox[5]" value="Five"  />
<input type="checkbox" class="required"    name="cBox[7]" value="6 + 1" />

<input type="text"     id="MyDiscountText" name="DiscountText" placeholder="Discount" />

<input type="submit" value="Validate Inputs" />
</form>

</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
As has been pointed out by other experts in this thread there are several things wrong with the code posted - session_start called in multiple (incorrect) places, use of deprecated library.

However, to answer your question directly - why is the javascript query on your input element returning undefined the answer is this

document.getElementsByName returns a collection (note the use of the plural Elements) - this differs from the document.getElementById which returns the element.

Therefore you cannot access the .value member of the returned result as you are trying to get the value property from a collection of items with value properties.

You therefore need to change your code to do this
var DiscountTx = document.getElementsByName("DiscountText")[0].value;

Open in new window

Note the request for the zero'th element of the returned collection. To write this another way
var DiscountTx = document.getElementsByName("DiscountText");
alert("Display " +DiscountTx[0].value);

Open in new window

The above change should solve your undefined problem - but you need to address the other issues raised in this thread.

More info on the getElementsByName here http://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
Julian HansenCommented:
@Ray
Also, the "Name" usage has been deprecated in HTML5
This is partially true - from the W3 schools page
Note: In HTML5, the "name" attribute is deprecated and has been replaced by the "id" attribute for many elements.
The use of id instead of name for elements such as <a> where before # links went to name properties they now work on id's. However for <input> elements name is not only valid but necessary if you want your form variables to be posted to your server page

From http://www.w3schools.com/tags/att_input_name.asp
Note: Only form elements with a name attribute will have their values passed when submitting a form.
Slick812Commented:
greetings  adokli, , Your javascript seem to be a little UN-inspected by you. as you use the .getElementsByName() inconsistently -

document.getElementsByName("DiscountText").value
document.getElementsByName("DiscountTxt").focus();
document.getElementsByName("DiscountTxt").select();

you have "DiscountText" in the first and "DiscountTxt" in the next two.  Now PLEASE notice that the name as getElementsByName  is Plural "Elements", this does NOT return a single object , it returns an array, so you MUST use an array access -

document.getElementsByName("DiscountText")[0].value
document.getElementsByName("DiscountText")[0].focus();
document.getElementsByName("DiscountText")[0].select();

ALSO you really should use better Coding techniques, you call this -
    document.getElementsByName("DiscountText")
Three Times, when you only need to use it ONCE-
var arrayDis = document.getElementsByName('DiscountText');
if (arrayDis[0].value == ""){
      alert('Please enter a value for Discount');
      arrayDis[0].focus();
     arrayDis[0].select();
      return false;
   }

Open in new window


BUT, for me I try to use the document.getElementById( ) instead IF I only need a single ELEMENT, as this is a more accurate way to get a specific element, especially during develpment where I can add an remove things that may affect the getElementsByName( ) array return.
Slick812Commented:
@Julian  did not see you post, was eating lunch, seem to repeat you.
Julian HansenCommented:
@slick, np,
Ray PaseurCommented:
To clarify, the "Name usage" refers to getElementsByName(), whereas the "Id" usage refers to getElementById().  The tested-and-working code examples I posted earlier illustrate the preferred usage of getElementById() in this context.  It's preferred mainly because it works, where the original script did not.  The shorthand reference to "Name" is different from the input tag attribute name= which is used in the HTML document and carried into the server-side request as an array key.  If the JavaScript uses the id= attribute as a tool to identify an input, you have the freedom to change the name= attribute in the HTML and action script without needing a change in the JavaScript.  If the JavaScript uses any xxxByName() method, you've got tighter coupling than necessary, and while this is not necessarily an evil, tight coupling is a code smell that can be avoided.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.