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
  • 36,596
  • 57
  • 175
  • 260
Kevin
  • 229
  • 2
  • 10
  • 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
  • 142,382
  • 31
  • 172
  • 209
2

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

alert("Value: " + document.getElementsByName('DateStart')[0].value);
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
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
  • 6,846
  • 9
  • 64
  • 87
1

You can say like bellow

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

if this is first element which has class inputPanel.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68