After dynamical adding options to select box, trigger doesn't work - javascript

I have select box with with id test. I have trigger on it like:
$("#test").on('change', function() { alert('test'); })
And that works for the first time, but after I add some options to select box dynamically like:
var option = $("<option>")
.attr('value', this.value)
.attr('class', this.class)
.html(this.text);
// if id corresponds to selected id then select it
if (parseInt(this.value) == selected_id) {
option.attr('selected', 'selected');
}
// append to select
$("#test").append(option);
trigger doesn't work. What to do?

Try this:
var option = "<option value='"+this.value+"' class='"+this.class+"'>"+this.text+"</option>";
$("#test").append(option);
Instead of doing:
var option = $("<option>")
.attr('value', this.value)
.attr('class', this.class)
.html(this.text);
And then appending it.
Could you post the entire script? Or at least a more complete example?

This should do it:
$(document).on('change', '#test', function() { alert('test'); });
With the following:
var trigger = false;
if (parseInt(this.value) == selected_id) {
option.attr('selected', 'selected');
trigger = true;
}
// append to select
$("#test").append(option);
!trigger || $('#test').change();
NOTE: By just adding a selected attribute to a new option, the select element won't trigger. You have to explicitly trigger it using .change() or .trigger('change') when applicable. When a user manually selects a value, both the value is set and the change event is triggered at the same time (if the new value is not equal to the previous value).

Related

Second Select disabled if Option 1 in first Select

I have two select boxes. I need the entire second select box to be disabled until the user selects any option other than the first option in the first select box.
This is my logic but I can't quite execute it.
if
.first-select = option-1
then
.second-select .attr('disabled').
else
.second-select .removeAttr('disabled')
You could use the selectedIndex property:
var
firstSelect = document.querySelector('.first-select'),
secondSelect = document.querySelector('.second-select')
;
function changeHandler() {
secondSelect.disabled = firstSelect.selectedIndex === 0;
}
firstSelect.addEventListener('change', changeHandler);
changeHandler(); // execute the handler once on DOM ready
Or if you are using jQuery:
$('.first-select').on('change', function() {
$('.second-select').prop('disabled', this.selectedIndex === 0);
}).change(); // trigger the event once on DOM ready
You have to do something like this
$("#first_select").on("change",function(){
if(this.selectedIndex != 0){
$("#second_select").removeAttr("disabled");
// or you can do this $("#second_select").prop("disabled",false);
});

jquery select2 .on("change", function(e) reset option

i am using select2.
Usage : if a value is "COUNTRY", i want to add a onchange event to the select2, else i want to remove the onchange event as shown below :
var reportLevel = getReportLevel();
if (reportLevel != "COUNTRY") {
$("#selected_countries").on("change", function(e) {
prepareGlidModel(e);
});
} else {
$("#selected_countries").on("change", function(e) {
});
}
Issue : Not being able to remove the onchange event, even if the else block is called.
Events are called based upon the reportLevel value selected in a dropdown.
try following:
var reportLevel = getReportLevel(),
// by default unbind/off change event
$select = $("#selected_countries").off("change");
// and if country then bind it
if (reportLevel == "COUNTRY") {
$select.on("change", function(e) {
alert("you selected :" + $(this).val());
});
}
Working example here: http://jsfiddle.net/JB89B/1/
i think on else case you want to reset the value to default for this you have to use
$("#selected_countries").val('default value')
and if u just want to prevent the default action of onchange event than on else you can write
e.preventDefault()
this will help
You can use off to deatach event handlers from your elements as shown below:
$("#selected_countries").off('change');

jquery returns the text of selected item in select tag plus text of selected item in other select tag

I have two select tags in my website. When I try to get the text of selected item in one select tag, I see that it returns the two texts of the two select tags, even if I specify which select to retrive data from via a class attribute.
My code is
$('select.select').change(function(e) {
e.preventDefault();
var val1 = $(' option:selected').text();
alert(val1);
});
$('select.select2').change(function(e) {
e.preventDefault();
var val2 = $(' option:selected').text();
alert(val2);
});
The alerts are always containing the text of the two select tags concatenated.
Your usual help is appreciated.
Perhaps update the selector to specify the context of the selection:
$('select.select').change(function(e) {
e.preventDefault();
var val1 = $('option:selected', this).text();
alert(val1);
return false;
});
The selector $('option:selected', this) will return values found within the context of the changed element.
It is because of this $('option:selected').text(); you have two selected option in your page so it returns two values.
You need to do this:
// Call the change event for the select
$('select.select').change(function (e) {
e.preventDefault();
// Get the selected option for the select in current scope
var text = $(this).find('option:selected').text();
alert(text );
//return false; No need of this, as we already called the preventDefault() method
});
you need to specify the class when you retrieve the value:
var val1 = $('.select option:selected').text();
and
var val2 = $('.select2 option:selected').text();

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

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