how to validate object in jquery - javascript

I am adding arbitrary data to li element using jquery as:
if($("li").data('family').$(this).text()==$(this).text()){
$("li").removeData('family',{'persons':''}); // I know this is wrong!
// any idea how to remove data from this object
}else{
//this part adds data which is not working fine
$("li").data('family',{$(this).text():$(this).text(),
'cat':'family'
});
}
above I m trying to validate whether the value already exits or not if exits remove it.
I am facing 1 problem:
How to add / remove key value same from object
Thanks in advance!

Try this
$("#cat-family ul li").live("click", function() {
var $ul = $(this).closest('ul');
var family = $ul.data('family');
if (!family) {
family = {
'cat' : 'family'
};
$ul.data('family', family);
}
var text = $(this).text();
if (family[text]) {
delete family[text];
} else {
family[text] = text;
}
console.log(this, $ul.data().family);
});
Demo: Fiddle

Try this:
var key='';
$(document).ready(function(){
$("#cat-family ul li").on("click",function(){
var $li=$(this);
key=$(this).text();
if($(this).data('family')){
if($(this).data('family').key==$(this).text())
$(this).removeData('family');
}
else{
key=$li.text();
var k={};
k[key]=key;
k['cat']='fam';
$(this).data('family',k);
}
console.log($(this).data());
});
});
Read Docs http://api.jquery.com/removeData/
Fiddle http://jsfiddle.net/WmLQa/1/

you can check data by:
if($("li").data("family").persons === $(this).text())
{
$.removeData($("li") , "family"); //to remove
}

Related

How to optimize this javascript duplicates

I wrote this code, but since I'm just starting to learn JS, can't figure out the best way to optimize this code. So made a duplicates for every if statement.
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$('.lang').hide();
$('.lang-all').click(function(){
$('.lang-all').hide();
$('.lang').slideToggle(200);
});
} else {
$('.lang').show();
$('.lang-all').hide();
}
if(gender.length == gender.filter(":checked").length){
$('.gender').hide();
$('.gender-all').click(function(){
$('.gender-all').hide();
$('.gender').slideToggle(200);
});
} else {
$('.gender').show();
$('.gender-all').hide();
}
});
So this is my code, as you can see on line 15 if(gender... I have a duplicate of previous code, just changed variable from "lang" to "gender". Since I have more that two variables, I don't want to make duplicate of code for every each of them, so I hope there is a solution to optimize it.
You can write a function to let your code more abstract, see:
function isChecked(obj, jq1, jq2){
if(obj.length == obj.filter(":checked").length){
jq1.hide();
jq2.click(function(){
jq2.hide();
jq1.slideToggle(200);
});
} else {
jq1.show();
jq2.hide();
}
}
//Your jQuery code, more abstract
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
isChecked(lang, $('.lang'), $('.lang-all'));
isChecked(gender, $('.gender'), $('.gender-all'));
});
make a function which had similar functionality, then pass a parameter as a class or id
$(function() {
call('.lang');
call('.gender');
function call(langp){
var lang = $(langp+" input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$(langp).hide();
$(langp+'-all').click(function(){
$(langp+'-all').hide();
$(langp).slideToggle(200);
});
} else {
$(langp).show();
$(langp+'-all').hide();
}
}
});

Multiple $("selectort").click (function () in if then construction not working

I have a server that dynamically(asp.net ) generate webpages that I can't alter.
On all pages I would like to capture all buttons clicked.
In JSFiddle https://jsfiddle.net/forssux/aub2t6gn/2/ is an example..
$(".checkout-basket").click (function ()
The first alert shows the 3 possible values,
but not the chosen item..
$(".button.button-dl").click(function ()
In jsfiddle this part doesn't get executed
Strangely on my real webpage I get the button clicked...but when I put it in the If then construction it fails to console.log the chosen item..
I hope somebody can explain me how to get these..
Kind Regards
Guy Forssman
//$("div.detail-info,table.checkout-basket").click(function () {
// var knopje = $(this).attr("class")//.split(" ");
// console.log(knopje + " knopje was clicked");
// if(knopje.indexOf("detail-info") > -1) {
// console.log("div class detail-info is clicked");
// }
// else if (knopje.indexOf("checkout-basket") > -1) {
// console.log("table class checkout-basket is clicked");
// }
// else {
// alert ("er is op iets anderes gedrukt");
// }
// capture click on download button in checkout-basket page
$(".checkout-basket").click (function () {
basket =[];
item="";
str = $(this).text();
str = str.replace(/\s\s+/g, ' ');
var str = str.match(/("[^"]+"|[^"\s]+)/g);
console.log("Array ",str);
for(var i=0;i<str.length;i++){
if(str[i] === "verwijder"){
console.log("Item= ",str[i+1]);
item = str[i+1];
basket.push(item);}
}
console.log("Basket contains ",basket);
//console.log("idValBasket ",idVal);
var test = idVal.replace(/\$/gi, "_").slice(0,-6);
console.log("test ",test);
var element = test.substr(test.length - 2)-1;
console.log("element ",element);
element=element-1;
item = basket[element];
console.log("Item finaal is ",item);
});
$(".button.button-dl").click(function () {
var addressValue = $(this).attr('href');
console.log("addresValue Basket",addressValue );
var re = /'(.*?)'/;
var m = addressValue.match(re);
console.log (" m basket is ",m);
if (m != null)
idVal = (m[0].replace(re, '$1'));
console.log("idVal Basket",idVal);
});
//This section captures the download in the detail page
$(".button").click(function () {
var downloadItem = document.getElementsByTagName("h1")[0].innerHTML
console.log("addresValue detail",downloadItem );
});
I never use click function, use on(*event*,...) instead:
$(".checkout-basket").on("click", function (){ /* CODE */ });
Check if visually there are a layout over the a layuot (a div, span, etc.)
Maybe a strange question and maybe i got it wrong, but why do you use push ?? if you want to delete an item ? btw also the example isn't working so maybe that is your problem

multiple select get recently selected option value

I want to know last or recently selected option value for dropdown
I have tried following code in django :
<script type="text/javascript">
django.jQuery(document).ready(function(){
django.jQuery("#id_emuhibah_issue").on("click", function(e){
console.log(" click -------");
console.log(django.jQuery(this).val());
console.log(this.value);
});
});
django.jQuery(document).ready(function(){
django.jQuery("#id_emuhibah_issue").on("change", function(e){
console.log(" chage -------");
console.log(django.jQuery(this).val());
console.log(this.value);
});
});
</script>
seems there is no luck to find out last selected value
Can anyone suggest solution for above case?
Just remove the click function and use only on.("change" function..) one function with one "document ready"
Here how I have manage to handle the case:
<script type="text/javascript">
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
var old_selected_issues = [];
django.jQuery(document).ready(function(){
django.jQuery("#id_issue").on("change", function(e){
var new_selected_issues = django.jQuery(this).val();
if(new_selected_issues != null){
var diff = new_selected_issues.diff(old_selected_issues);
old_selected_issues = new_selected_issues;
if(diff.length){
//perform the job on last selected option
var lang = window.location.pathname.slice(1,3)
django.jQuery("#issue_iframe").attr('src', '/'+lang+'/admin/'+diff[0]+'/');
}
else{
django.jQuery("#issue_iframe").attr('src', '');
}
}
else
{
old_selected_issues = [];
django.jQuery("#issue_iframe").attr('src', '');
}
});
});
</script>
Please let me know, in case of any other possible solution

Get all li data-val in an ul

I can't get the data-val of a li when it has a link inside, could you help me to fix it?
li example:
<li data-val="Lima 2">Lima [T:19ÂșC H:82%]<span style="float:right;"><b>[X]</b></span>
</li>
Javascript
$("#cup").on("click", function () {
$('.clista').each(function () {
var cidades = [];
var cidade = '';
$(this).find('li').each(function () {
var current = $(this);
if (current.children().size() > 0) {
return true;
}
cidade += $(this).attr('data-val');
alert(cidade);
});
cidades.push(cidade);
});
});
Could you check the script: http://jsfiddle.net/fabiobraglin/rcheaowx/8/
Tks a lot!
You should write your alert outside of the each function. And you shouldn't check for children, that's why you don;t get the result you want.
$('.clista').each(function () {
var cidades = [];
var cidade = '';
$(this).find('li').each(function () {
cidade += $(this).attr('data-val');
});
alert(cidade);
cidades.push(cidade);
});
Since you have put an if block which returns true if li has children. I don't know what are you trying to accomplish by doing so. However, that if check becomes true and function exits by returning true. If you remove that return statement or remove complete if block, your update function will work fine. Try this. Hope it helps.
try this:
$("#cup").on("click", function () {
var cidades = new Array();
$('.clista li').each(function () {
cidades.push($(this).data('val'));
});
alert(cidades);
});
http://jsfiddle.net/rcheaowx/9/
to get all the data-val just remove the below code section
if (current.children().size() > 0) {
return true;
}

get id of child element when parent is clicked

Hello I have seen similar posts but none answer what I want to accomplish
I made a sample here
http://jsfiddle.net/edgardo400/R6rVJ/
What i basically want is when a click happens in the parent you get the id of the child
and store it in a variable so i can pass the variable currentID to the code below otherwise I will have to replicate this code 9 times for each id from box1 to box9
jQuery(currentID).delegate("a", "hover", function(event){
var $img = jQuery(this).parent("li").find('img');
var image = jQuery(this).attr('data-img');
jQuery('.defaultimg').stop(true, true).fadeOut();
if( event.type === 'mouseenter' ) {
if($img.length){
$img.show();
}else{
jQuery(this).parent("li").append('<img id="theImg" src="' + image + '" />');
}
}else{
if($img){
$img.hide();
}
jQuery('.defaultimg').stop(true, true).fadeIn();
}
});
});
$('#boxes').on('click', function(e) {
var currentID = e.target.id;
console.log(currentID);
......rest of code
In javascript it would be:
var a = document.getElementById('#boxes');
a.onclick = function(e){
console.log(e.target.id);
}
If you only wish to make your code working and displaying on your console the box name, you should probably set
jQuery('#boxes').bind('click', function(event) {
var currentID = jQuery(event.srcElement).attr('id');
/* rest of your code */
});
You might want to do something easier
jQuery('#boxes').children().bind('click', function() {
jQuery(this).delegate...
});
Although I'm not sure why you are doing this ...
fixed http://jsfiddle.net/nxTDA/

Categories

Resources