Get value of Span Text

JavascriptHtml

Javascript Problem Overview


I have a span with class="span" and a hidden field class="dropdown".

The span text changes, and I need to grab the text and set it as the value of the hidden field's value.

I will then use php (I already have) and use the name of the hidden field to email me the text.

How do I do it?

Javascript Solutions


Solution 1 - Javascript

<script type="text/javascript">
document.getElementById('button1').onChange = function () {
    document.getElementById('hidden_field_id').value = document.getElementById('span_id').innerHTML;
}
</script>

Solution 2 - Javascript

var span_Text = document.getElementById("span_Id").innerText;

console.log(span_Text)

<span id="span_Id">I am the Text </span>

Solution 3 - Javascript

The accepted answer is close... but no cigar!

Use textContent instead of innerHTML if you strictly want a string to be returned to you.

innerHTML can have the side effect of giving you a node element if there's other dom elements in there. textContent will guard against this possibility.

Solution 4 - Javascript

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

Solution 5 - Javascript

Judging by your other post: https://stackoverflow.com/questions/10343376/how-to-get-the-inner-text-of-a-span-in-php. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).

As for the correct approach to grabbing the span text from the client I recommend Johns answer.

These are a good place to get started.

JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript

PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php

Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHunter MitchellView Question on Stackoverflow
Solution 1 - JavascriptJohn CondeView Answer on Stackoverflow
Solution 2 - JavascriptmaxspanView Answer on Stackoverflow
Solution 3 - Javascriptwle8300View Answer on Stackoverflow
Solution 4 - JavascriptVishal ThakurView Answer on Stackoverflow
Solution 5 - JavascriptJackView Answer on Stackoverflow