Varying ID's, One JQuery Function - javascript

I have to use ID instead of something repeatable like class, just because of the way the plugin I'm calling works. So below, I am having to create two different functions in order to force the bootstrapValidator in a particular field upon clicking a checkbox. I can't use something like
'revalidateField', 'availmon[] || availtue[]'
but is there some other method or variable I can use so I'm not doing this same function 7x?
Here is a JSFiddle with all of the external resources attached for seeing what I'm actually doing.
$(function () {
$('#checkallmon').on('click', function () {
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
$('#app').bootstrapValidator('revalidateField', 'availmon[]');
});
});
$(function () {
$('#checkalltue').on('click', function () {
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
$('#app').bootstrapValidator('revalidateField', 'availtue[]');
});
});

And if you do something like this:
$(function() {
$(".checkall").on('click', function() {
var elem = $(this);
var validationRule = elem.data('validation-rule');
elem.closest('fieldset').find(':checkbox').prop('checked', this.checked);
$('#app').bootstrapValidator('revalidateField', validationRule+'[]');
});
});
And in the HTML you do it like this:
<label class="checkbox-inline preferred">
<input type="checkbox" id="checkallmon" class="checkall" name="availmon[]" data-validation-rule="availmon" value="open">Fully Available
</label>
Didn't try this, but it should work. So it's bound to a class (used your checkall class) and the function gets the validation rule from the data attribute validation-rule. So you just have to assign checkall as class and data-validation-rule with the name of the rule to any checkbox.
You could also use the .attr('name') to use the name as "rule", but in my opinion the data attribute is a much cleaner way.
I hope I understood your question in the right way.

Related

Is there an opposite of keyword this?

Is there a keyword that is opposite to the keyword this?
$('.lt-buttonContainer button').click(function () {
var $this = $(this);
$this.addClass("button1Clicked");
$!this.removeClass("button1Clicked");
})
There is no built in method to get all the other elements. Use not() to remove it from the collection.
var buttons = $('.lt-buttonContainer button');
buttons.click(function () {
var $this = $(this);
$this.addClass("button1Clicked");
buttons.not($this).removeClass("button1Clicked");
});
No, there is not a keyword that is the opposite of this in your context.
!this simply takes the logical not of the value of this which will not solve the problem in your code.
Your question could really stand for some clarification, but in your specific example, if you want all elements that were in the original collection, but are not the current value of this and that' what you meant by opposite, then you have to compute that collection yourself.
That could be accomplished like this:
$('.lt-buttonContainer button').click(function () {
$('.lt-buttonContainer button').removeClass("button1Clicked");
$(this).addClass("button1Clicked");
});
Or, if you really want a collection of the elements in the original collection that are not this, then you can do this:
$('.lt-buttonContainer button').click(function () {
$('.lt-buttonContainer button').not(this).removeClass("button1Clicked");
$(this).addClass("button1Clicked");
});
though the extra .not() operation in this second code snippet is not required in this specific case because it does no harm to .removeClass() from all objects in the collection before adding it back on one.
Does following snippet help ?
$('.lt-buttonContainer button').click(function () {
var $this = $(this);
$('.lt-buttonContainer button').removeClass ("button1Clicked");
$this.addClass("button1Clicked");
})
You could use toggleClass() jq method and delegate event using following logic:
$('.lt-buttonContainer').on('click', 'button:not(.button1Clicked)', function (e) {
$(e.delegateTarget).find('button.button1Clicked').add(this).toggleClass("button1Clicked");
});
And if elements button are siblings:
$('.lt-buttonContainer').on('click', 'button:not(.button1Clicked)', function () {
$(this).siblings('button.button1Clicked').add(this).toggleClass("button1Clicked");
});

Add onclick to element, but keep current onclick event

Is it possible to add a javascript event to a DOM element that already has a onclick event, but I want to keep that event property.
I have radio buttons like this:
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this);" />
in which I want to add
window.location.href=window.location.href
while keeping the original onclick, but I have no access to the html, I can only modify through javascript.
so my desired code will be
<input type="radio" name="checkout-payment" value="56" id="checkout-payment-56" class="checkout-radio checkout-payment-radio checkout-payment-radio" onclick="paymentChanged(this); window.location.href=window.location.href" />
Wrap the
window.location.href=window.location.href
in function, lets call it
onRadioButtonClick()
then, just do
var self = this; //keep the context of the file
$("[name=checkout-payment]").on('click', function () {
onRadioButtonClick.call(self); //call the method with the normal context.
//continue code..
});
You could try:
var curHandler = $('#checkout-payment-56').attr("onclick");
$('#checkout-payment-56')[0].onclick = null;
$('#checkout-payment-56').click(function () {
window.location.href=window.location.href;
});
I actually found out there was a much simpler way to acheive my desired result.
$( '.webshop-checkout input[type="radio"]' ).click(function() {
location.reload(true);
});
i am sorry i was not clear in my original post, and it has been edited.
If you want to add this to every .webshop-checkout input[type="radio"], you could do it that way:
$('.webshop-checkout input[type="radio"]').click(function(){
window.location.href=window.location.href;
});
JS Fiddle Demo
$("#checkout-payment-56" ).bind( "click", function(evt) {
console.log('that works');
//sessionStorage.setItem(evt.target.id,evt.target.className);
});

Working With checkboxes in the web pages

I have group of checkboxes and that are compulsory to be applied but the situation is user can be able to check only one check box at a time. So, for this I have implemented something like this with the help of internet. No doubt it works fine when there are no checkbox checked by default. But suppose, one of the checkbox is checked true when page loads, then this does not works unitl I click on checkbox twice.
Here is what I am using::
So , Assuming I have set of 5 checkboxes, I set same class name for all the checkboxes and then
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
In View page I have declared::
function Checkme(class_Name) {
Check_OR_Uncheck(class_Name);
}
In Common js::
function Check_OR_Uncheck(class_Name) {
$("." + class_Name).click(function () {
if ($(this)[0].checked) {
$("." + class_Name).each(function () {
$(this)[0].checked = false;
});
$(this)[0].checked = true;
}
else {
$(this)[0].checked = false;
}
});
}
Please Help me to achieve this..
Keep your code in the document ready event. This will register the click event for "myclass".
$(".myclass").click(function () {
if ($(this)[0].checked) {
$(".myclass").each(function () {
$(this)[0].checked = false;
});
$(this)[0].checked = true;
} else {
$(this)[0].checked = false;
}
});
jsfiddle
You could use document ready handler and call method:
jsFiddle
$(function(){
$(':checkbox:checked').each(function(){
Checkme(this.className);
});
});
Try this
$(function(){
$('.myclass').click(function(){
var s=$(this).prop('checked');
if(s==true)
{
$('.myclass').prop('checked',false)
$(this).prop('checked',true)
}
});
});
Or
You simply can use
if(s==true)
{
$(this).siblings().prop('checked',false);
}
FIDDLE
Try this
$(function(){
$('input:checkbox').prop('checked', false)
$('input:checkbox').click(function(){
if($(this).is(':checked')){
$('input:checkbox').not(this).prop('checked', false);
}
});
})
Instead of implementing a group of check boxes that behave like a group of radio buttons, I suggest implementing a group of radio buttons that look like a group of check boxes:
input[type=radio] {content:url(mycheckbox.png)}
input[type=radio]:checked {content:url(mycheckbox-checked.png)}
This approach simplifies your implementation; you have two one-line CSS rules instead of a JS event handler function, event binding (on both document ready and the HTML element itself), not to mention a possible dependency on jQuery (if you choose to use it).
The catch to this approach is that it requires CSS3 support. For more info, check out this SO answer: https://stackoverflow.com/a/279510/2503516

Get Closest Form to an Element in jQuery

I have this js/jquery script i wrote to check all checboxes with in a form. It works well but this checks all checkboxes that are on page irrespective of the form wrapper they are.
here is the function
function toggleCheck(state)
{ var checkboxes = jQuery("form input:checkbox");
if(state==true){checkboxes.prop('checked',true); }
if(state==false){ checkboxes.prop('checked',false); }
}
usage
<a id="check" href="#" onclick="javascript:toggleCheck(true);" class="btn">Select All</a>
<a id="uncheck" href="#" onclick="javascript:toggleCheck(false);" class="btn">Deselect All</a>
Note this works well but my problem is if i have
<form action="myaction-page">//some form elements and checkboxes </form>
and
<form action="myaction-page-2">//some form elements and checkboxes </form>
and i click the check all link in form1, all checkboxes gets check including those in form2.
Is there a way to separate them without introducing form ids or names?..this is because i have used it extensively in production code and to rewrite all will be trouble.
Any Help will be greatly appreciated.
P.S it is worth noting that the select all and deselect all are within both forms and both forms are on the same page.
Assuming your select/deselect links are inside the form, do:
function toggleCheck(state,elem) {
jQuery(elem).closest("form").find("input:checkbox").prop('checked', state);
}
And change your link JS to (passing the appropriate true/false parameter):
onclick="javascript:toggleCheck(false,this);"
jsFiddle example
The answer is: it depends on your DOM. If your <a> elements are inside the form, you could use $.closest():
function toggleCheck(state) {
$(this)
.closest("form")
.find("input[type=checkbox]")
.prop('checked', state);
}
I slightly altered your code to increase readability, performance (see the additional notes regarding the :checkbox selector) and be more "jQuery"-like.
[edit]
After reading the comments I rewrote the function, still on the assumption that the <a> elements are inside the <form>, this time also with a working jsFiddle:
function toggleCheck(state) {
$(document).find(event.target)
.closest("form")
.find("input[type=checkbox]")
.prop('checked', state);
}
[edit2]
And for the sake of completness regarding my comment about the order of the elements (jsFiddle):
function toggleCheck(state) {
var pos = $(document).find(event.target.localName + "." + event.target.className).index(event.target);
var $form = $($(document).find("form").get(Math.floor(pos/2)));
$form
.find("input[type=checkbox]")
.prop('checked', state)
}
[edit3]
The last edit, I promise. This time I ignore the default callback and do my own thing:
function toggleCheck(state) {
// either write the s tate now in a variable for
// the next callback
}
$(document).on("click", "a.btn", function(e) {
var $ele = $(this);
// or do some string exploration
var toggle = $ele.attr("onclick").indexOf("true") > -1;
var pos = $(document).find("a.btn").index($ele);
var $form = $($(document).find("form").get(Math.floor(pos/2)));
$form
.find("input[type=checkbox]")
.prop('checked', toggle);
});
Works without having to touch anything. But I wouldn't want to use this. ;-)
the .closest method will do what you want.
onclick:
onclick="toggleCheck.call(this,true);"
js:
function toggleCheck(state) {
var checkboxes = jQuery(this).closest("form").find("input:checkbox");
checkboxes.prop('checked',state || false);
}
You can also just apply a data-target to your anchors and eval based on the action of your form elements:
... data-target='myaction-page' ...
... checkboxes[i].form.getAttribute( 'action' ) ...
Shown in detail on this JSFiddle

Prototype event handler

I've defined the following HTML elements
<span class="toggle-arrow">▼</span>
<span class="toggle-arrow" style="display:none;">▶</span>
When I click on one of the elements the visibility of both should be toggled. I tried the following Prototype code:
$$('.toggle-arrow').each(function(element) {
element.observe('click', function() {
$(element).toggle();
});
});
but it doesn't work. I know everything would be much simpler if I used jQuery, but unfortunately this is not an option:
Instead of iterating through all arrows in the collection, you can use the invoke method, to bind the event handlers, as well as toggling them. Here's an example:
var arrows = $$('.toggle-arrow');
arrows.invoke("observe", "click", function () {
arrows.invoke("toggle");
});
DEMO: http://jsfiddle.net/ddMn4/
I realize this is not quite what you're asking for, but consider something like this:
<div class="toggle-arrow-container">
<span class="toggle-arrow" style="color: pink;">▶</span>
<span class="toggle-arrow" style="display:none; color: orange;">▶</span>
</div>
document.on('click', '.toggle-arrow-container .toggle-arrow', function(event, el) {
var buddies = el.up('.toggle-arrow-container').select('.toggle-arrow');
buddies.invoke('toggle');
});
This will allow you to have multiple "toggle sets" on the page. Check out the fiddle: http://jsfiddle.net/nDppd/
Hope this helps on your Prototype adventure.
Off the cuff:
function toggleArrows(e) {
e.stop();
// first discover clicked arow
var clickedArrow = e.findElement();
// second hide all arrows
$$('.toggle-arrow').invoke('hide');
// third find arrow that wasn't clicked
var arw = $$('.toggle-arrow').find(function(a) {
return a.identify() != clickedArrow.identify();
});
// fourth complete the toggle
if(arw)
arw.show();
}
Wire the toggle arrow function in document loaded event like this
document.on('click','.toggle-arrow', toggleArrows.bindAsEventListener());
That's it, however you would have more success if you took advantage of two css classes of: arrow and arrow-selected. Then you could easily write your selector using these class names to invoke your hide/show "toggle" with something like:
function toggleArrows(e) {
e.stop();
$$('.toggle-arrow').invoke('hide');
var arw = $$('.toggle-arrow').reject(function(r) {
r.hasClassName('arrow-selected'); });
$$('.arrow-selected').invoke('removeClassName', 'arrow-selected');
arw.show();
arw.addClassName('arrow-selected');
}

Categories