hi guys i have some select tags in my selling item page. first one created by HTML and others are created by jquery append when user click on a button add more
<select id='code0' onclick='getvalue(this)'><option>1</option></select>
and in document.ready im applying select2 on this select tag
$(document).ready(function(){
$("#code0").select2();
})
function append(){
$("table").append("<tr><td><select id='code1' onclick='getvalue(this)'><option>1</option></select></td></tr>");
$("#code1").select2();
}
next appended select will have id of code2. I'm managing it without any issue
Now the function getvalue() is working fine before applying select2 but after applying select2 the select is not triggering click or any event. how can i trigger event after applying select 2;
function getvalue(item){
alert("event triggered"); // to check that jquery called this function or not
console.log(item.value);
}
clicking on select tags is not calling get value function;
whenever the page loads i can see this error on console
jQuery-2.1.4.min.js:2 Uncaught TypeError: Cannot read property 'call' of null
at Function.each (jQuery-2.1.4.min.js:2)
at MutationObserver.<anonymous> (select2.min.js:2)
Once you have linked select2 to existing select.
select2 override select and create list(li) for all options and select is hidden.
So any event added to select will not work directly.
Select2 plugin provides functions which you can use to server your need
Assign select2 ele as a var and use methods given by plugins
var select2Ele = $("#code0").select2();
select2Ele.on("select2:select", function (event) {
// after option is selected
});
select2Ele.on("select2:selecting", function (event) {
// before selection
});
For multiple select2 above code will work like this. In log method we have event which can be used to get current element value and other stuffs
$eventSelect.on("change", function (e) { log("change"); });
function log (name, evt) {
if (!evt) {
var args = "{}";
} else {
var args = JSON.stringify(evt.params, function (key, value) {
if (value && value.nodeName) return "[DOM node]";
if (value instanceof $.Event) return "[$.Event]";
return value;
});
}
var $e = $("<li>" + name + " -> " + args + "</li>");
$eventLog.append($e);
$e.animate({ opacity: 1 }, 10000, 'linear', function () {
$e.animate({ opacity: 0 }, 2000, 'linear', function () {
$e.remove();
});
});
}
Refer select2 doc
Related
I have asp.net mvc Kendo grid. Grid rows has dropdowns, When user clicks on grid cell I am able to get Dropdown from below code but in that dropdown not able to bind values
var input = $("<select name='MinAcceptableName' id='MinAcceptableId'></select > ")
e.container.append(input);
input.focus();
I have a JavaScript function that should bind values to above control either on code execution or on <select> click
var url = '#Url.Action("GetCodesList", "LookupCode")'
var ddl = $('#MinAcceptableId');
$('#MinAcceptableId').focus(function () {
console.log("this is code value - " + code);
$.post(url, {codeType: code, selectedValue: value }, function (response) {
ddl.empty(); //clear if already data there
ddl.append($('<option></option>').text("--Select--").val(""));
alert("added default option to MinAcceptableName select");
$.each(response, function (index, item) {
ddl.append($('<option></option>').text(item.Description).val(item.CodeId));
});
});
$('#MinAcceptableId').blur();
})
From above code I am not able to bind values to dropdown(Dropdown empty). JavaScript function code seems is not executing all. How can I fix this ?
This is what I'm doing:
$('select').each(function () {
var selectedValue = $(this).find('option:selected').val();
if (selectedValue !== '0') {
$('option').each(function () {
if (!this.selected) {
$(this).attr('disabled', true);
}
});
}
});
The first option is "-Select an option-" that has a value of "0", that's why I do that validation. Basically what I want to do is to disable all options within a dropdown that has a selected value different than the first one. All dropdowns have been initialized with jquery's select2 and every one of them has a unique id.
The code I'm sharing doesn't work properly because I get the options disabled in every dropdown no matter if no option has been selected.
Can anybody help me fix this please?
I haven't tested but you should replace this line:
$('option').each(function () {
with this one:
$(this).find('option').each(function () {
Also, you should call this function using change event, which means i'ts triggered when some option is selected, like this:
$('select').on('change', function() {
The thing is that by doing this:
$('select').each(function () {
$('option').each(function () {
You were iterating through all select elements and all it's options, instead of iterating through the only select element that was clicked
I want to pass HTML control to another function inside JavaScript. I am calling a modal popup which has a input control and a save button.
The function in which i am calling the modal popup has entire GridView row as a parameter. I want to pass this to another javascript function which will be called on the button click inside of modal dialog.
I tried as below but it passes a string variable.
function ShowDialogPeoplePicker(id, requestType, cntrl) {
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Approvers = row.cells[1].getElementsByTagName("span")[0];
if (requestType == "AddApprovers") {
$('#btnAddApprover').removeAttr('onclick');
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
}
}
The below function will be called on a button click and will set the values inside GridView row.
function setApprovers(cntrl)
{
var usernames= $("#hdnApproversName_CTO").val();
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
row.cells[1].getElementsByTagName("span")[0].innerHTML = usernames;
$("#overlayTasks").hide();
$("#dialogTasks").hide();
return false;
}
Instead of attaching your click handler like this:
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
Try this instead:
$('#btnAddApprover').on('click', function() {
setApprovers(cntrl);
});
If you need to remove previously added event listeners, you can do that with:
$('#btnAddApprover').off('click');
Or if you want to attach the listener to listen just one time in the first place, you can use:
$('#btnAddApprover').one('click', function() {
setApprovers(cntrl);
});
(with one instead of on). Hope this helps!
Instead of
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
use
$('#btnAddApprover').click(function() {
return setApprovers(cntrl);
}
I am using the jQuery plugin radiosToSlider (http://rubentd.com/radios-to-slider/) and need to make sure that all radio button groups are checked and to give an alert when they are
I can do this if they are just radio buttons by checking the length but because the plugin changes the input buttons I am having difficulties
My fiddle is
http://jsfiddle.net/yFaAj/270/
$(document).ready(function () {
$(".radios").radiosToSlider();
});
$(":radio").change(function () {
var names = {};
$(':radio').each(function () {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function () {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
thanks
The problem isn't that the plugin changes your structure (although it does add some ins elements, which I don't agree with), it's that the plugin doesn't fire a change event for the converted radio controls, and setting the checked property interactively doesn't appear to do so either.
Since the plugin author doesn't publish an API for this use case, it's hard to know whether this is by design or oversight, but the source code definitely doesn't fire the event when the slider is clicked:
this.bearer.find('.slider-level').click( function(){
var radioId = $(this).attr('data-radio');
slider.bearer.find('#' + radioId).prop('checked', true);
slider.setSlider();
});
Your options, as I see them:
Contact the API author and ask for a bug fix, or the intended way to support this case
Downside: Time: dependent on the author to respond
Attach your "check" function to the click event of the .slider-level class, as the API does.
Downside: Brittle: future versions of the plugin may attach the behavior to different selectors
Attach your function to the click event of your radio group, and catch click events on the bubble
Downside: Inefficient: It will check for every click in the radio control
Here's a sample implementation of option 3. DEMO.
$(document).ready(function () {
$(".radios").radiosToSlider();
});
var makeIsRadioGroupChecked = function(selector) {
var $radioGroup = $(selector);
return function isRadioGroupChecked() {
return $radioGroup.find(':checked').length > 0;
};
};
var isOptionsChecked = makeIsRadioGroupChecked('#optionsRadioGroup');
var isSizeChecked = makeIsRadioGroupChecked('#sizeRadioGroup');
var areAllGroupsChecked = function() {
return isOptionsChecked() && isSizeChecked();
};
var alertIfAllGroupsChecked = function() {
if (areAllGroupsChecked()) {
alert("all answered");
}
};
$('.radios').on('click', alertIfAllGroupsChecked);
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