Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend jQuery's .val() method to non-input elements

I am writing a custom jquery plugin that basically replicates the functionality of an input. I could explain why, but truthfully the explanation is quite long and I believe it to be irrelevant to the question.

The trouble comes when I try to extend jQuery's .val() method to my custom jquery plugin. Here is what I've tried:

$.fn.custom_text_input = function(options){
    return this.each(function(){
        var custom_text_input = new CustomTextInput(options, this)

        $(this)[0].val = function(){
            alert('something useful')
        }
    })
}

Ive tried a few other variations of this, all to no avail. If anyone has any ideas that will work, I would very much appreciate the wisdom!

Thanks!

like image 333
Fred Garbutt Avatar asked Sep 27 '13 23:09

Fred Garbutt


2 Answers

To overwrite the $.val() method you need to do something like $.fn.val = function () {...}. Here is a demo: http://jsfiddle.net/CRRP5. I would recommend saving the old .val() method in a variable so you can use it when .val() is called on a regular form input.

like image 140
Jasper Avatar answered Nov 13 '22 20:11

Jasper


The only way you're going to get this to work is by extending the result of jQuery's val() method.

$(function(){
  $.fn.oldVal = $.fn.val
  $.fn.val = function(value){
    //I'm assuming here that you're setting/getting a data value
    //on the object to keep track of it's "custom value"
    if(value && $(this).data('custom-input-value')){
       return $(this).data('custom-input-value', value); 
    }
    else if(value = $(this).data('custom-input-value')){
      return value;
    }else{
      return value ? $(this).oldVal(value) : $(this).oldVal();
    }
  }


})

That might work for you :p

Here's a jsfiddle with it working: http://jsfiddle.net/Z4c6d/

like image 26
nzifnab Avatar answered Nov 13 '22 19:11

nzifnab