Alternative to .change in jquery? - javascript

I'm trying to fire an ajax event, and passing the value of select list options as arguments in the ajax call. Unfortunately, I'm firing the call on the .change event, and it is passing the values of the select option before the new option has been selected (i.e passing the previously selected options values). Is there an event which will get the current values of the option selected? Much thanks in advance,
<select id='theList'>
<option> Option 1</option>
<option> Option 2</option>
</select>
In the JS:
$('#theList').change( function() {
$.getJSON('Home/MethodName', { var1: Option1Value, var2: MiscValue}, function(data) {
//Execute instructions here
}
)});
I wanted to use .trigger, but I think that fires beforehand as well.

I think .change() is what you want, but you're misusing it. The change event fires after the value has changed. In your handler, you need to read the new value:
$('#theList').change( function() {
var value = $('#theList').val();
$.getJSON('Home/MethodName', { your_key: value }, function(data) {
// ...
}
)});
You also might want to set values on your <option> tags:
<option value="something"> Option 2</option>

You must be doing something wrong when getting the current select value. The following works correctly for me.
http://jsfiddle.net/TJ2eS/
<select id="demo">
<option value=""></option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
$("#demo").change(function() {
alert("current select value " + $(this).val());
});

A word of warning, .change is now defunct, you should use...
.on('change', function()
Like that.

Related

Remove and add values from dropdown using javascript/jQuery

I am trying to achieve the following thing in my code but it is getting complicated.
I have 'n' dropdowns with or without duplicate values in it.
for simplicity lets assume following scenario:
dropdown1:
<select>
<option>100</option>
<option>200</option>
<option>102</option>
</select>
dropdown 2:
<select>
<option>100</option>
<option>200</option>
<option>201</option>
</select>
dropdown3 :
<select>
<option>100</option>
<option>300</option>
<option>301</option>
</select>
case1:
if user select value 100 from dropdown 1 then 100 should be removed from all the dropdowns.and when user change dropdown 1 value from 100 to 200 then 100 should be added back to all the dropdowns and 200 should be removed from all the dropdowns.
removing seems easy but adding back values is little difficult.
how can I maintain a list or some other data structure to remember which value to add and where incase of multiple value change? is there any advance jquery feature or generic javacript logic i can use ?
If it is sufficient to just disable the option instead of actually removing it, the following could work for you. You might want to adapt the handling of the selects when initially loading the site.
$('select option[value="' + $('select').eq(0).val() + '"]').not(':eq(0)').prop('disabled', true);
$('select').on('change', function() {
var val = $(this).val();
$('select option').prop('disabled', false);
$('select option[value="' + val + '"]').not($(this)).prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='102'>102</option>
</select>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='201'>201</option>
</select>
<select>
<option value='100'>100</option>
<option value='300'>300</option>
<option value='301'>301</option>
</select>
It would be better to set display to none instead. Hence, you will avoid the complications of adding or removing in the appropriate order.
So, you can easily return them visible.
$( "option" ).each(function( index ) {
$(this).css("display", "");
});
$("#drop").change(function () {
var selected_value=$(this).val();
var dropdown=$(select);
for(i=0;i<dropdown.length;i++){
$("dropdown[i] option[value=selected_value]").remove();
}
});
Set id of first dropdown="drop"
Here select the value and define it S a variable loop through dropdown with in page remove option when value=selected_value

How do I attach an event to an array of select boxes?

I have an array of select boxes, with a class "taskcompleted". I want to be able to do something when a box is changed.
<select class = "taskcompleted" >
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
I have used this javascript code
function initselects() {
var myselects = $('.taskcompleted');
myselects.each( function(){ // any select that changes.
console.log( $(this).val() );
}).change();
}
When the page loads, it is logging a change for each select box. I do not want this to happen. I want to only log a change after the page as has loaded.
You can use change() to attach the event to each select, like this:
function initselects() {
$('.taskcompleted').change(function() {
console.log($(this).val());
});
}
Something like this you mean? This will add change handlers to all selects with class taskcompleted
The problem you have it that you're adding .change() to the end which actually triggers the change you don't want to happen - so instead, just listen for it
function initselects() {
$('select.taskcompleted').on('change', function() {
// do something
});
}
If you don't want the logging at page load, then simply remove change() from the end.
In general you can use it like that
JavaScript:
var myselects = $('.taskcompleted');
myselects.change( function(){
console.log($(this).attr('name') + ': ' + $(this).val() );
});
HTML:
<select name="1stselectbox" class = "taskcompleted" >
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<select name="2ndselectbox" class = "taskcompleted" >
<option value="Maybe">Maybe</option>
<option value="dontknow">I don't know</option>
</select>
So you set the change listener directly on the jQuery objects, no need to use a loop (each). The example above will even print which select box was selected (might be useful). E.g. the output will be when changing the first box to Yes: 1stselectbox: Yes
JSFiddle: https://jsfiddle.net/x8jwy92h/

how to change a value of drop down and to trigger a onchange functions in javascript

I was wondering if it is possible to change a value of a dropdown box dynamically and to trigger an ajax onchange function assigned to this dropdown at the same time.
so far I can only change the value of a dropdown box but the onchange function is not being called.
here is the dropdown:
<select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
<option value="">--Select Item--</option>
<option value="one"> Option one</option>
<option value="two"> Option Two</option>
<option value="three"> Option Three</option>
</select>
when I do this operation:
document.getElementById("ProductSelector").value = "one";
the value of the dropdown is changing, but the getItems function is not being triggered.
What am I doing wrong or may be there is another way to change a value of the doropdown which will allow me to trigger my ajax function as well?
I don't want to use JQuery. I just wandering why the function is not working if I use dinamic change and on manual change it works fine?
So, you are changing the value with JavaScript and the change event isn't triggering. So, lets trigger it then.
Trigger the event change every time you change the value via JavaScript.
No jQuery used.
Try this:
function changeVal() {
var elem = document.getElementById("ProductSelector"),
event = new Event('change');
elem.value = "one";
elem.dispatchEvent(event);
}
function getItems(val) {
alert(val);
}
changeVal();
<select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
<option value="">--Select Item--</option>
<option value="one">Option one</option>
<option value="two">Option Two</option>
<option value="three">Option Three</option>
</select>
I mostly do it this way:
HTML:
<select class="class-name">
<option value="1">1</option>
<option value="2">2</option>
</select>
jQuery:
$(".class-name").on("change", function() {
var value = $(this).val();
$.ajax({
type: "post",
url: "your-php-script.php",
data: { 'value' : value },
success: function (data) {
alert('This has changed');
}
);
});
Problem is changing the value with JS will not trigger the change event. Best solution would be to write a function which changes the value and triggers the change event manually.
HTML
<select name="ProductSelector" id="ProductSelector">
<option value="">--Select Item--</option>
<option value="one"> Option one</option>
<option value="two"> Option Two</option>
<option value="three"> Option Three</option>
</select>
JS (no jQuery)
//define the element so we can access it more easily
var element = document.getElementById('ProductSelector');
//define the event we want to trigger manually later
var event = new Event('change');
//add eventlistener which is triggered by selecItem()
element.addEventListener('change', function(event) {
getItems(event.target.value);
});
function getItems(val) {
alert(val);
}
//set the value and trigger the event manually
function selectItem(value){
//select the item without using the dropdown
element.value = value;
//trigger the event manually
element.dispatchEvent(event);
}
//using a function with the option you want to choose
selectItem("three");
JSFiddle
Use the working JSFiddle: Note that you have to uncomment the last line of code.
<html>
<body>
Select your favorite value:
<select id="mySelect">
<option value="value1">value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
<option value="value4">value4</option>
</select>
<script>
$(document).ready(function() {
$( "#mySelect" ).change(function() {
var value = $(this).val();
$.ajax({
type: "post",
url: "request-url.php",
data: { 'value' : value },
success: function (data) {
alert('the ajax request has been send');
}
);
});
});
</script>
</body>
</html>
You can try removing the onchange="" attribute from the select input and just use the jQuery to check for changes:
$('body').on('change', "#ProductSelector", function(){
var id = $(this).val();
//now do your ajax call with the value selected
});
"What am I doing wrong or may be there is another way to change a value of the doropdown which will allow me to trigger my ajax function as well?"
Another way of adding the event listener is by doing it "unobtrusive style".
document.getElementById('ProductSelector').addEventListener('change', function(event) {
getItems(event.target.value);
});
function getItems(val) {
// Todo: whatever needs to be done :-)
alert(val);
}
<select name="ProductSelector" id="ProductSelector">
<option value="">--Select Item--</option>
<option value="one">Option one</option>
<option value="two">Option Two</option>
<option value="three">Option Three</option>
</select>
http://jsfiddle.net/dytd96cb/

Change selected item from inside onchange event

In the following select box:
var sval=1;
function foo(v) {
sval=Number(v);
}
...
<select name="sval" onchange="
if (confirm('...?')) foo(this.value); else $(this).val(sval);">
<option value="1">1
<option value="2">2
<option value="3">3
The idea is to confirm the selected item change. If not confirmed to change back to the old value.
if confirm returns true, all is working as expected
if confirm returns false, then the select always gets value 1, regardles of sval
Why changing the selected item does not work from inside the onchange handler?
EDIT: The following code based on ejay_francisco's answer does the proper job:
http://jsfiddle.net/4wCQh/33/
var vals = 1;
$("#svalue").change(function() {
if (confirm('...?'))
vals=Number(this.value);
else
$(this).val(vals);
});
but its not clear what is the reason that the inline code $(this).val(sval) resets the select to 1
I've modified your code and this is how i've done it
Working Fiddle :
Javascript :
$( "#svalue" ).change(function() {
if (confirm('...?')) {
vals =$('#svalue').val();
$('#svalue').val(this.options[this.selectedIndex].value);
}else{
$('#svalue').val(vals);
}
});
HTML :
<select id="svalue">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
EDITED :
here's how its done inline : working Fiddle
HTML:
<select name="sval" onchange="if (confirm('...?')) {foo(this.value);sval=(this.value);} else $(this).val(sval);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
Javascript :
var sval=1;
function foo(v) {
$('#svalue').val(v);
}
apparently you forgot to change the value of sval to whatever the user has previously clicked. the code is sval=(this.value); on the onchange part.
Try
I think else part is not neccessary
Change to
<select name="sval" onchange="
if (confirm('...?')) foo(this.value);">
Your approach is absolutely horrible.
When ever you inline JavaScript events on elements it just looks ugly.
Why are you wanting to set the select value to the value it has as the currently selected value?
Could you just skip this $(this).val(sval = this.value;); and only have this sval = this.value;
I'm just really a huge fan as to keeping the code and values to a bare minimum where variables are not needed and also where code is not needed.
Give this a shot.
<script type="text/javascript">
var sval = 1;
var foo = function () {
if(confirm('...?')) {
$(this).val(sval = this.value);
}
else
{
$(this).val(sval);
}
};
setTimeout(function () {
document.getElementById('sval').onchange = foo;
}, 100);
</script>
<select id="sval">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I have found the reason the code is not working.
It came out that there are differences between execution in fiddle and browser which made tracking the problem harder.
In the inline code of the onchange event a variable with the same name as name="sval" gets defined and because the name is the same with the integer variable from the global context, the code is not using the proper value to change select's value.

JQuery select2 set default value from an option in list?

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.
One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :
Markup
<select class="select2">
<option id="foo">Some Text</option>
<option id="bar" selected="selected">Other Text</option>
</select>
JavaScript
$('select').select2(); //oh yes just this!
See fiddle : http://jsfiddle.net/6hZFU/
Edit: (Thanks, Jay Haase!)
If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:
$('select').select2("val", null); //a lil' bit more :)
After this, it is simple enough to set val to "Whatever You Want".
The above solutions did not work for me, but this code from Select2's own website did:
$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed
Webpage found here
Hope this helps for anyone who is struggling, like I was.
$("#id").select2("val", null); //this will not work..you can try
You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
One way to accomplish this is...
$('select').select2().select2('val', $('.select2 option:eq(1)').val());
So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".
<select class=".select2">
<option id="foo">Some Text</option>
<option id="bar">Other Text</option>
</select>
Hope this is useful to someone else.
For 4.x version
$('#select2Id').val(__INDEX__).trigger('change');
to select value with INDEX
$('#select2Id').val('').trigger('change');
to select nothing (show placeholder if it is)
Came from the future? Looking for the ajax source default value ?
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
You're welcome.
Reference:
https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2
Step 1: You need to append one blank option with a blank value in your select tag.
Step 2: Add data-placeholder attribute in select tag with a placeholder value
HTML
<select class="select2" data-placeholder='--Select--'>
<option value=''>--Select--</option>
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
</select>
jQuery
$('.select2').select2({
placeholder: $(this).data('placeholder')
});
OR
$('.select2').select2({
placeholder: 'Custom placeholder text'
});
e.g.
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
you can see it here https://select2.org/programmatic-control/add-select-clear-items
Don't know others issue, Only this code worked for me.
$('select').val('').select2();
Normally we usually use active but in select2, changes to selected="selected"
Example using Python/Flask
HTML:
<select id="role" name="role[]" multiple="multiple" class="js-example-basic-multiple form-control">
{% for x in list%}
<option selected="selected" value="{{x[0]}}">{{x[1]}}</option>
{% endfor %}
</select>
JQuery:
$(document).ready(function() {
$('.js-example-basic-multiple').select2();
});
$(".js-example-theme-multiple").select2({
theme: "classic",
placeholder: 'Select your option...'
});
It's easy. For example I want to select option with value 2 in default:
HTML:
<select class="select2" id="selectBox">
<option value="1">Some Text</option>
<option value="2">Other Text</option>
</select>
Javascript:
$("#selectBox").val('2').trigger('change')
$('select').select2("val",null);
If you are using an array data source you can do something like below -
$(".select").select2({
data: data_names
});
data_names.forEach(function(name) {
if (name.selected) {
$(".select").select2('val', name.id);
}
});
This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.
For ajax select2 multiple select dropdown i did like this;
//preset element values
//topics is an array of format [{"id":"","text":""}, .....]
$(id).val(topics);
setTimeout(function(){
ajaxTopicDropdown(id,
2,location.origin+"/api for gettings topics/",
"Pick a topic", true, 5);
},1);
// ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

Categories

Resources