How to implement jQuery val () for span?

I have several elements that are grouped by range. I am creating a plugin for interacting with elements. Now I would like to provide my users with support for the val() function so that they can get or set the "value" of my range. Setting the value will cause the selection box item to change, and getting the value will add selectbox values.

Basically, I would like my plugin to add support for the val() method. Any ideas on how to implement this?

The code

 <span id="test"> <select id="one"> <option value="1">1</option> <option value="2">2</option> </select> <select id="two"> <option value="1">1</option> <option value="2">2</option> </select> </span> 

Challange
Get the following code to work: $('#test').val('1:1'); and $('#test').val() .

+6
source share
5 answers

This is not a complete plugin, and I have not redefined val() , but it should do what you want.

 $.fn.value = function(value) { if (value) { var s = value.split(':'); for ( var i = 0; i < s.length; i++ ) { this.find('select').eq(i).val(s[i]); } } else { var result = []; this.find('select').each( function( index, item ) { result.push($(item).val()); }); return result.join(':'); } } $(function() { $("#test").value("2:2"); alert($("#test").value()); }); 

You can try it at http://jsfiddle.net/QBSWm/1/

+2
source

Take a look at the InputMask jquery plugin. They do this to save the original jQuery val() function in a variable and replace it with their own. Then you first get the call, you can check if there is a span element, and if so, return it , otherwise call the original function .

 var originalVal = $.fn.val; $.fn.val = function(params){ // if span then return your logic // otherwise call originalVal } 
0
source

I don't think this is a good jQuery related idea like this, and there may be some input errors, but here you go:

 var oldVal = jQuery.fn.val; jQuery.fn.extend({ val: function(value) { // replace class check below with something related to your span if (this.length == 1 && this.is('span.my-custom-class')) { if (arguments.length == 0) { // below is just a sample, traverse // child selects like in DanielB answer // and return the value you expect return this.attr('justsomesample'); } else { this.attr('justsomesample', value); return this; } }; return oldVal.apply(this, arguments); }}); }); 
0
source

You can use the .text () jQuery function instead of the jquery .val () function to change the range.

0
source

This is not good iead to override .val() , but if you really want to use the .val() method for span, you can simply add the following code:

 $.fn.sval = function(value) { if(!value) return $(this).html(); else return $(this).html(value); } 

and then to use it just like .val ():

 // Get value alert($('#test').sval()); // Set value $('#test').sval("yo"); 
-1
source

Source: https://habr.com/ru/post/887353/


All Articles