MMMMS
MMMMS

Reputation: 2201

if condition not working while value is correct in jquery

I am just trying div text like placeholder text using below code,

$('#editabledrag').draggable()
                        .click(function(){
                            $(this).draggable({disabled:false });
                        })
      .dblclick(function(){
            $(this).draggable({disabled : true});

        var textval=$(this).text();
        alert(textval); 
          if(textval == "Drag or double click and type!." )
        {
                alert("if");
            $(this).text("");
            $(this).focus();

        }
       else
       {
           alert("else");
           $(this).focus();

       }

      $(this).blur(function(){
            var textval2 =$(this).text();

            //textval2 = textval2.length;
                alert(textval2);
                if (textval2 == "" ) {
                    alert( "if" );
                    $(this).text("Drag or double click and type!.");
                } 
                else {
                      alert( "else" );

                }

        });

      });

My jsp:

<div id="editabledrag" contenteditable="true" style="position: fixed;z-index:10000000">
Drag or double click and type!.
</div>

My fiddle : http://jsfiddle.net/Manivasagam/ux3k0t23/27/

I am getting div value correctly but my if condition not satisfying.

where i am wrong?

Upvotes: 0

Views: 50

Answers (3)

rack_nilesh
rack_nilesh

Reputation: 553

its because content in your div. Remove "new lines" in div and write it as

<div id="editabledrag" contenteditable="true" style="position: fixed;z-index:10000000">Drag or double click and type!.</div>

Upvotes: 1

Malitta N
Malitta N

Reputation: 3423

You can trim the string before you compare. Use textval.trim()

http://jsfiddle.net/ux3k0t23/28/

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

Your fetched text have line breaks in them. You need to remove the line breaks from fetched text before comparing the values in if condition:

if(textval.replace(/(\r\n|\n|\r)/gm,"")=="Drag or double click and type!."){
  //do something..
}

Working Demo

Upvotes: 1

Related Questions