Is there a way to append the value of a javascript variable to a label without using jquery?
Eg:
Var global_message = "1234";
<label id="my-label">Test</label>
I want the value Test1234 to be displayed on the browser.
I dont want to write a jquery to say
$("#my-label").val() = $("#my-label").val()+global_message
Is there a way to append the value of a javascript variable to a label without using jquery?
Eg:
Var global_message = "1234";
<label id="my-label">Test</label>
I want the value Test1234 to be displayed on the browser.
I dont want to write a jquery to say
$("#my-label").val() = $("#my-label").val()+global_message
Share
Improve this question
asked Jan 24, 2017 at 7:07
jothijothi
3721 gold badge5 silver badges16 bronze badges
2
- The title says "without script"? You can't get a value of JS variable without a script. What is the real point here? – Teemu Commented Jan 24, 2017 at 7:12
-
Are you asking for
document.getElementById('my-label').innerHTML += global_message
– mseifert Commented Jan 24, 2017 at 7:13
3 Answers
Reset to default 2What I understand from your question is that you want to access JavaScript variable directly in HTML and don't want to use any JavaScript/jQuery code.
But, You can not access JavaScript variable outside <Script>
tag.
HTML does not recognise any variable.
So you can use @WitVault answer if you want to use JavaScript and @Pranav C Balan using jQuery
var global_message = "1234";
document.getElementById("my-label").innerText += global_message;
<label id="my-label">Test</label>
The val()
method is using to update the form elements value so it can't be used for updating text content of the label.
For updating label
text use text()
method with a callback function, where the second argument in callback holds the old text.
$("#my-label").text(function(i, oldText){
return oldText + global_message;
})
var global_message = "1234";
$("#my-label").text(function(i, value) {
return value + global_message;
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="my-label">Test</label>