I have a JavaScript program that isn't properly functioning. For some reasons before it appends what it is actually getting from the checked radio box it appends three times with noting in the append except the styling. I'm not sure what I'm doing wrong.
$(document).delegate('#add-owner', 'pageinit', function () {
loadOwners();
$('#add-owner-save').bind('click', function () {
var permission = $('#editing-permissions option:selected').text();
var selection = $("input[type='radio']:checked") || [];
if (selection.length > 0) {
for (var i = 0; i < selection.length; i++) {
console.log($('#label-' + selection[i].id).find('.owner-name').text());
console.log($("input[type='radio']:checked").val());
$('.display-owners').append('<div class="ui-grid-a"><div class="ui-block-a">' + $('#label-' + selection[i].id).find('.owner-name').text() + '</div><div class="ui-block-b" style="text-align:right">' + permission + '</div></div>');
}
$('.display-owners').trigger('create');
}
$('.display-owners').show();
$('#add-owner').dialog('close');
$('input[name=contribute-radio]').attr('checked', false).checkboxradio("refresh");
return false;
});
});
I think the problem is that I have multiple radio areas on this page. How do I specify that I just want these radio buttons are the ones I want it to checked?
This code:
... + $('#label-' + selection[i].id).find('...
should be like this:
... + $('#label-' + selection[i].attr('id')).find('...
because what you have in selection array are jQuery objects, not DOM elements objects.
Thanks Esalija for pointing out my assumption was not correct.
Since said you have multiple sets of radio buttons, the selector you're using is finding all of them on the page so that is why you have multiple "checked" radio buttons.
This:
var selection = $("input[type='radio']:checked") || [];
To this:
var selection = $("input[name='radioset1']:checked") || [];
Then just name each radio set different and replace "radioset1" with the set you need for this one.
Related
This is a follow-up to my previous question: Multiple checkbox filter: how to get both and additive and subtractive effect
Many thanks to everyone who helped me in my previous question. Basically, I want to make checkboxes that hide and show div items based on what class(es) they have. The filters are separated into two categories, with two options within each category: citiesFilter (hamiltonFilter + torontoFilter) and costFilter (cheapEatsFilter + costFilter).
Checking two boxes within each category should increase the number of <div> elements that appear (i.e. clicking 'hamiltonFilter' and 'torontoFilter' should show <div> elements that have either class)
Checking two boxes between two categories should narrow the number of <div> elements that appear (i.e. clicking 'hamiltonFilter' and 'cheapEatsFilter' should ONLY show <div> elements that have BOTH classes)
The previous answers work, but only within each category; it doesn't narrow the results when I click 'hamiltonFilter' and 'cheapEatsFilter', rather it shows me all <div> elements with either class. I tried modifying their code but cannot figure out how to select for <div> elements with both classes.
https://jsfiddle.net/de1zc7vx/1/
edit: put in the wrong jfiddle
$(document).ready(function() {
$('#checkboxFilterContainer').find('input:checkbox').on("change", function() {
var $citiesIDs, $costIDs = [];
var $citiesCategory = $('#citiesFilterContainer').find('input:checked');
var $costCategory = $('#costFilterContainer').find('input:checked');
$citiesCategory.each(function(index, element) {
$citiesIDs.push(element.getAttribute('id'));
});
$costCategory.each(function(index, element) {
$costIDs.push(element.getAttribute('id'));
});
var $totalLength = ($citiesIDs.length + $costIDs.length);
if ($totalLength == 0) {
$('.blogpost').removeClass('hide');
} else {
$('.blogpost').addClass('hide');
for(i = 0; i < $totalLength; i++) {
var x = $citiesIDs[i];
var y = $costIDs[i];
var xClass = $('.' + x);
var yClass = $('.' + y);
$('.x.y').removeClass('hide');
}
}
})
})
Add the hide class to all the posts
Make an OR selector for the selected cities (.firstId,.secondId,...)
Make an OR selector for the selected costs
If city ids were given, filter the posts by that OR selector
If cost ids were given, filter further (or for the first time) by that OR selector
For all the posts remaining, remove the hide class
var $filteredPosts = $('.blogpost').addClass('hide');
if ($totalLength) {
var citiesOrSelector = '.'+ $citiesIDs.join(',.');
var costsOrSelector = '.'+ $costIDs.join(',.');
if ($citiesIDs.length) $filteredPosts = $filteredPosts.filter(citiesOrSelector);
if ($costIDs.length) $filteredPosts = $filteredPosts.filter(costsOrSelector);
}
$filteredPosts.removeClass('hide');
I am trying to create several checkboxradio buttons groups in jQuery mobile that depend on a limit checkboxradio button group value. For example if a limit of 6 is selected I want to only allow the user to be able to select up to a total of 6 children based on all of the other checkboxradio button group selected values and disable everything else. When the limit changes I want to update the UI accordingly.
I have the following code in my change event handler whenever any of the checkboxradio buttons are clicks:
function updateUI(element) {
var limit = parseInt($('input[name="Limit_Total"]:checked').val(), 10);
// Children
var childCount = parseInt($('input[name="Child_Total"]:checked').val(), 10);
var secondChildCount = parseInt($('input[name="Second_Child_Total"]:checked').val(), 10);
var thirdChildCount = parseInt($('input[name="Third_Child_Total"]:checked').val(), 10);
var fourthChildCount = parseInt($('input[name="Fourth_Child_Total"]:checked').val(), 10);
var fifthChildCount = parseInt($('input[name="Fifth_Child_Total"]:checked').val(), 10);
// Totals
var totalChildern = childCount + secondChildCount + thirdChildCount + fourthChildCount + fifthChildCount;
// Enable the correct combination of children
$('input[name*="Child_Total"]').not(element).checkboxradio('disable').checkboxradio('refresh');
for (var i = 0; i <= 6; i++) {
if (i <= (limit - totalChildren)) {
$('input[id$="Child_Total_' + i + '"]').not(element).checkboxradio('enable').checkboxradio('refresh');
} else {
$('input[id$="Child_Total_' + i + '"]').not(element).attr('checked', false).checkboxradio('refresh');
}
}
}
I basically want to simulate the behavior illustrated in the image below:
The problem is it doesn't quite give me the behavior I want. It deselects all but the button I select within the group. I am trying to figure out the most efficient way to do this but I am having a hard time. Any suggestions or help would be greatly appreciated!
I have setup the following jsfiddle to demonstrate the UI: http://jsfiddle.net/X8swt/29/
I managed to solve my problem with the following function:
$('div fieldset').each(function() {
// Disable all none checked inputs
$(this).find('input:not(:checked)').checkboxradio().checkboxradio("disable").checkboxradio("refresh");
// Grab the selected input
var selectedElement = $(this).find('input:checked');
// Calculate the remaining children that can be selected
var remaining = (limit - totalChildern);
// Enable all inputs less than the selected input
$.each($(selectedElement).parent().prevAll().find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
// Enable up to the remaining boxes past the selected input
$.each($(selectedElement).parent().nextAll().slice(0,remaining).find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
});
Please feel free to comment or critique my solution.
On a webpage I give the user the option of hiding table elements (which contain checkboxes) like this:
mytable.style.display = 'none'; //the table and the enclosed textbox is hidden
I am now trying to find all of the tables that are not hidden like this:
var frm = document.forms[0];
var arrayDisposals;
var intCount;
var arrayDisposals = new Array();
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox" && frm.elements[i].name.substr(0, 3) == "Del") {
if ('none' != frm.elements[i].style.display) {
{
arrayDisposals.push(frm.elements[i].id + '|' + frm.elements[i].checked)
}
}
}
The problem is that the second IF statement does not work i.e. all elements are added to the array. How do I only add checkboxes that are not hidden?
If you were looking for a jQuery solution this should suffice. Use .map()
var arrayDisposals = $('input[type="checkbox"][name*="Del"]:visible').map(function(){
return this.id+ "|" + this.checked
}).get();
Use attribute selector to find checkboxes and where the name contains "Del" and :visible to check if it is not hidden.
DEMO
Is there a way to get the value of an :input in jQuery that holds for all :input?
I am asking this because I have a page with select and checkbox, it is for the following code:
for (var i = 0; i < arguments.length; i++) {
var localArgument = arguments[i].trim();
data[localArgument] = $(html).find(":input[name='" + localArgument + "']").val();
$(html).on("change", ":input[name='" + localArgument + "']", function(event) {
console.log(localArgument + ": " + $(this).val());
data[localArgument] = $(this).val();
reloadTable(table, html, data);
});
}
Where arguments is an array that holds names for elements.
I know I need to do it for checkbox with .prop("checked"), however I would much rather use a general function which I know does not need to be updated in the future.
just use $('input') selector to select all input elements
If you want to get the value of each input element you can do something like
$('input').each(function() {
// use $(this).val() to get the value
})
You can safely use val() for all inputs, checkboxes, radio buttons, and selects. This is a demo: http://jsfiddle.net/FxjQB/3
The is(:focus) was the aproach. The final code is listed below:
setInterval(function(){
if($j("SELECT[name='cf20_field_7']").is(":focus")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").val();
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
hovered = true;
}
,100
);
Is there some possibility to fire function when there is no hover in SELECT field.
And also there may be aproach that to check is there is no hover on SELECT field.
It cause problemms. When you are trying to select another option cursor is begging while setInterval is working.
The best approach that i find is listed below:
//every 100 mil secconds update info
setInterval(function(){
$j("SELECT[name='cf20_field_7']").trigger('change');
if ( $j("SELECT[name='cf20_field_7']").on("change")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").attr("value");
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
}
,100
);
More information:
I can discribe situation more. So i had a form. onsubmit event didn`t work because there is another event is attachet. So i deside to update value of first field of form every 100 milisecs. The value is containing all dynamictly created "selects and inputs". But when i try to change value of the select by mouse. The function is fired and function check value of select and cause mouse begging. So i need somehow to check if that select is hovered to prevent firing of the function.
Invalid here:
if ( SELECT[name='cf20_field_7'].on("change"))
I guess you need this:
if ( $("SELECT[name='cf20_field_7']").on("change"))
But still, the above is invalid. You need some handler like:
$("SELECT[name='cf20_field_7']").on("change", function(){
return false;
});
if ($j("SELECT[name='cf20_field_7']").on("change")) return false
Not clear what should be checked here. I assume you want to run some function attached to onchange even of select. In that case you should use .trigger instead of .on. But in both cases return value will be jquery object (for chaining purposes) so basically your statement will always be true both with trigger and on If you want to test some value of select, you should do something like next:
if(someTestFunct($j("SELECT[name='cf20_field_7']"))) return false;
function someTestFunct(jObj) {
//some other code?
return jObj.val() == "some value to test";
}
Possibly some better approach may be used, but without more details it is hard to suggest something.