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/
Related
I'm trying to insert price into the html element, which I'm getting from the input "data" value.
First function is working perfect, but second one is always giving 0.
$(document).ready(function() {
if ($('input[name="bedrooms"]').is(':checked')) {
var bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
} else {
var bedroomPrice = 0;
}
$('input').on('change', function() {
$('#total').html(bedroomPrice);
});
});
Could you please tell me what I'm doing wrong?
You are using assigning value to a variable only when page loads. Actually you need to update the value of the variable when your input is changed.
Here is updated JS code:
$(document).ready(function() {
var bedroomPrice = 0;
$('input').on('change', function() {
if ($('input[name="bedrooms"]').is(':checked')) {
bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
} else {
bedroomPrice = 0;
}
$('#total').html(bedroomPrice);
});
});
Now it checks bedroom prices when the input gets change, which is latest value.
Also if you have multiple bedrooms choices and you want to show only price of the checked checkbox (considering user can check any 1 checkbox only at the time).
User this (which is the current element object) instead of input[name="bedrooms"].
So JS code will becomes like:
$(document).ready(function() {
var bedroomPrice = 0;
$('input').on('change', function() {
if ($(this).is(':checked')) {
bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
} else {
bedroomPrice = 0;
}
$('#total').html(bedroomPrice);
});
});
Hope it will work for you.
On a checkbox change event, one of a javascript bind the toggle action.
Later on(in a different script) I want to change toggle action based on a condition.
Ex.
script 1:
$(document).ready(function () {
var shipFields = $('.address1 input');
$("input[name = 'same_as_bill']").on("change", function (evt) {
toggleFields(shipFields, !$(this).is(":checked"));
});
function toggleFields(fields, show) {
var inputFields = $("li", fields).not(".sameas, .triggerWrap");
inputFields.toggle(show);
}
}
Script 2:
$(document).ready(function () {
$('li.sameas input').click(function (sender) {
var target = $(sender.target);
var selectedCountryValue = $('li.country select', target.closest('fieldset')).val();
// determine data method based on country selected
if (selectedCountryValue === "xxx") {
ShowAddress(true, target);
} else {
ShowAddress(false, target);
}
});
function kleberShowAddress(show, target) {
if (show) {
$('li.address).hide();
} else {
$('li.address).show();
}
}
});
Issue I have here is, my site load the script 1 first and then the script 2. So by the time script 2 performs the action, toggle action is queued and will trigger that after the changes from script 2, that will revert the changes which I want.
Is there a way to remove the action in the queue? or stop happening first request. I do not want to use .unbind() which will stop triggering script 1 function. I just want to stop the action when ever it meets the condition in script 2.
Please note: above functions are trimmed to show less codes.
add var isActive = true; and use it to check in first script.
In script 2, you can call isActive = false any time you want to disable the first script's function or isActive = true for re-enable them.
Your code will look like:
//script1
var isActive = true;
$(document).ready(function() {
var shipFields = $('.address1 input');
$("input[name = 'same_as_bill']").on("change", function(evt) {
if (isActive) {
toggleFields(shipFields, !$(this).is(":checked"));
}
});
function toggleFields(fields, show) {
if (isActive) {
var inputFields = $("li", fields).not(".sameas, .triggerWrap");
inputFields.toggle(show);
}
}
});
//script2
$(document).ready(function() {
isActive = false;
$('li.sameas input').click(function(sender) {
var target = $(sender.target);
var selectedCountryValue = $('li.country select', target.closest('fieldset')).val();
// determine data method based on country selected
if (selectedCountryValue === "xxx") {
ShowAddress(true, target);
} else {
ShowAddress(false, target);
}
});
function kleberShowAddress(show, target) {
if (show) {
$('li.address').hide();
} else {
$('li.address').show();
}
}
});
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);
}
});
});
I am trying to do required validation in a asp.net page.
I have multiple controls that will be hidden and displayed.
Controls like checkboxlist,dropdownlist,multiselectedlistbox.
I am using a css class called required attaching to all these controls to check the validation.
I am trying to check if each control has value or not but my code is checking each options with in each controls.
I am really not finding a way not a jquery expert just a novice...
Here is my code any ideas anyone please....
$("input[type='submit']").click(function () {
if ($(this).val() != 'Back') {
var names = [];
var info=" ";
$('.required input').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
$('.required option').each(function () {
var control = $(this);
if (control.is(':enabled')) {
names[$(this).attr('name')] = true;
}
});
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if ((radio_buttons.filter(':checked').length == 0) ||(radio_buttons.filter(':selected').length == 0)) {
info += radio_buttons.closest("table").find('label').html()+"</br>";
}
}
if (info != " ") {
$("#validation_dialog p").html(info);
$("#validation_dialog").dialog({
title: "Validation Error!",
modal: true,
resizable: false,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
return false;
}
}
});
here is a fiddle for it...
http://jsfiddle.net/bDmgk/35/
I think what you want is:
$(".required input[type='radio']:checked").each(function(){
});
instead of :
$(".required option").each(function(){ ... });
Hi I made some changes to your fiddle basically I checked for the inputs inside each column like this and then I added them to your names array.
Using
$('table.required:eq(0) input:checked')
I you can got all the inputs that are checked on the first column if the lenght of the array returned is 0 then no input is checked, i't the same procedure for the other ones.
An yes those input names are weird.
Check this fiddle
JSFiddle
I have a very critical issue.
Below is my jsp code:
<html:select property="city" name="city" onchange="javascript:checkCity(this);">
<html:option value="N">NewYork</html:option>
<html:option value="F">France</html:option>
<html:option value="I">Italy</html:option>
<html:option value="P">Paris</html:option>
</html:select>
There can be single or multiple html select since my <html:select> is placed in for loop.
Below is my Javascript code:
var citySelected = new Array();
function checkCity(selObject)
{
var form = document.forms[0];
var cityObj = form["city"];
var len = cityObj.length;
if(selObject==cityObj) // if there is single <html:select> selObject is same as city Object.so this logic works fine
{
if(cityObj.value==cityObj.options[3].value)
{
alert("You have selected Paris City");
citySelected[0] = true;
}
if(!cityObj.options[3].selected && cityObj[0])
{
var result = confirm("You have selected cities other than paris");
if(result)
{
citySelected[0] = false;
}
else
{
cityObj.options[cityObj.options.selectedIndex].selected=false;
cityObj.options[3].selected=true;
}
}
}
else{
for(var i=0; i<len; i++) { //if there are multiple <html:select> then take length of form object n iterate
if (selObject == cityObj[i] )
{
if(cityObj[i].value==cityObj[i].options[3].value) // if 3rd option is selected
{
alert("You have selected Paris City");
citySelected[i] = true;
}
if(!sctypeObj[i].options[3].selected && citySelected[i]) //if 3rd option is deselected
{
var result = confirm("You have selected cities other than paris");
if(result)
{
cityObj[i] = false;
}
else
{
cityObj[i].options[cityObj[i].options.selectedIndex].selected=false;
cityObj[i].options[3].selected=true;
}
}
}
}
}
}
Below is Javascript which works on jsp onload():
function onload()
{
var form = document.forms[0];
var formObj = form["city"];
var size=formObj.size;
var len = formObj.length;
for(var i=0; i<len; i++) {
citySelected[i] = false;
}
if(size==0){ //if there is seingle <html:select> element
var cityvalue=formObj.value;
if(cityvalue=="P")
{
citySelected[0] = true;
}
}
else
{
for(var i=0; i<len; i++) { //if there are multiple <html:select> elements
var cityvalue=formObj[i].value;
if(cityvalue=="P")
{
citySelected[i] = true;
}
}
}
}
Here is where am finding problem. Onload if there is single or multiple <html:select> elements the logic works fine.But when there are no <html:select> elements at all in my jsp per say if I have option to delete all dropdowns then my jsp throws Javascript error:
"size is null or not an object".
How do I resolve this? In onload() function I am differentiating between <html:select> element using size.
if(size==0)
{
//logic for single <html:select>
}
else
{
//logic for multiple html select
}
But when there are no <html:select> elements at all in my jsp per say if I have option to delete all dropdowns then my jsp throws Javascript error:
"size is null or not an object".
How do I resolve this? Any help would be great..
An alternate way to determine the number of <select> elements within a form would be to use jQuery's selectors like so:
$('#myForm select').length // returns number of <select> elements in the form
You can use the fact that null/undefined evaluates to false in Javascript, like so:
if(!size)
{
//logic for single <html:select>
}
else
{
//logic for multiple html select
}
The line var size=formObj.size; could be the cause of the problem. Try using an "or" statement to prevent the error when the size attribute is null or undefined:
var size = formObj.size || 0;
If for single select element length is returning 4, then it seems that other select elements present inside jsp with the same name and those are hidden.
However, getElementByName('propertyName') is not a correct function to iterate collection type, rather we need getElementsByName('propertyName').
Use:
var formObj = document.getElelementsByName('city');
var length = formObj.length;
if(length == 0) {
// No select element
}
if(length == 1) {
// One select element
} else {
// More than one select elements
}
I am not sure how size will help here, this is not required. Size always will be returning undefined in this case.