I'm trying to figure out a way to verify an ID from a button being clicked, does not already exist in a set of inputs.
Code that gets ID from button clicked
$(".detail-view button").on("click", function() {
var detailID = $(this).attr('id');
Code that checks ID doesn't exist
function itemExists() {
$("input#lunchorder_item_entry_id").each(function() {
existingID = $(this).val();
if(detailID == existingID) {
alert("You have already added this item. If you want to change item details, please remove the item and re-add it to your cart. Thank You!");
} else {
}
});
}
The issue I'm having this only works part of the time, if anyone has a suggestion on a better way to do this I'm sure this isn't the best way to achieve my goal. Thank you!
detailID isn't visible in your itemExists() function, either make it global, or pass it to the function.
itemExists(detailID){
// if(detailID == existingID) {
}
The whole this should look something like this
$(".detail-view button").on("click", function() {
var detailID = $(this).attr('id');
itemExists(detailID);
});
function itemExists(detailID) {
$("input#lunchorder_item_entry_id").each(function() {
var existingID = $(this).val();
if(detailID == existingID) {
alert("You have already added this item. If you want to change item details, please remove the item and re-add it to your cart. Thank You!");
} else {
}
});
}
Related
$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
var i;
for (i = 0; i < calloutArray.category.length; i++) {
$(this).hide();
if (checkboxName === calloutArray.category[i]) {
$(this).show();
}
}
});
}
});
});
To explain this function it basically listens to see if a checkbox has been clicked and then hides all the callouts on the page.
It then loops through each one of those checkboxes and checks which ones are true on the page. I then create a variable that stores the current checkbox value.
After this I then want to loop through each callout and pull its data from a data attribute.
I then loop through each string in the array and hide the callout no matter what. However if the callout has an array value that is the same as the checkbox value then I need to show it.
This seems to be working without the hide. However I need to hide the callouts if they do not hold the same checked category names which is where I'm running into problems.
The If statement seems to never return true if I have already hidden the callout. So the question is how do I show the callout if the selected checkboxes match one of the callout array strings but hide the callout if the string is not in the callout array.
From what I've understand, the following code is equivalent
$('.checkbox').on('change', function () {
$('.pagination, .callout').hide();
$('.checkbox:checked').each(function () {
var checkboxName = $(this).val();
$('.callout').hide().each(function () {
var calloutArray = $(this).data();
if (calloutArray.category.indexOf(checkboxName) !== -1) {
$(this).show();
}
});
});
});
Merge selectors having common actions(hide())
Use :checked pseudo-selector to select only checked elements
Use hide() on selector and then iterate over it using each()
Use indexOf to check if element is in array
You're showing/hiding your element on each iteration of the loop. That means the result of the last iteration wins, as though you hadn't done the earlier ones at all.
You can just use Array#indexOf to see if the name is in the array, and use the resulting flag to show/hide the callout:
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
E.g.:
$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
});
}
});
});
Also note that
if ($(this).prop('checked') === true) {
is quite a long way to write
if (this.checked) {
Similarly, with inputelements, this.value is the same as $(this).val().
I have a multiselect with many options. When 'everybody' is selected it removes other selected, if other are selected and the 'everybody' is selected it should remove it.
To remove the other and keep the item 'everybody' it's ok. But I have problem to keep other and only remove everybody.
For the moment I have something like :
resetGroupSelectionWhenEverybody: function() {
$(".group_ids").on("select2:select", function (e){
if (e.params.data.text === 'everybody') {
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
} else {
if ($('[title="everybody"]').length > 0) {
var idToRemove = 0;
groupIdsData = $('#scheduled_publication_groups_ids').select2('data');
groupIdsData.forEach(function(e, i) {
if (e.text === 'everybody') {
idToRemove = i;
}
});
groupIdsData.splice(idToRemove, 1);
$('#scheduled_publication_groups_ids').select2({'data': groupIdsData}).trigger("change");
}
}
});
},
With this code groupIdsData is tonly the selected elements I want (all expect everybody's group). But after I'm stuck to change the view. select2({'data': groupIdsData}) doesn't seems to be the right choice.
Few things :
I don't think I'm setting the idToRemove properly
What the best way to update the value of the select2 multiselect? It seems it can be a hash
The answer is to use select2('val') to get a array of ids, and then work with this. Code is better using .val() not full select2 objects.
resetGroupSelectionWhenEverybody: function() {
$(".group_ids").on("select2:select", function (e){
if (e.params.data.text === 'everybody') {
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(group_everybody_id).trigger("change");
} else {
if ($('[title="everybody"]').length > 0) {
groupIds = $('#scheduled_publication_groups_ids').select2('val');
groupToKeep = groupIds.splice( $.inArray(group_everybody_id, groupIds), 1);
$('#scheduled_publication_groups_ids').select2({width: '50%'}).val(groupToKeep).trigger("change");
}
}
});
},
In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/
i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example
var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/
You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});
So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.
I have listview with two checkboxes in itemtemplate.
I want to validate that user can only select only one checkbox in each row.
The behaviour you're describing is accomplished using standard HTML radiobuttons. If you change your design to use these you'll get the benefit that
The user can only select a single item, no extra javascript needed
Users expect to be able to choose multiple checkboxes but only a single radiobutton IE you're working with their expectations
If you're still sure you want to use jQuery then something like this should do it.
$(':checkbox').change(function(){
if($(this).attr('checked')) {
$(this).siblings(':checkbox').attr('checked',false);
}
});
#vinit,
just a little change, you forgot the else part,
$('input:checkbox[id*=EmailCheckBox]').click(uncheckOthercheckbox);
$('input:checkbox[id*=SMSCheckBox]').click(uncheckOthercheckbox);
function uncheckOthercheckbox() {
if (this.id.indexOf("EmailCheckBox") != -1) {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("EmailCheckBox")) + "SMSCheckBox";
}
else {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("SMSCheckBox")) + "EmailCheckBox";
}
var i = "#" + otherCheckBoxId;
if (this.checked) {
$(i).removeAttr('checked');
}
else {
if ($(i).attr('checked') === false) {
$(i).attr('checked', 'checked');
}
}
}
Thanks for the reply. had also asked one of my friend and he gave me the following solution which is working fine. Posting it, if anybody needs it.-
say ur checkboxes in the 2 clumns are named EmailCheckBox and SMSCheckBox
then use this code to toggle the checkboxes in each single row:
$('input:checkbox[id*=EmailCheckBox]').click(uncheckOthercheckbox);
$('input:checkbox[id*=SMSCheckBox]').click(uncheckOthercheckbox);
function uncheckOthercheckbox() {
if (this.id.indexOf("EmailCheckBox") != -1) {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("EmailCheckBox")) + "SMSCheckBox";
}
else {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("SMSCheckBox")) + "EmailCheckBox";
}
var i = "#" + otherCheckBoxId;
if (this.checked) {
$(i).removeAttr('checked');
}
}