jquery How to access only checked checkbox? - javascript

I have a div which contains 7 checkboxes , i wrote this following code for accessing only the checked checkbox into the array icons
var icons = $("div").find("input[type=checkbox]").each(function () {
if($(this).attr("checked") == "checked") return this; });
alert(icons.length);
but it always alert 7 .Can anybody tell me the problem?

var icons = $("div").find("input[type=checkbox]:checked");

the easiest way is to assign a class to target inputs and use checked selector, see an example below:
var icons = $('.box:checked');

Hiya demo http://jsfiddle.net/KzMqB/
You probably just need to check once using :checked and it will give you what you are looking for.
good read: http://api.jquery.com/checked-selector/
Hope this helps!
code
var icons = $("div").find("input[type=checkbox]:checked").each(function() {
alert("ID of checked checkbox = " + $(this).attr("id"));
});

You can use $.map,
$(document).ready(function() {
var checks = $.map($("div").find('input[type="checkbox"]:checked'),function(arr){
return arr;
})
console.log(checks.length);
})
or your method,
$(document).ready(function() {
var checks = $.each($("div").find('input[type="checkbox"]:checked'),function(){
return this;
})
console.log(checks.length);
})

var icons= $("div").find("input:checked").length;
alert(icons);

Related

Populating a jquery array from values of a select using each

I'm trying to populate an array in Jquery with selected values from a select.
Here is my jquery (no ajax call because I first want to make the array before i call ajax to input fields into db)
$('#add-group-form').submit(function(e) {
e.preventDefault();
var contactsArr = [];
$("select option").each(function(i, val){
var $val = $(val);
if($(i).attr('selected', 'selected')){
contactsArr.push({value: $val.val()});
}
});
console.log(contactsArr);
});
Now in all honesty i got the each from a different source.
Not sure how i check the attribute to make sure it is selected.
Thanks in advance for the help
**EDIT:
Okay so I may have forgotten to check for answers as I got distracted by trying to figure it out
This is how I've done it (tested and works in my system).
var contactsArr = [];
$(".edit-contact-select option:selected").each(function() {
contactsArr.push({value: $(this).val()});
});
I was over-complicating the entire thing.
you don't need to iterate through options for the "selected" one. use this instead:
$('#add-group-form').submit(function(e) {
e.preventDefault();
var contactsArr = [];
$('select').each(function(){
contactsArr.push({value: $(this).val()});
});
console.log(contactsArr);
});
$('select').val() actually returns the SELECTED value of the select input.
hope that helps.
Looks like you have a multiple select if so you can use .val() to get the selected values in an array
$('#add-group-form').submit(function (e) {
e.preventDefault();
var contactsArr = $("select").val();
console.log(contactsArr);
});
If you want to store the selected values from multiple select elements, then use .map() like
$('#add-group-form').submit(function (e) {
e.preventDefault();
var contactsArr = $("select").map(function (i, val) {
return $(this).val()
}).get();
console.log(contactsArr);
});

Jquery change color condition

Hi everyone I have an issue with Jquery :
I have a multiple selection and the user can select one thing and it will copy the text into an input above. I would like that the text in the multiple selection that will be copied become red if the button is clicked so did you understand? I don't know how to do condition in Jquery, here is what I have done :
$(document).ready(function(){
if ($choose = true)
{
$("ok").click(function(){
$("droite").css({"background-color":"yellow"});
}
});
});
droite is an id and no it's not working but I would like to know how it works
choose is a function here it is :
var choose = function(bouton){
var lesoptions = $('#droite').find(":selected");
//lesoptions.remove();
$('#numLot').val(lesoptions[0].text);
};
Can I have your opinion ?
thanks
$("ok") is wrong. it should be $("#ok") or $(".ok") or whatever.
compare operator is == instead =
Try to use like below,
var $Choose;
//Assign value to $Choose as like true or false
$(document).ready(function(){
if ($choose)
{
//If you have id like ok use "#" or if class use "." instead
$("#ok").click(function(){
$("#droite").css({"background-color":"yellow"});
});
}
});
Hope this helps...
You have to use . selector before class names and # before id names.
Read about selectors: jQuery Selectors
Since choose is a function so, you will have to return something and check if it returns true/false. So make your function like this:
function choose(bouton){
var something = /*your return value*/; //Put your return value here
var lesoptions = $('#droite').find(":selected");
$('#numLot').val(lesoptions[0].text);
return something; //something is what you want to be returned by function
};
If $choose is not defined while you are putting it in if condition then you will not get proper working.
If #ok is added dynamically then use delegation using .on.
You should put code like this:
$(document).ready(function(){
var $choose = choose(bouton);
if ($choose)
{
$("#ok").on("click",function(){ //Again not mentioned what is ok, still like you told I assume it id
$("#droite").css("background-color","yellow");
});
}
});

Jquery Show Input Text Based On Input Value

I facing problem with my jquery, on showing input text based on input value.
Here is the JS fiddle demo :
http://jsfiddle.net/Ltapp/364/
When I try to input #hotmail, the input box will show. But when I want to type some text in the #hotm input box, it will hide again.
JS code :
$(window).load(function(){
var myString = '#hotmail';
$('#hotm').hide();
$("input").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
});
It's because your selector $("input") affects both input elements. I have updated it to the $("input:first") selector instead. JsFiddle here
$("input:first").keyup(function () {
var value = $(this).val();
if(value.match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
As many has said, you are binding the event on all the inputs I did a little change:
$(function(){
var myString = /#hotmail/ig;
$("#check").bind('keyup checkvalue', function() {
$('#hotm')[myString.test(this.value) ? 'show' : 'hide']();
}).trigger('checkvalue');
});
using regex if you are using #HoTmAil it will also hit on that, and also added a custom event checkvalue to see if #hotm should be visible on for example a postback on the form you might be using.
demo: http://jsfiddle.net/voigtan/xjwvT/1/
You're affecting all inputs. Either give each one a unique ID / Class or use the jQuery $(this) method.
See JSFiddle Here:
http://jsfiddle.net/Ltapp/366/
<input type="text" id="firstinput"/>
<p id="secondinput"><input type="text"/></p>
var myString = '#hotmail';
$('#secondinput').hide();
$("#firstinput").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#secondinput').show();
} else {
$('#secondinput').hide();
}
});
use this for your if part :
if($(this).val().match($(this).val().substr(0,strlen($(this).val())))
it's because the new box also = "input"; if you give the hotmail textbox it's own id, it won't hide
<input id="hotmail" type="text"/>
and then
$("#hotmail").keyup(function () {...});

JQuery - Output the class name of checked checkboxes

I am wondering whether or not it is possible to output the class name of checked checkboxes each time a checkbox is checked/unchecked? For example, I have 3 checkboxes. If I check one, it'll output its class name, if I then check a 2nd one it'll output the first checkbox class name + the 2nd class name. If I then uncheck the first checkbox, it'll only output the class name of the 2nd checkbox.. and so forth? I made a JSFiddle to get started... http://jsfiddle.net/LUtJF/
Thanks
$("input[type='checkbox']").change(function() {
var classes = $("input[type='checkbox']:checked").map(function() {
return this.className;
}).get().join(",");
alert(classes);
});
Your fiddle, fiddled with.
Check this fiddle: http://jsfiddle.net/eUse5/
Code:
function showChecked() {
var s = '';
$('input:checked').each(function() {
if(s!='') s += ', ';
s += $(this).attr('class');
});
alert(s);
}
$('input[type="checkbox"]').change(showChecked);
$(document).ready(function() {
var cb = $('input[type=checkbox]');
cb.change(function() {
cb.each(function() {
if ($(this).is(':checked')) {
alert($(this).attr('class'));
}
});
});
});
It can be done like
$(":checkbox").click(function(){
var classes = "";
$(':checked[class]').each(function(){ // this will filter only checked checkbox having class attribute
classes += " "+$(this).attr("class");
});
alert(classes);
});
fiddle: http://jsfiddle.net/LUtJF/7/

How to build a simple table filter with jQuery?

How can I build a simple table filter with good effect using jQuery? I don't mind about pagination.
list -> select data of database.
I do not want to use a plugin, I prefer the use of short code.
Example:
$('#inputFilter').keyup(function() {
var that = this;
$.each($('tr'),
function(i, val) {
if ($(val).text().indexOf($(that).val()) == -1) {
$('tr').eq(i).hide();
} else {
$('tr').eq(i).show();
}
});
});
CHECH THIS
I don't normally help out with this, but I got bored this morning..
http://jsfiddle.net/hHJxP/
I know it's kinda late but hope this code helps.
<script>
$(document).ready(function(){
$("#yourInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#yourTableId tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
Try testing the innerHTML of the row to the value of the input field, showing / hiding the content depending on the test-result.
$('#test').bind('keyup', function() {
var s = new RegExp(this.value);
$('tr').each(function() {
if(s.test(this.innerHTML)) $(this).show();
else $(this).hide();
});
});
JSFIDDLE with example table and input field.
edit
It might be better to use .text() instead of innerHTML. Performancewise innerHTML would be better, but .text() doesn't accept the html-tags as valid search results. JSFIDDLE #2.

Categories