Generalize a specialized JQuery function - javascript

This is a question about Multiple Checkbox Select/Deselect Using JQuery:
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/
which has the functionality of selecting multiple items from a list to process them. The Online Demo is at:
http://viralpatel.net/blogs/demo/jquery/multiple-checkbox-select-deselect/jquery-select-multiple-checkbox.html
I've extended the demo to include several groups, and have made the sample JQuery JavaScript function to work for one case, the BlackBerry one. The working code is at http://jsfiddle.net/jLx5z99q/3/.
In it, this is the specialized function that I want to generalize:
$(function () {
$("#BlackBerry").click(function () {
$('.case_blackberry').attr('checked', this.checked);
});
$(".case_blackberry").click(function () {
if ($(".case_blackberry").length == $(".case_blackberry:checked").length) {
$("#BlackBerry").attr("checked", "checked");
} else {
$("#BlackBerry").removeAttr("checked");
}
});
});
I want to generalize it so that the "#BlackBerry" and ".case_blackberry" are two parameters to the function, so that I can call it several times to cover other groups as well.
I'm not a JavaScript developer. Please help.
UPDATE:
I've posted the full working html source code at http://pastie.org/10278464.
Also, FYI, this full working html source code is generated automatically by easygen with this template. This html test code is the reason that I wrote easygen, to make it easy to write whatever test case whatever the way I like. Hope it will help someone else too.
Thanks

You need define some specific attributes.
Try this fiddle.
Example Fiddle:: http://jsfiddle.net/iboylmz/2acnLzzw/3/

This could work:
function bindMulti( parent, children ) {
parent.click(function () {
children.attr('checked', this.checked);
});
children.click(function () {
if (children.length == children.filter(':checked').length) {
parent.attr("checked", "checked");
} else {
parent.removeAttr("checked");
}
});
};
Use like this:
bindMulti($('#select_all'),$('.children'));
bindMulti($('#BlackBerry'),$('.case_blackberry'));

Maintaining your current's code logic and flow and element identification, you can do:
$(function () {
$(".case_subgroup_all").click(function () {
$('.case_'+$(this).attr('id').toLowerCase()).attr('checked', this.checked);
});
$(".case_blackberry").click(function () {
if ($(".case_blackberry").length == $(".case_blackberry:checked").length) {
$("#BlackBerry").attr("checked", "checked");
} else {
$("#BlackBerry").removeAttr("checked");
}
});
});
I've also added case_subgroup_all to your 'check all' checkboxes, in order to call your event handler.
jsfiddle: http://jsfiddle.net/jLx5z99q/5/

Related

.is(":checked") doesn't work in jQuery

I'm new to jQuery and I need to check if the checkbox is checked. In other posts I saw that I need to use .is(":checked") to solve it, but somehow it doesn't work.
$('.neutral').on('click', function() {
var checkbox = $(this);
if (checkbox.is(":checked")) {
console.log('checked');
} else {
console.log('unchecked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="neutral" />
In this code I have 2 problems and I don't know how to solve it.
When I'm using console.log('checked') outside of the if statement (after checkbox variable) and I click on the checkbox one time, console prints the result 2 times.
I don't know why this if statement doesn't working.
Thank you for your time and help.
checked happens after the change event,just replace click with change.
$('.neutral').on('change', function() {
var checkbox = $(this);
if (checkbox.is(":checked")) {
console.log('checked');
} else {
console.log('unchecked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="neutral" />
I have seen your code, I think you should try
$(document).on("click",".neutral",function() {
// Write code here
});
Instead of your code, Replace this code to as i written
$('.neutral').on('click', function() {
// Code here
});
For more undesirability see here
$(document).ready(function() {
// This WILL work because we are listening on the 'document',
// for a click on an element with an ID of #test-element
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
// This will NOT work because there is no '#test-element' ... yet
$("#test-element").on("click",function() {
alert("click bound directly to #test-element");
});
// Create the dynamic element '#test-element'
$('body').append('<div id="test-element">Click mee</div>');
});
Visit these link that may help you more for your implementation
Statck over flow link
jsFiddle Link

Textarea startswith function not working

I am trying to apply starts with function on textarea, but obviously I am doing something wrong. I don't understand javascript, so I am sorry for obvious mistakes or problems. At least I tried what seemed logical to me... Fiddle here: http://jsfiddle.net/SVxbW/235/
HTML:
$("textarea").bind(function () {
if ($(this).startsWith("Hello") {
$(".kuk").show();
}
else {
$(".kuk").hide();
}
});
.kuk {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<textarea></textarea>
<button class="kuk">Clear</button>
And what if someone pastes the text "Hello" with right click of mouse? How to recognize that action too?
You need to get the val() then use startsWith(). Additionally you need to bind proper event handler. Here I have used keyup
$("textarea").on('keyup', function() {
if ($(this).val().startsWith("Hello")) {
$(".kuk").show();
} else {
$(".kuk").hide();
}
});
Updated Fiddle
Try this. You need to bind an event also you need to get val to check whether it startswith hello or not.
$("textarea").bind('keyup',function () {
if ($(this).val().startsWith("Hello")) {
$(".kuk").show();
}
else {
$(".kuk").hide();
}
});
Here is jsfiddle
I made jsfiddle for those wondering which code I am using right now. I added few kinds of input options and now it works in chrome as well.
final fiddle
$("textarea").bind('change keyup paste blur input',function () {
if ($(this).val().startsWith("Hello") || $(this).val().startsWith("HELLO") || $(this).val().startsWith("hello")) {
$(".kuk").show();
}
else {
$(".kuk").hide();
}
});

Jquery rename content insite a tag and confirm it

The User should be able to change the Name and then confirm the change. I'm not able to archive it with this code as when I click confirm, it returns like before.
What am I missing?
Any better way to put this together (which I'm sure there's one) ?
Please check the demo where you can also see the changeElementTypefunction
http://jsfiddle.net/dLk6E/
js:
$('.replace').on('click', function () {
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').bind('click', function () {
$('.replace').show();
$('.confirm').hide();
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')) {
$(document).keypress(function (e) {
if (e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity', '1');
}
});
}
});
Here are your updated code and working fiddle http://jsfiddle.net/dLk6E/
(function($) {
$.fn.changeElementType = function(newType) {
var attrs = {};
$.each(this[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
this.replaceWith(function() {
return $("<" + newType + "/>", attrs).append($(this).contents());
});
}
})(jQuery);
$('.replace').on('click', function (){
$("h2").changeElementType("textarea");
$('.replace').hide();
$('.confirm').show();
//Confermation of the change
$('.confirm').on('click', function(){
$('.replace').show();
$('.confirm').hide();
// you are missing this
$('.replaceble').html($("textarea").val());
$("textarea").changeElementType("h2");
});
if ($('textarea:visible')){
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
$("textarea").changeElementType("h2");
$('.replace').css('opacity','1');
}
});
}
});
updated
jsfiddle.net/dLk6E/1
I think your code is right but you need to use the value you're entering when replacing it. So the confirmation binding would be something like this (fetching it, and then using it to update the textarea before "transforming" it into an h2 tag.
$('.confirm').bind('click', function(){
var valueEntered = $('textarea').val();
$('.replace').show();
$('.confirm').hide();
$("textarea").html(valueEntered).changeElementType("h2");
});
You could be using .on for this as well as of jQuery 1.7 is prefered to .bind.
Another thing I would suggest is whenever you struggle with something like this just put in google (or whatever...) exactly what you want, in this case "jquery get value of input" will get asw first result the jquery documentation
This way you won't forget it ;)
Update: Maybe a small detail but in the binding I use it would be more efficient to just hit $('textarea') once, so it would be something like this. Something that you may keep in mind (not really an issue here), better to store in a variable than hit the DOM several times.
$('.confirm').on('click', function(){
var $textarea = $('textarea');
$('.replace').show();
$('.confirm').hide();
$textarea.html($textarea.val()).changeElementType("h2");
});
jsfiddle

Correct jQuery to read from a select option

My script doesn't seem to be working correctly, what I'm trying to get is pretty self explanatory. I have tried several diffrent ways to make this work, searched around and tried to solve it.
I also tried to check the chrome log via console.log() but it didn't run the code through.
So if you know the solution to make it work I would appreciate the answer on how you solved it and what was wrong in the code.
NEW: The fiddle below includes the HTML.
jQuery(document).ready(function($){
$('#cart_review .quantity option :selected').change(function (event) {
$quan = $(this);
console.log($quan.parent().next()[0]);
$quan.parent().next().find('.price').text(function () {
return $quan.val() * parseInt($(this).attr('data-val'), 10) + ' kr';
});
var total = 0;
$('#cart_review .price').each(function(k, v){
total += parseFloat($(v).text(), 10);
});
$('#total').text(total + ' kr')
});
});
Check out this jfFiddle
Option does not have change event, select does. You need to Change the handler to:
$('#cart_review .quantity').change(function (event) {
//rest code
});
jfFiddle
use this
$('#cart_review .quantity').change(function (event) {
// your logic here
}
instead of
$('#cart_review .quantity option').change(function (event) {}
working fiddle
Hope this helps...
http://jsfiddle.net/uQ2F8/3/
$(function(){
$('select.quantity').change(function (event) {
Hey I just changed your selector, I think this is what you're trying to accomplish. I did it with the first one.

How to handle two unrelated events with jquery

I'm wondering if I can fire off both of these events together :
$("input[type=checkbox]").click(function(){
if($(this).is(":checked"))
{
//Value of checkbox
alert(this.value);
}
});
and
$("input[type= 'text']").keyup(function(){
alert(this.value);
});
I looked into .bind, but that seems to only work for one selected elements (i.e. $(p).bind("mouseout mouseenter).doSomething()).
The situation I am running into is that I have a function that needs to fire anytime either one of these things occur.
Try
$("input[type=checkbox],input[type='text']").on('click keyup', function(){
// code
});
Two ways you can achieve this as shown below:
using "on" method:
$(document).on('keyup click',"input[type=checkbox],input[type='text']", function(){
// Do stuff here..
})
Call function after the event.
$("input[type=checkbox]").click(doSomething);
$("input[type= 'text']").keyup(doSomething);
function doSomething() {
}
If you still need the additional if, you can use:
$("input[type=checkbox]").click(function(){
if($(this).is(":checked"))
{
//Value of checkbox
alert(this.value);
somethingHappened();
}
});
$("input[type= 'text']").keyup(function(){
alert(this.value);
somethingHappened();
});
function somethingHappened() {
// Do stuff
}
Perhaps all you need is a common function?
$("input[type=checkbox]").click(function(){
if($(this).is(":checked")) {
special(this.value);
}
});
$("input[type= 'text']").keyup(function(){
special(this.value);
});
function special(val) {
alert(val);
}
If your intent really is to invoke a function when any checkboxes/text fields across the whole page changes, you probably want something like this:
$('body').on('change', ':checkbox,:text', function () {
});
Note that the :checkbox and :text selectors are much nicer than input[type=checkbox] etc.

Categories