I need assistance changing the value of a custom-select box. I cannot use JQuery because I already have a change() function hooked up to it.
How can I change the value of the select box in Javascript?
This is my custom select function:
$.fn.customSelect = function() {
if ( $(this).length ) {
$(this).find('select').attr('selectedIndex',-1).change(function() {
var optionText = $(this).find('option:selected').text();
$(this).siblings('label').text(optionText)
});
}
};
I have tried:
var field = document.getElementById('test5');
field.value = '2';
field.focus();
This will select the option, but it will not show up as the default option (hopefully you guys can understand this haha).
Any possible solutions?
I made a fiddle example of what trying to do here
You need to invoke the change event to run the plugin code, also name the change event:
$.fn.customSelect = function() {
if ( $(this).length ) {
$(this).find('select').attr('selectedIndex',-1).bind('change.customSelect', function() {
var optionText = $(this).find('option:selected').text();
$(this).siblings('label').text(optionText)
});
}
};
Trigger like this:
$('#select1').val('1').trigger('change.customSelect');
Related
Hi I am developing one jquery application. I ghave one dropdownbox with jquery choosen.
$(function () {
$(".limitedNumbSelect").chosen();
});
This is my dropdown and binding values from database.
<b>Awarded To:</b> <asp:ListBox ID="ddlvendorss" runat="server" SelectionMode="Multiple" class="limitedNumbSelect"></asp:ListBox>
I am trying to get click event for the above dropdown. As soon as i click on the dropodwn i want to fire a alert before loading any options.
$('#ddlvendorss').click(function (e) {
alert("I am going crazy");
});
In the below code checkedValues arrays contains some values(values present in dropdownlistbox). As soon as i click on the drodpown i ant to hide those values. But below code doesnt work.
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
$(".limitedNumbSelect option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
Above code does not work. May I get some advise on this? Any help would be appreciated. Thank you.
Chosen hides the select element, thus you are not actually clicking the element. However you can use chosen:showing_dropdown event
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
alert('No need to go crazy');;
});
Fiddle
If you want to hide options, You can use
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
//Find options and hide
$(this).find('option:lt(3)').hide();
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
Fiddle
As per OP's code
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
//Get all options
var options = $(this).find('option');
//Show all
options.show();
//Hide based on condtion
options.filter(function () {
return checkedValues.indexOf($(this).val()) === -1;
});
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));
I have an input text in jQuery I want to know if it possible to get the value of that input text(type=number and type=text) before the onchange happens and also get the value of the same input input text after the onchange happens. This is using jQuery.
What I tried:
I tried saving the value on variable then call that value inside onchange but I am getting a blank value.
The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/
$('input').on('focusin', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
});
$('input').on('change', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
Better to use Delegated Event Handlers
Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.
Here is the same example using delegated events connected to document:
$(document).on('focusin', 'input', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}).on('change','input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/
Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.
*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change).
Initial value can be taken from defaultValue property:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
Just put the initial value into a data attribute when you create the textbox, eg
HTML
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
JQuery
$("#my-textbox").change(function () {
var oldValue = $(this).attr("data-initial-value");
var newValue = $(this).val();
});
I have found a solution that works even with "Select2" plugin:
function functionName() {
$('html').on('change', 'select.some-class', function() {
var newValue = $(this).val();
var oldValue = $(this).attr('data-val');
if ( $.isNumeric(oldValue) ) { // or another condition
// do something
}
$(this).attr('data-val', newValue);
});
$('select.some-class').trigger('change');
}
I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:
var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
console.log('Current Value: ', $(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
If you want to target multiple inputs then, use each function:
$('input').each(function() {
var inputVal = $(this).val();
$(this).on('change', function() {
console.log('Current Value: ',$(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
my solution is here
function getVal() {
var $numInput = $('input');
var $inputArr = [];
for(let i=0; i < $numInput.length ; i++ )
$inputArr[$numInput[i].name] = $numInput[i].value;
return $inputArr;
}
var $inNum = getVal();
$('input').on('change', function() {
// inNum is last Val
$inNum = getVal();
// in here we update value of input
let $val = this.value;
});
The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.
The function may also break when using focus, because of the ▲▼ (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
If you only need a current value and above options don't work, you can use it this way.
$('#input').on('change', () => {
const current = document.getElementById('input').value;
}
My business aim was removing classes form previous input and add it to a new one.
In this case there was simple solution: remove classes from all inputs before add
<div>
<input type="radio" checked><b class="darkred">Value1</b>
<input type="radio"><b>Value2</b>
<input type="radio"><b>Value3</b>
</div>
and
$('input[type="radio"]').on('change', function () {
var current = $(this);
current.closest('div').find('input').each(function () {
(this).next().removeClass('darkred')
});
current.next().addClass('darkred');
});
JsFiddle: http://jsfiddle.net/gkislin13/tybp8skL
if you are looking for select droplist, and jquery code would like this:
var preValue ="";
//get value when click select list
$("#selectList").click(
function(){
preValue =$("#selectList").val();
}
);
$("#selectList").change(
function(){
var curentValue = $("#selectList").val();
var preValue = preValue;
console.log("current:"+curentValue );
console.log("old:"+preValue );
}
);
I facing problem with my jquery, on showing input text based on input value.
Here is the JS fiddle demo :
http://jsfiddle.net/Ltapp/364/
When I try to input #hotmail, the input box will show. But when I want to type some text in the #hotm input box, it will hide again.
JS code :
$(window).load(function(){
var myString = '#hotmail';
$('#hotm').hide();
$("input").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
});
It's because your selector $("input") affects both input elements. I have updated it to the $("input:first") selector instead. JsFiddle here
$("input:first").keyup(function () {
var value = $(this).val();
if(value.match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
As many has said, you are binding the event on all the inputs I did a little change:
$(function(){
var myString = /#hotmail/ig;
$("#check").bind('keyup checkvalue', function() {
$('#hotm')[myString.test(this.value) ? 'show' : 'hide']();
}).trigger('checkvalue');
});
using regex if you are using #HoTmAil it will also hit on that, and also added a custom event checkvalue to see if #hotm should be visible on for example a postback on the form you might be using.
demo: http://jsfiddle.net/voigtan/xjwvT/1/
You're affecting all inputs. Either give each one a unique ID / Class or use the jQuery $(this) method.
See JSFiddle Here:
http://jsfiddle.net/Ltapp/366/
<input type="text" id="firstinput"/>
<p id="secondinput"><input type="text"/></p>
var myString = '#hotmail';
$('#secondinput').hide();
$("#firstinput").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#secondinput').show();
} else {
$('#secondinput').hide();
}
});
use this for your if part :
if($(this).val().match($(this).val().substr(0,strlen($(this).val())))
it's because the new box also = "input"; if you give the hotmail textbox it's own id, it won't hide
<input id="hotmail" type="text"/>
and then
$("#hotmail").keyup(function () {...});
I have an annoying problem where I have a jQuery selecting the various options of a SELECT option list. I want to set the SELECTED=SELECTED attribute to force something other than the first item to be the default.
Seems pretty basic, and if I set other characteristics of the OPTION tag it works fine. For instance:
$(this).addClass ('TEST');
works as you'd expect by adding the TEST class to what should be the default option. I also can do the following:
$(this).attr('annoying', "SELECTED");
This adds the attribute "annoying" with the value of "SELECTED. Sadly if I do the following:
$(this).attr('SELECTED', "SELECTED");
it just completely ignores it. If I go into Chrome's debugger and punch this in manually it does work but not from my JS file. :^(
Any ideas?
UPDATE
Great suggestions so far but as nothings working I suspect something else is amiss. To provide further context ... this is a Wordpress site and I'm making the QuickEdit function bring up the right OPTION in a custom attribute to a taxonomy. For those of you who don't know Wordpress its probably not important (who knows at this stage).
Here's the full code:
jQuery(document).ready(
function ($) {
$('.editinline').on ('click',
function () {
var $data_ref = $(this).closest('tr');
$('.bespoke-item.quick-edit').each (
function () {
var col_name = $(this).attr('name');
var col_value = $data_ref.find ('.' + col_name).text();
$(this).val(col_value); // this will work for non-enumerated widgets
if ( $(this).is( "select" ) ) {
selected = false; // used as a flag on whether the SELECTED value has been found
options = $(this).find ('.select-option');
options.each(
function () {
if ( $(this).attr('value') == col_value ) {
$(this).addClass ('TEST');
selected = true;
$(this).attr('SELECTED', "SELECTED");
this.selected = 'SELECTED';
}
}
);
if ( !selected ) {
// The value of the did not match any of the selections (this likely means it wasn't set at all)
// In this case revert to the "static-default" setting
options.each(
function () {
if ( $(this).attr('static-default') ) {
$(this).attr ('SELECTED' , 'SELECTED');
alert ("Found value in static default " + $(this).val());
selected = true;
} else {
$(this).removeAttr ( 'SELECTED' );
}
}
);
}
}
}
);
}
);
});
Three options for you (all assume that this is the option element in question, as it seems to be in your question):
If you're using a recent copy of jQuery, it could be the attr vs. prop thing (also note that selected should be in lower case, not caps):
$(this).prop('selected', true);
Sometimes it's simpler just to use the DOM directly:
this.selected = true;
Or, of course, use val on the select element, setting it to the value of the option you want selected.
$("selector for the select element").val($(this).val());
// or better (as `value` is entirely reliable on option elements):
$("selector for the select element").val(this.value);
Live Examples of All Three | Source
I have a hidden select which should be automatically selected via a visible select, my jquery is:
$(document).ready(function() {
var selected_val = $('#id_foo option:selected').val();
$('#id_bar').val(selected_val);
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
$('#id_bar').val(selected_val);
});
});
This works fine, but the page I am working on has the option to add a value to the (visible) select on the fly. How do I bind to this event and add this to the hidden list before updating the selected value?
The best way to tackle this is to update the hidden select with the new values when you update the visible one.
Or, as per my comment, you could populate the hidden select when the visible one is changed:
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
//clear and re-populate all of hidden select here
$('#id_bar').val(selected_val);
});
This should do the trick:
$(function () {
var $bar = $('#id_bar');
var $foo = $('#id_foo');
$bar.val($foo.val());
$foo.change(function () {
var newValue = $(this).val();
if ($bar.find('[value="' + newValue + '"]').length === 0) {
$bar.append($('<option/>').val(newValue));
}
$bar.val(newValue);
});
});
Before setting the new value, checks if the value is an option. If it's not, add as an option.
This snippet correctly identifies the event and succesfully copies the select options from foo to bar. However it does not seem to set :selected correctly on either id_foo or id_bar and using DOMSubtreeModified feels hackish
$('#id_foo').bind("DOMSubtreeModified", function(){
var high = 0;
$('#id_foo').children().each(
function(){
if ($(this).val() > high) {
high = $(this).val();
}
}
);
$('#id_foo').val(high);
var new_options = $('#id_foo').clone();
$('#id_bar').html('');
$('#id_bar').append(new_options.children());
});
So, for now the best I could come up with:
$('#id_foo').bind("DOMSubtreeModified", function(){
location.reload();
});