user4496109
user4496109

Reputation:

Changing text using ID in jQuery

I want to change the text of a line of text in a <b> tag using jQuery but it doesn't seem to work.

var status = false;

function updateStatus{$(document).ready(function(){
	if (status == false){
		$('#status').text('Text');
		$('#status').css("color","green");}
	if (status == true){
		$('#status').text('Text');
		$('#status').css("color","red");}
})}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/status.js"></script>

<b id="status"></b>

Upvotes: 1

Views: 64

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107528

You are not using the jQuery library quite like it was intended. You have a document-ready callback handler being defined inside of a function you're never calling, with some syntax errors sprinkled in. You should put the logic that modifies the text in its own separate function away from any event handlers, and then call that function when the document is ready. Try this instead:

    var status = false;
    
    function updateStatus() { // you were missing "()"
    	if (status == false) { // no need for two separate if-statements
    		$('#status').text('Text');
    		$('#status').css("color","green");
        } else {
    		$('#status').text('Text');
    		$('#status').css("color","red");
        }
    }

    // Define ready-handler
    $(document).ready(function() {
        // call your update function
        updateStatus();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b id="status"></b>

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Firstly, you're missing () in function declaration and secondly you're not calling the function.

Here's the error code:

function updateStatus{ //should be function updateStatus(){

While you may use like this:

var status = false;

function updateStatus(){//declare a function
    if (status == false){
        $('#status').text('Text');
        $('#status').css("color","green");
    }
    if (status == true){
        $('#status').text('Text');
        $('#status').css("color","red");}
    }
}

$(document).ready(function(){
    updateStatus();//call the function when DOM is ready
});

Upvotes: 0

Related Questions