views:

89

answers:

4

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

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


<script type="text/javascript">
$("#mixui_title").val("very happy cow");
</script>
+2  A: 

Try html() function instead :

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

<script type="text/javascript">
$("#mixui_title").html("very happy cow");
</script>
Canavar
Text might be more appropriate here. But then again, that might be slicing hairs.
Justin Johnson
+3  A: 

Use the text method instead:

$("#mixui_title").text("very happy cow");
kgiannakakis
A: 

It's not enclosed by the

$(document).ready(function(){ 
   //your code goes here 
});
Phillip Jacobs
not needed if the script is placed after the element in the page, like submitters example
Jason Harwig
+1  A: 

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>
Baddie
Actually, for performance reasons JavaScript should be placed at the bottom of the page. See: http://developer.yahoo.com/performance/rules.html#js_bottom
Josh Hinman
JavaScript should typically be placed at the bottom of the page to increase page render times. See: http://developer.yahoo.com/performance/rules.html#js_bottom
Justin Johnson
@Josh Hinman Well played
Justin Johnson