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!

4 Answers 4

2

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

alert("Value: " + document.getElementsByName('DateStart')[0].value);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That's the 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.

1 Comment

Answers like this not only answers OPs question but also helps others to learn
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);

Comments

1

You can say like bellow

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

if this is first element which has class inputPanel.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.