input string in javascript

12,566

Solution 1

Assuming you have one input with the name DateStart(use id's):

alert("Value: " + document.getElementsByName('DateStart')[0].value);

Solution 2

If the input is in a form, and there is only one form in the document, you can access it like:

alert(document.forms[0].DateStart.value);

If the form has a name you can use:

alert(document.forms['formName'].DateStart.value);

or if you like being long–winded:

alert(document.forms['formName'].elements['DateStart'].value);

or if the name is also a valid identifier (i.e. a name you could also use as a variable name)

alert(document.forms.formName.DateStart.value);

or even:

alert(document.formName.DateStart.value);

Or an ID:

alert(document.getElementById('formId').DateStart.value);

Or using the querySelector interface:

alert(document.querySelector('input[name="DateStart"]').value);

Lots of ways to skin that cat.

Solution 3

From the current code you can use getElementsByName

var dateStart = document.getElementsByName('DateStart')[0];
alert("Value: " + dateStart.value);

But it's advisable and a best practice to add Id attribute on DOM element and using getElementById in JavaScript to retrieve DOM element. (take a look at name vs id)

HTML

<input id="DateStart" name="DateStart" class="inputPanel" type="text" size="20" maxlength="20" value="2013-10-20">

JavaScript

var dateStart = document.getElementById('DateStart');
alert("Value: " + dateStart.value);

Solution 4

You can say like bellow

alert(document.getElementsByClassName('inputPanel')[0].value); 

if this is first element which has class inputPanel.

Share:
12,566
Kevin
Author by

Kevin

Updated on June 04, 2022

Comments

  • Kevin
    Kevin almost 2 years

    Short question

    QUESTION

    How can I access the string value "2013-10-20" from the input in HTML to show it in JavaScript?

    HTML

    <input name="DateStart" class="inputPanel" type="text" size="20" maxlength="20" value="2013-10-20">
    

    JAVASCRIPT

    <script javascript="javascript" type="text/javascript">
        alert("Value: " + ???)
    </script>
    

    Thanks!

  • Kevin
    Kevin over 9 years
    Thank you! That's the solution.
  • Nipuna
    Nipuna over 9 years
    Answers like this not only answers OPs question but also helps others to learn