How to implement jQuery val() for a span? - javascript

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/

I don't think its a good idea to mess with jQuery like this, and there may be some typing 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's answer
// and return the value you expect
return this.attr('justsomesample');
}
else {
this.attr('justsomesample', value);
return this;
}
};
return oldVal.apply(this, arguments); }});
});

Look at the InputMask jquery plugin. What they do is to store original jquery val() function in a variable and replace it with their own. Then you will receive the call first, you can check if the element is span, 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
}

You can use the .text() JQuery function instead of .val() JQuery function to change your span.

It's not a good iead to override .val(), but if you really want a .val() like method for span, you could just add 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");

Related

Checking value of an html select with jQuery

I have the following select box:
<select id="choose">
<option value=1>A</option>
<option value=2>B</option>
<option value=3>C</option>
</select>
<div id="hide-me">hide me!</div>
How can I hide an element when I select option "B"? I tried this:
<script type="text/javascript">
if ("#chose option:selected").val(2) {
$("#hide-me").hide();
};
</script>
I think I'm close, but nothing happens when I select option "B". Anyone have any suggestions?
You need to attach change event to select element to detect the option change. then use .toggle() with argument value not equal to 2 for making show/hide decision :
$('#choose').change(function(){
$("#hide-me").toggle($(this).val() != "2");
})
Working Demo
Listen to the change event of the #choose element, and add your conditional logic there.
Example Here
$('#choose').on('change', function () {
if (this.value === "2") {
$("#hide-me").hide();
} else {
$("#hide-me").show();
}
});
..equivalent, but perhaps less readable version:
Example Here
$('#choose').on('change', function () {
$("#hide-me").toggle(this.value !== "2");
});
As a side note, the value of the selected option is a string.
If you wanted to, you could also convert it to a number:
if (parseInt(this.value, 10) === 2) { ... }
or you could use == rather than ===: (not suggested, though. This could lead to logical errors.)
if (this.value == 2) { ... }
Without jQuery:
Example Here
document.querySelector('#choose').addEventListener('change', function () {
var element = document.getElementById('hide-me');
if (this.value === "2") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
});
The problem with your code is that:
It is not syntactilally correct — ("#chose option:selected").val(2) is an expression, which in turn should be wrapped in parentheses to be a proper condition for if, like this:
if (("#chose option:selected").val(2)) {
However, even after that your code is not correct because you're not actually using jQuery. You're calling method .val() just on a string "#chose option:selected", whereas that string should instead be a jQuery selector passed to jQuery itself:
if ($("#chose option:selected").val(2)) { // $ is the jQuery object that does all the work
However2, even that is incorrect, because you'd just be checking the value of an element right away. What you need is to wait for an element to be changed. Other answers explain very well how to do that.

How to get the value of a select tag which doesn't change on hover?

I'm using jQuery's .val() function to read the value of a <select> tag.
It seems that, at least in Firefox, .val() returns the value of the option the user is currently hovering over. You can see this behaviour at this jsfiddle.
Is there any way using jQuery or pure javascript to get the value that is shown in the select box, i.e. the last value that actually fired a change event?
Original Idea
function foo() {
var value = $('#select').val();
// do something that depends on value
}
The problem with this is that I only want foo() to use the value that is currently selected. By selected I mean the option that was clicked. In the fiddle, you can see that this value changes as you hover over options.
Alternative
var value;
$('#select').change(function() {
value = $('#select').val();
}
function foo() {
// do something with value
}
This is OK, but the information appears to exist in the DOM, since the last clicked value is displayed in the select box.
So, my question is, is it possible to get the last clicked option from the DOM?
You can do this on the change event instead of by interval
UPDATED CODE based on comments below
$('#bar').on('change', function(){
var $t =$(this) , value=$t.val();
$t.attr('data-answer', value);
});
setInterval(function(){
$('#foo').text($('#bar').attr('data-answer'));
},1000);
your select would have this attribute on it
<select id="bar" data-answer="" >
//options here
</select>
Or using .data method:
$('#bar').on('change', function(){
var $t =$(this) , value=$t.val();
$t.data('answer', value);
});
setInterval(function(){
$('#foo').text($('#bar').data('answer'));
},1000);
Sounds like you're looking for focus()
$("select").focus(function () {
var focusValue = this.value;
$('#foo').text(focusValue);
})
You can chain the event listener focus with change to find the current value and then the selected.
$("select").focus(function () {
var focusValue = this.value;
$('#foo').text(focusValue);
}).change(function() {
var changeValue = this.value
$('#foo').text(changeValue);
});
Here is a jsFiddle Demo

how to know the old value of an element onChange or onTrigger in JQuery?

I have a button :
<button id="btn1">55</button>
And so I change the button value to test2
$('#btn1').text("22");
I want to show a background-picture if the buttons oldValue greater then the newValue.
How can I get the old value from this button?
"I have over 100 buttons and they are changing dynamically."
Update: Isn't there an event that fires before it changes?
You could use jQuery's .data() call and store it for retrieval as needed.
For instance, say you HTML is:
HTML
<form action="#" method="GET">
<input type="text" value="369" />
<button id="btnID">420</button>
</form>
You could easily first gather the data needed and asign it to each element:
Opening script
$("button") // would simply grab all buttons, you can use whatever css selector
.each(function(i) {
$(this).data("prevVal", parseInt($(this).text()));
});
You can then later check this value against a new value as needed:
... some change function
$('#btn1').text("22");
if ($('#btn1').data("prevVal") > 22) {
// do work
}
$('#btn1').data("prevVal", 22)
Just FYI
If you were using inputs instead it would be easier:
$("input").each(function(i) { $(this).data("prevVal", parseInt($(this).val())) })
.on("change", function(e) {
var newVal = parseInt($(this).val());
if ($(this).data("prevVal") > newVal) {
// do work
};
$(this).data("prevVal" newVal);
});
Or if you wanted to maintain a list of values:
$("input").each(function(i) {
$(this).data("vals", new Array());
$(this).data("vals").push(parseInt($(this).val()));
})
.on("change", function(e) {
$(this).data("vals").push(parseInt($(this).val()));
var vals = $(this).data("vals");
if (vals[vals.length-1] > vals[vals.length-2]) {
// do work
};
});
You need to compare it before changing value.
For example
$('#btn1').text(function (index, old) {
if (parseInt(old) > 22) {
//change background image
}
return "22";
});
FIDDLE
Unless you preserve it before the change you cannot get the old value. The change event is fired after the value has been changed already.
Not sure where you want the old value.. but if it while changing the text then use the function to change the text.
$('#btn1').text(function (index, oldvalue) {
console.log(oldvalue);
return "test2";
});
<button id="btn1">test1</button>
​$(document).ready(function(){
var i=1;
$('#btn1').click(function(){
$(this).data('old', $.trim($(this).text())).text('btn'+(++i));
alert( $(this).data('old'));
});
});​
for demo
use jQuery.data() to store data associated with the specified element and you will be able to get it just by accessing the same element.
Here's the link to show you how to use jQuery.data();
Here's the code using a more convenient .data() link
Set
$("#btn1").data("oldVal", $("#btn1").html());
Get
$("#btn1").data("oldVal");
Fiddle

jQuery execute function when option is selected from option object

I am dynamically creating the options for a select element using jQuery. Is it possible in jQuery to setup a function to be executed when that option is selected?
I know I can detect the change of the entire select element, but is it possible to specify this on a per-option basis? Maybe something like this:
$('<option />').onselect(function(){
// do something
});
Edit:
If it's not possible to specify a function that get's executed when a specific option is selected, is it possible to bind a function to an element in jQuery? It would make my logic cleaner by allowing me to just simply execute that function assigned to the option in the .change for the select.
You can delegate a change event to the document and attach an event handler to the select element. This allows for runtime manipulation:
$(document).on('change', 'select', function() {
console.log($(this).val()); // the selected options’s value
// if you want to do stuff based on the OPTION element:
var opt = $(this).find('option:selected')[0];
// use switch or if/else etc.
});
Or if you insist on creating functions for each OPTION, you can do:
$('<option>').data('onselect', function() {
alert('I’m selected');
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
You can use onchange handler to the select:
<select name='numbers' id='numbers'>
<option value='1' selected='selected'>One</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
<script>
$('#numbers').change(function () {
if ($(this).val() === '1'){
function1();
}
if ($(this).val() === '2'){
function2();
}
});
</script>
Best Regards
What you can try is binding the change() event on the select element itself. From there, assuming you have a valid function for each option, you can call an individual option's callback:
$('select').change(function() {
var type = $(this).val();
switch(type) {
}
// Alternatively, you can try this as well:
$(this).find('option:selected').each(function() {
});
});
If you are saying you want to assign individual functions to each option element you can do something like this:
var options = [{"value" : "1",
"display" : "One",
"fn" : function() { console.log("One clicked"); }
},
{"value" : "2",
"display" : "Two",
"fn" : function() { console.log($(this).val() + " clicked"); }
}];
var $select = $("select").on("change", function() {
var opt = this.options[this.selectedIndex];
$(opt).data("fn").call(opt);
});
$.each(options, function(i, val) {
$select.append(
$("<option/>").attr("value", val.value)
.text(val.display)
.data("fn", val.fn)
);
});
​Demo: http://jsfiddle.net/6H6cu/
This actually attaches functions to each option using jQuery's .data() method, and then on click/keyup on the select element it calls the appropriate options function (setting this to the option).
In my opinion that is way overkill, but it seems to be what you are asking.
I guess a simpler version would be something like:
var optionFunctions = {
"1" : function() { ... },
"2" : function() { ... },
...
};
// code to create the options omitted
$("select").on("change", function() {
var fn = optionFunctions[$(this).val()];
if (fn)
fn.call(this.options[this.selectedIndex]);
});

Using JavaScript or jQuery, how do I check if select box matches original value?

Just wondering if there is any way to check if the value of a select box drop-down matches the original value at the time of page load (when the value was set using selected = "yes") ?
I guess I could use PHP to create the original values as JavaScript variables and check against them, but there are a few select boxes and I'm trying to keep the code as concise as possible!
That's not too hard at all. This will keep track of the value for each select on the page:
$(document).ready(function() {
$("select").each(function() {
var originalValue = $(this).val();
$(this).change(function() {
if ($(this).val() != originalValue)
$(this).addClass('value-has-changed-since-page-loaded');
else
$(this).removeClass('value-has-changed-since-page-loaded');
});
});
});
This will apply a new class value-has-changed-since-page-loaded (which presumably you'd rename to something more relevant) to any select box whose value is different than it was when the page loaded.
You can exploit that class whenever it is you're interested in seeing that the value has changed.
$(document).ready(function() {
var initialSelectValue = $('#yourselect').val();
// call this function when you want to check the value
// returns true if value match, false otherwise
function checkSelectValue() {
return $('#yourselect').val() === initialSelectValue;
}
});
PS. You should use selected="selected" not selected="yes".
On page load, create an array with the initial value of each select box indexed by name:
var select_values = [];
$(document).ready(function() {
$("select").each(function() {
select_values[$(this).attr('name')] = $(this).val();
});
});
later when you need to check if a value has changed:
function has_select_changed(name) {
return $("select[name="+name+"]").val() != select_values[name];
}
First, a snippet:
$('select').each(
function(){
if( this.options[ this.selectedIndex ].getAttribute('selected') === null ){
alert( this.name +' has changed!')
}
});
Now the explanation:
Assuming selectElement is a reference to a <select /> elementYou can check which option is selected using
selectElement.selectedIndex
To get the <option /> element which is currently selected, use
selectElement.options[ selectElement.selectedIndex ]
Now when you know which option element is selected you can find out if this element has the selected='selected' attribute (as in the source code, it doesn't change - this is not the same as .selected propery of a DOM node, which is true for the currently selected option element and changes when the selection is changed)

Categories

Resources