1

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!

doniyor
  • 31,751
  • 50
  • 146
  • 233
Kevin
  • 199
  • 1
  • 7
  • 19

4 Answers4

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.

RobG
  • 124,520
  • 28
  • 153
  • 188
2

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

alert("Value: " + document.getElementsByName('DateStart')[0].value);
Amir Popovich
  • 26,624
  • 8
  • 44
  • 88
2

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);
Community
  • 1
  • 1
Nipuna
  • 5,638
  • 8
  • 55
  • 84
1

You can say like bellow

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

if this is first element which has class inputPanel.

Mritunjay
  • 22,738
  • 6
  • 47
  • 66