user3806613
user3806613

Reputation: 510

JavaScript: changing input value using JavaScript?

I'm trying to do a very simple task but for some reason I can't do it.

basically I am using the if statement to change the value of an input field using javascript but it doesn't work!

this is my code:

if (document.getElementById("colour").value == "171515"){
    document.getElementById("colour").value = "db0000";
}

if (document.getElementById("colour").value == "db0000"){
    document.getElementById("colour").value = "171515";
}

and the HTML looks like this:

<input type="text" id="colour" name="colour" class="colour" value="171515"/>

so what i need to do is this:

I launch a page and the input field is on my page with the value of value="171515", and then I press a button and that should change the value of the input field to value="db0000", and then I press the button again, and it should change the value of the input button to value="171515" and I need to do the same steps as many times as I want.

currently, it seems like it gets into a loop action and thats why it doesn't change the value of input field! (correct me if i'm wrong).

any help would be appreciated.

Thanks

EDIT:

The javascript code above is executed like so:

$(params.addPplTrigger).bind('click', function(e){
                    e.preventDefault();

///////// THE CODE ABOBE WILL GO HERE///////////

}

Upvotes: 0

Views: 82

Answers (2)

Shomz
Shomz

Reputation: 37711

You're just missing an else:

if (document.getElementById("colour").value == "171515"){
    document.getElementById("colour").value = "db0000";
}

else if (document.getElementById("colour").value == "db0000"){
    document.getElementById("colour").value = "171515";
}

What happens in your original code

Case 171515:

  • first if condition evaluates to true, because the value is 171515
  • value gets changed to db0000
  • second if condition evalutes to true again, because the value is db0000 now
  • value gets changed back to 171515

Case db0000:

  • first if condition gets evaluates to false, because the value is not 171515
  • the value remains the same
  • second if condition gets evaluates to true, because the value is db0000
  • value gets changed to 171515

So, in both cases you'd end up with 171515.

Upvotes: 1

Suchit kumar
Suchit kumar

Reputation: 11869

since you are doing :

if (document.getElementById("colour").value == "171515"){
    document.getElementById("colour").value = "db0000";
}

and then reverse

if (document.getElementById("colour").value == "db0000"){
    document.getElementById("colour").value = "171515";
}

so you are not able to see the change .use else instead of second if.

if (document.getElementById("colour").value == "171515"){
    document.getElementById("colour").value = "db0000";
}else{
    document.getElementById("colour").value = "171515";
}

Upvotes: 0

Related Questions