JavaScript/jQuery: Select on change event not firing - javascript

I have this problem trying to getting one single function attach multiple individual functions on "Change" event of a dropdown list using for ... in loop. The $('select') object top has no method 'on' is the Type error detected by Chrome Debugger.
Here is my code: (I don't have much JavaScript / jQuery knowledge so please be bear up with my coding)
function AKaizerDropdown(HiddenFeild) { //#id of hidden field passed as parameter
var select = $('select'); // select object assigned to variable
var selectcount = 0;
var Selecthold=new Array();
for (select in this) {
select.on('change', function() {
var SelectedIndex = this.attr('selectedIndex');
selecthold[selectcount] = [select.attr('id'), selectedindex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
selectcount +=1;
}
var item= new array();
//Elements in selecthold array printed onto hidden field
for (item in selecthold) {
$(HiddenFeild).val += item[0] + item[1]; //Assigns values to element Hiddenfield in DOM
}
}
Edited Code :
$.fn.AKaizerDropdown = function (HiddenFeild) {
var select_ = $(this).find('select');
var selectcount = 0;
var Selecthold=new Array();
select_.each(function () {
$(this).on('change', function () { //everything runs fine except dropdownlist doesn't enter into this event when an item is chosen
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, Selectedindex];
});
});
var button_ = $(this).find('input')
button_.on('click', function () {
for (item in Selecthold) {
$(HiddenFeild).val += item[0] + item[1]+','; //Assigns values to element Hiddenfeild in DOM seperated by ","
}
});
}
Somewhat fixed code still doesn't work
Here is the part where i attach it to popover Bootstrap(twitter 2.3.2) .
//think the problem lies here where the pop up seems to re-render the same same html found in ($#KaizerDragon") where all JavaScript is probably discarded?
$("#ContentPlaceHolder1_ADragonTreeviewt41").popover({
html: true, container: 'body',
trigger: 'click',
content: function () {
$(function () {
$("#KaizerDragon").AKaizerDropdown();
});
return $("#KaizerDragon").html();
}
});
So my question is how can I correct the above code to get the intended output(as in comments within code) ?

You are declaring
var select = $('select'); // select object assigned to variable
But then overriding the value in your for loop
for (select in this) ...
That is to say, the select inside the loop isn't the same as you declared above.

try something like this
select.each(function(){
$(this).on('change', function() {
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, SelectedIndex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
})

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

onchange event not working at begining of page loading

I have a web application which has an onchange event for loading multiple select options to a textbox separated by ',' and slice the last ','
It's working fine,
I have an another function for form filling. When I try to load the form only select option is being updated expecting onchange function to get data from select and have some value in textbox.
But sadly it's not working but working only after new option is selected or removed and added back
Function for adding multiple select data to textbox with onchange event:
// arguments: reference to select list, callback function (optional)
function getSelectedOptions(sel,fn) {
var opts = [], opt;
// loop through options in select list
for (var i=0, len=sel.options.length; i<len; i++) {
opt = sel.options[i];
// check if selected
if ( opt.selected ) {
// add to array of option elements to return from this function
opts.push(opt);
// invoke optional callback function if provided
if (fn) {
fn(opt);
}}}
// return array containing references to selected option elements
return opts;
}
// example callback function (selected options passed one by one)
function callback(opt) {
// display in textarea for this example
var display = document.getElementById('display');
display.innerHTML += opt.value + ',';
}
// anonymous function onchange for select list with id lstBox2
document.getElementById('sel1').onchange = function(e) {
// get reference to display textareaa
var display = document.getElementById('display');
display.innerHTML = ''; // reset
// callback fn handles selected options
getSelectedOptions(this, callback);
// remove ', ' at end of string
var str = display.innerHTML.slice(0, -1);
display.innerHTML = str;
};
Function to form filling:
$(document).ready(function () {
tests = split[testIndex];
// $('#display2').val(tests);
var opt2 = '<option selected>' + tests + '</option>';
$('#sel').append(opt2);})
Try moving your document.getElementById('sel1').onchange code into the $(document).ready(...) block. It's hard to tell without a complete page example, but one possibility is that 'sel1' isn't part of the DOM yet when you try to add the onchange handler.
Try to use
$('body').on('change', '#sel1', function(e) {
});
instead if the elements are added after load.

How to hide the values in jquery choosen dropdownlistbox?

Hi I am developing one jquery application where I have one choosen dropdownlistbox and gridview. The first column of gridview contains checkboxes and at the top it also contains check all button. For example if I check 3 rows inside the gridview then corresponding values in dropdownlistbox i need to disable. I am trying as below.
This is the code to get all the cheked values from gridview.
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true))
{
checkedValues += $(this).val();
}
});
Once i get values in array and when i go to dropdown i have below code.
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
//if (this.value == checkedValues) If this.value is equal to any value from checkedValues then i want to hide that value inside dropdownlistbox.
// Here i want to hide all values of checkedValues array(values will be same in dropdownlistbox)
});
});
I tried as below.
$('.limitedNumbSelect').change(function (e) {
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if ($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true)) {
checkedValues.push($(this).closest('tr').find('td:eq(2)').text().trim());
}
});
$(".limitedNumbSelect > option").each(function () {
var val = $(this).val();
alert(val);
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
In above code there is one bug. For example if i select one value from gridview then if i click on dropdown i am able to select that value(on first click). On second click required value will hide.
Above code does not work. Array checkedValues doesnt catch values.
I am unable to figure out what to write inside. Any help would be appreciated. Thank you.
Try something like this:
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
});
});
Replace the line:
checkedValues += $(this).val();
In this line:
checkedValues.push($(this).val());

Retrieving values from for loop into jquery

How do I retrieve values from #for loop into jquery..Each value inside for loop should have different id, and jquery should get each separate id....
My for loop,
#for (int i = 0; i < searchList.Count;i++ )
{
<label for="input#i"><input type="checkbox" id="input#i"/>#searchList[i] </label>
}
My jquery which isn't helping,
$("#input#i").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input#i").val();
alert(valChk);
}
});
Thanks in advance...
You can use Attribute Starts With Selector to bind the event.
$("[id^=input]").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input#i").val();
alert(valChk);
}
});
As the id of both label and input-checkbox starts with 'input' the click event will bind to both of them. If you want to restrict you can add type to the selector, for instance you want only on checkbox you can change selector as under.
$("input[id^=input]").on("click", function () {...
or
$(":checkbox[id^=input]").on("click", function () {...
If you assign a class to the control you want to attach event then you can use class selector to bind the event.
#for (int i = 0; i < searchList.Count;i++ )
{
<label for="input#i"><input type="checkbox" class="chk-class" id="input#i"/>#searchList[i] </label>
}
$(".chk-class").on("click", function () {...
Edit As Mohamed-Yousef pointed you should use currentChk preferably or $(this) instead of $("#input#i") in statement $("#input#i").val(); as #i will not be the substituted value by C# loop but it will be added as string literal.
As a additional note you may use native javascript whenever possible and suitable e.g I would use this.checked instead of currentChk.prop("checked") to get the better performance, readability and simplicity.
$("[id^=input]").on("click", function () {
if (this.checked)
{
//your code
}
else
{
//your code
}
});
if you want to trigger onclick for all input
$("input").click(function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
var valChk = "Id:" + this.id + " Value:" + this.value;
alert(valChk);
}
});
$("input:checkbox [id^=input]").click(function(){
if ($(this).is(":checked")) {
var valChk = $("this").val();
alert(valChk);
}
});
this another option you can use

Javascript/JQuery iterate through table rows and cells and output an attr of checked checkboxes to console

I have the following code, which should go through each table row and dump my array which is declared in an earlier segment of javascript. Then if the checkbox is checked, and it has an attr of "changed=yes" then it should be pushed onto the array and the value should be outputted in console as well as the "path" attribute which should be outputted as a variable that can be overwritten every time the function finds a new checkbox that is checked and changed. So what is wrong with my code? These functions are contained in a function that is called when the user clicks submit on the form.
JsFiddle: http://jsfiddle.net/hU89p/392/
$('#myTable1 tr').each(function(){
myArray = [];
$.each($("input[type='checkbox']:checked").closest("td").siblings("td"),
function () {
if($(this).data("changed") == 'yes'){
myArray.push($(this).attr('checkboxtype'));
filepath = $(this).attr('path');
console.log(myArray);
console.log(filepath);
}
});
});
Here is the Working Fiddle :
Keep it simple :
$('#myTable1 tr').each(function() {
var columns = $(this).find('td');
columns.each(function() {
var box = $(this).find('input:checkbox');
if(box.is(":checked") && box.attr("changed") == 'yes')
{
myArray.push(box.attr('checkboxtype'));
filepath = box.attr('path');
}
});
});
console.log(myArray);
});
You should be using $("input[type='checkbox']:checked").closest("td").siblings("td").each().
See the difference between $().each() and $.each().
try this :-
$('#myTable1 tr').each(function () {
myArray = [];
$(this).find("td input:checkbox").each(function () {
if ($(this).is(":checked") && $(this).attr("changed") == 'yes') {
myArray.push($(this).attr('checkboxtype'));
filepath = $(this).attr('path');
console.log(myArray);
console.log(filepath);
}
});
});

Categories