0

I'm converting an input field to reqular text with this snippet.

$(".supernappula").live('click', function() {
   $('.item-quantity .simpleCart_input').replaceWith(function(){
   return '<span class='+this.className+'>'+this.value+'</span>'
   })    
});

However, if the value has already been changed from input to span, it will convert it to undefined and it shouldn't do it.

I was thinking a solution like this:

$(".supernappula").live('click', function() {
    var howmany = $('.item-quantity .simpleCart_input').html();
    if(howmany == "undefined"){return false;}
        $('.item-quantity .simpleCart_input').replaceWith(function(){
        return '<span class='+this.className+'>'+this.value+'</span>'
        });
});

But it doesn't actually do anything. So basically, how would I stop it from executing if it's already converted?

  • 2
    Doesn't answer your question but please stop using `.live()`. It's been deprecated for ages now. Use `.on()` (jQuery 1.7+) or `.delegate()` instead. – James Allardice Oct 08 '12 at 10:07
  • 1
    Here, it is asked before: [http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript][1] [1]: http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript – Mathlight Oct 08 '12 at 10:08
  • @JamesAllardice seems like people are giving me deprecated solutions then. What are the differences of .on() and .delegate()? –  Oct 08 '12 at 10:09
  • @ChristianNikkanen - They are just more effective methods for handling event delegation than `.live()` was. Have a look through the jQuery API docs for details. – James Allardice Oct 08 '12 at 10:10

2 Answers2

0

Encase your replace with a if condition

$(".supernappula").live('click', function() {
   if( $('.item-quantity .simpleCart_input').length){
      $('.item-quantity .simpleCart_input').replaceWith(function(){
         return '<span class='+this.className+'>'+this.value+'</span>'
      }) 
    }   
});

EDIT

Both the class names are assigned to the same input .. You are using the wrong selector..

Try this $('.item-quantity.simpleCart_input')

UPDATED FIDDLE

What $('.item-quantity .simpleCart_input') means is that .simpleCart_input is a child of .item-quantity which is wrong in your case ..

Both classes are associated to the same element .. So your selector should not have any spaces between them..

Community
  • 1
  • 1
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • Thanks, it works, though I created a workaround and moved the snippet to my ajax call. –  Oct 08 '12 at 10:24
0

You element must have at least a white space inside. So you can do the verification with something like this:

if($.trim($(".item-quantity .simpleCart_input").html()) == ""){return false;} ...

rjmateus
  • 26
  • 3