I have a few select elements that are grouped by a span. I'm creating a plugin to do some interaction with the elements. Now I would like to give my users the support of the val()
function, so that they are able to get or set the 'value' of my span. Setting the value will result in the select box element to change en getting the value will result in the addition of the selectbox values.
Basically I would like my plugin to add the support for the val()
method. Any ideas on how to implement this?
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()
.
This is not a full plugin and I did not override 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With