0

I have this conditional function in jQuery, in order to show an specific message with it's own style when required:

function msg(type, text) {
    if (type="success"){
        $('.messageDisplay').attr('class', 'messageDisplay messages success');
        $('.messages').text(text);
        $('.messages').stop( true, false ).fadeIn(300).delay(2000).fadeOut(450);}
    else if (type="info"){
        $('.messageDisplay').attr('class', 'messageDisplay messages info');
        $('.messages').text(text);
        $('.messages').stop( true, false ).fadeIn(300).delay(2000).fadeOut(450);}
    else if (type="error"){
        $('.messageDisplay').attr('class', 'messageDisplay messages error');
        $('.messages').text(text);
        $('.messages').stop( true, false ).fadeIn(300).delay(2000).fadeOut(450);}
    else if (type="warning"){
        $('.messageDisplay').addClass('messages warning');
        $('.messages').text(text);
        $('.messages').stop( true, false ).fadeIn(300).delay(2000).fadeOut(450);}}

When call it, it only takes first condition, as the class that is always added to the messageDisplay div is 'messageDisplay messages info'. For example, on this case I am calling the "error" message type:

$('.tableContent').on('click', '.editIcon', function (e){
        if (editing==1){
            msg("error", "Acepta o anula la edición actual antes de editar otro registro");}

And even when it takes the right text, generates a success style message:

<div class="messageDisplay messages success">Acepta o anula la edición actual antes de editar otro registro</div>

After checking several times what could be causing this behaviour in jQuery, I am unable to find it and I'm almost sure no other jQuery's function is causing this. Is it something wrong on the conditional?

Biomehanika
  • 1,530
  • 1
  • 17
  • 45

2 Answers2

3
if (type="success"){

should be

if (type=="success"){

And so on for all

= means assignment not comparison 
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
1

Try

if (type.toString() === "success") {

.

or if you're sure about type being a string then

if (type === "success")

And the same for all your conditions.

You're using "=" operator, and that it's for assign, use "===" to be sure you're comparing same type (strings) besides the value.

At least you're 100% sure about "type" being a string better convert it with toString()

Also you could use toString() but there are some diff you may want to check, see this question for it: What's the difference between String(value) vs value.toString()

Note: About == and === take a look to this question: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Community
  • 1
  • 1
Allende
  • 1,480
  • 2
  • 22
  • 39