0

I want to change the value of an element with JavaScript.

$("#mixui_title").val("very happy cow");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<span id="mixui_title">Angry cow sound?</span>

4
  • How are you triggering the change? Commented Nov 19, 2009 at 19:56
  • @Virat A trigger is not needed in this example. Commented Nov 19, 2009 at 22:52
  • Question headline could be better... Commented Nov 19, 2009 at 22:53
  • As noted by others and +1 by me, span has text, not value, inputs contain value (val), use .text instead. Commented Nov 19, 2009 at 23:05

4 Answers 4

3

Use the text method instead:

$("#mixui_title").text("very happy cow");
Sign up to request clarification or add additional context in comments.

Comments

2

Try html() function instead :

<span id="mixui_title">Angry cow sound?</span>

<script type="text/javascript">
$("#mixui_title").html("very happy cow");
</script>

1 Comment

Text might be more appropriate here. But then again, that might be slicing hairs.
1

2 Things:

1- Usualy, javascript is placed at the top of the page. If you do this in the future, you'll need to need to enclose it in the jQuery equivalent of document.ready:

 $(function() {
//  do stuff
 });

This tells jQuery to run the function as soon as the document is ready.

2- For any value between two opening/closing tags, you need to use the jQuery method .html("enter text to change") while the .val() method is used to change the value of any control with the attribute value="" like inputs:

<input type="submit value="This will be changed with val()" />

The following should work fine. Note its wrapped in $(function() { }); and is using the .html() property and is placed at the top of the page.

<script type="text/javascript">
$(function(){
    $("#mixui_title").html("very happy cow");
});
</script>

<span id="mixui_title">Angry cow sound?</span>

2 Comments

Actually, for performance reasons JavaScript should be placed at the bottom of the page. See: developer.yahoo.com/performance/rules.html#js_bottom
JavaScript should typically be placed at the bottom of the page to increase page render times. See: developer.yahoo.com/performance/rules.html#js_bottom
-1

It's not enclosed by the

$(document).ready(function(){ 
   //your code goes here 
});

1 Comment

not needed if the script is placed after the element in the page, like submitters example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.