jQuery $(this) duplicate - javascript

This code really messes me up.. Could you help? There is 5 elements, with the #newlinks. In all #newlinks, there is childs of a. This code runs perfect on the first #newlinks, but after that one, it won't give the even a-elements a gray background.
#newlinks.
$(function(){
var bg = 0;
$("#newlinks").children("a").each(function(){
if(bg % 2 == 0){
$(this).css("backgroundColor", "#F2F2F2");
bg++;
}else{
bg++;
}
});
});
I have also tried this, but i guess it won't work, because $(this) could be both the newlinks-element selected and the a-element selected.
$(function(){
var bg = 0;
$("#newlinks").each(function(){
$(this).children("a").each(function(){
if(bg % 2 == 0){
$(this).css("backgroundColor", "#F2F2F2");
bg++;
}else{
bg++;
}
});
});
});

You can not give the same ID for more than one elements. They must be unique.
You must use classes. So that $(".newlinks") selector should work.

ID should be only one per page. Please change to class like <div class="newlinks"> and then use the code below :
$(function(){
$(".newlinks").children("a").each(function(index){
if(index % 2 == 0){
$(this).css("background", "#000000");
}
});
});

Try this jssfiddle :
$(function () {
$("#newlinks a").each(function (index) {
if (index % 2 == 0) {
$(this).css("backgroundColor", "#F2F2F2");
}
});
});

Related

jquery function to change text color depending on a special character

I want to change the text color if there's a negative number in my HTML list
This is my call to my jquery function inside my HTML.
<ul id="negativeValidation">
<li>123.5</li>
<li>-43.5</li>
</ul>
This is my jquery function:
$(document).ready(function() {
$('#negativeValidation', function() {
if($("li:contains('-')")== true)
{
$("li").css("color", "red");
console.log("True");
}else{
$("li").css("color", "green");
console.log("False");
}
});
});
It's not working, when I go to the console I alway get the "false" message so I would like to know what's wrong or if I'm missing something.
$("li:contains('-')") returns a jQuery object which is always truthy, even if that selector doesn't exist. To test if an element matches you need to use length or is() but you also are wanting to check each instance
try something like:
$('#negativeValidation li').each(function(){
var color = $(this).is(':contains(-)') ? 'red' :'green';
$(this).css('color',color);
});
A more effective way would be use CSS and add a class for negatives
#negativeValidation li {color: green}
#negativeValidation li.negative {color: red}
JS
$('#negativeValidation li').filter(function(){
return +$(this).text() < 0;
}).addClass('negative');
First you have console.log('False') in both cases.
write it like this JS Fiddle
$(document).ready(function() {
$('#negativeValidation li').each(function() {
var txt = $(this).text();
if (txt.indexOf('-') > -1) {
$(this).css("color", "red");
console.log("True");
} else {
$(this).css("color", "green");
console.log("False");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="negativeValidation">
<li>123.5</li>
<li>-43.5</li>
</ul>
you should need "for":
$(document).ready(function() {
$('#negativeValidation', function() {
var lis = $('#negativeValidation li');
for (i = 0; i <= lis.length; i++) {
if (lis.eq(i).is(':contains(-)')) {
lis.eq(i).css("color", "red");
console.log("True");
} else {
lis.eq(i).css("color", "green");
console.log("False");
}
}
});
});
I want to change the text color if there's a negative number in my
HTML list
but problem title refer special characters. Hope you mean to refer only negative numbers.
So in a pure javascript way
// Select all li elements.It will return a collection of matched elements
var getLiItems = document.querySelectorAll("#negativeValidation li");
// Loop through it , get each's text content ,
// convert it to float and check if less than 0
for(var i=0;i<getLiItems.length;i++){
var getTextContent = parseFloat(getLiItems[i].textContent);
//if less than zero add a class to it
getTextContent < 0 ? (getLiItems[i].classList.add("negativeColor")): 0;
}
Working Example

Occur if 3 button are clicked and disable other button

I have in a html page 5 button named 1,2,3,4 and 5.If 3 button are clicked the other button must be disabled.
var clicking=0;
$(document).ready(function(){
$('button').click(function(){
clicking++;
$(this).toggleClass("active");
if(clicking==3){
$('button').click(function(){
$(this).toggleClass("nothing");
})
}
})
})
I tried with this script but it don't work because all the button can be clicked.The if is ignored.
i want that only 3 of this 5 button can be clicked and the other must become disabled.
EDIT: shortened the code
I think this is what you want? Count the number of buttons with .active. If it's three or more, disable all buttons that don't have .active.
JS:
$('button').on('click', function() {
$(this).toggleClass('active');
$('button').prop('disabled',false);
if ($('.active').length >= 3) {
$('button:not(.active)').prop('disabled',true);
}
});
Here's a fiddle.
You should do something like this :
var clicking=0;
$(document).ready(function(){
$('button').click(function(){
clicking++;
$(this).toggleClass("active");
if(clicking==3){
$('button').each(function(){
if(!$(this).hasClass("active")){
$(this).addClass("inactive");
}
});
}
});
});
I didn't try it, but I think you like for something similar.
Ok i am not a master of jquery but i came up with a simple logic to implement what you want to achieve, that is disabling all the other buttons that haven't been clicked after three clicks. Here's my working code:
var count = 0;
var ids = new Array();
$(document).ready(function(){
$('button').click(function(){
ids[count] = this.id;
count++;
if(count == 3){ //three buttons clicked, now time to disable the remaining buttons
for(var i=0; i<$('button').length; i++){ //we'll check for all buttons
var id = $('button')[i].id;
var flag = true;
for(var j=0; j<ids.length; j++){ //checking all the buttons against the buttons that got clicked
if(id == ids[j])
flag = false; //button has been clicked (won't be disabled)
}
if(flag){
$("#"+id).attr("disabled", true); //disabling button
}
}
}
})
})
It's very self explanatory and i added lots of comments but still what i did is:
save the ids of buttons that got clicked, then after three clicks, disabling all the buttons who's ids don't match with the saved ids. Pretty simple.. but im sure you can make the code better as i'm not too good at jquery.
See the Working DEMO here
My sugestion is to use an array so you know witch buttons were clicked.
$(document).ready(function(){
var clickedbuttons = [];
$('button').click(function(){
$(this).toggleClass("active");
var idx = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(idx == -1)
clickedbuttons.push($(this).attr("id"));
else clickedbuttons.splice(idx,1);
if(clickedbuttons.length == 3) {
$('button').each(function() {
var index = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(index == -1)
$(this).attr("disabled", "disabled");
});
}
else {
$('button').each(function() {
$(this).removeAttr("disabled");
});
}
});
})
I'm assuming each button has an id. This will work as you want but you have to have an id in every button.
If you do not want to reenable change accordingly
$(document).ready(function(){
var clickedbuttons = [];
$('button').click(function() {
var idx = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(idx == -1) {
clickedbuttons.push($(this).attr("id"));
$(this).toggleClass("active");
}
if(clickedbuttons.length == 3) {
$('button').each(function() {
var index = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(index == -1)
$(this).attr("disabled", "disabled");
});
}
else {
$('button').each(function() {
$(this).removeAttr("disabled");
});
}
});
})

Remove option with value = MRW if I checkbox if checked

I'm trying to remove a option with value equal to MRW if #natural_person_lives_in_ccs_0 is checked but if I unchecked the checkbox then the SELECT should be as it was by default meaning same options. This is what I did:
$(document).ready(function(){
var lives_in_css = $('#natural_person_lives_in_ccs_0').is(':checked');
if (lives_in_css) {
$(".shipping_from option[value='MRW']").remove();
} else {
$(".shipping_from").append('<option value="MRW">Option1</option>');
}
});
But it's not working since Option1 is added by default and I don't know how to write this. I think to use .toggle() but don't know if it's the right one. I leave a Plunker here for testing. Any help on this?
Steps:
Check Yes option value=MRW should be removed
Remove the check from Yes option value=MRW as by default (same position)
Try to use the .change() function to accomplish your task here,
$('#natural_person_lives_in_ccs_0').click(function () {
var elem = $(".shipping_from option[value='MRW']");
if (this.checked) {
elem.remove();
} else if (elem.length == 0) {
$(".shipping_from").prepend('<option value="MRW">Option1</option>');
}
});
DEMO
The best way would be,
$('#natural_person_lives_in_ccs_0').click(function () {
$(".shipping_from option[value='MRW']").toggle(!this.checked);
$(".shipping_from option:eq(" + ((this.checked) ? 1 : 0) + ")").prop('selected', true);
});
DEMO
Write your script like bellow.
var showOptionsAcorrdingCheckbox = function(){
var lives_in_css = $('#natural_person_lives_in_ccs_0').is(':checked');
if (lives_in_css) {
$(".shipping_from option[value='MRW']").remove();
} else {
$(".shipping_from").append('<option value="MRW">Option1</option>');
}
}
$(document).ready(function(){
$(':checkbox').change(showOptionsAcorrdingCheckbox);
});
DEMO
code:
$(document).ready(function(){
$(document).on('change', '#natural_person_lives_in_ccs_0', function(){
if($(this).is(':checked'))
{
$(".shipping_from option[value='MRW']").remove();
}
else
{
$(".shipping_from").append('<option value="MRW">Option1</option>');
}
});
});

Selecting, Deleting jQuery based on wildcard

What I would like is if there is NOT a word "link" in the href "www.1link.com" all the top classes 1-6 is changed to classdefault.
Also a different code that does the same thing except of adding "defaultclass" it removes all the classes 1-6 empty.
This is what I've tried so far and it hasn't worked
http://jsfiddle.net/yLxXn/2/
$(document).ready(function() {
if ($('a[href$="link"]')) {
// do something here
$("[class^=content]").attr("class", "classdefault");
}
});
Try something like this :
if ($('a').attr('href').indexOf('link') != -1) {
// other code
}
UPDATE
If you want this to happen if it does not contain "link", change >= to <=. As following:
For replacing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').attr('class', 'classdefault');
}
});
For removing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').removeClass();
}
});

JQuery for loop - function with variables

Is there a way to turn this into a for loop? I have to run this code 114 time and am looking for a way to simplify this. The numbers on the class name would be the variable. The next one would be .select3 etc...
$('.select2').click(function () {
if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic)
{
$(this).parent().clone().appendTo('.saved_list ul');
$('.saved .select2').replaceWith('<div class="remove2">Remove</div>');
$('.saved a').contents().unwrap();
} else {
alert ('You can only choose 3 paintings');
}
if ($('.saved_list li').has('.thumb2')) {
$(".select2 .img-swap").attr("src", "images/check_on.gif");
} else {
$(".select2 .img-swap").attr("src", "images/check_off.gif");
};
});
Try this:
var run_select = function(index){
var selector = '.select'+index;
$(selector).click(function () {
if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic)
{
$(this).parent().clone().appendTo('.saved_list ul');
$('.saved '+selector).replaceWith('<div class="remove2">Remove</div>');
$('.saved a').contents().unwrap();
} else {
alert ('You can only choose 3 paintings');
}
if ($('.saved_list li').has('.thumb2')) {
$(selector+" .img-swap").attr("src", "images/check_on.gif");
} else {
$(selector+" .img-swap").attr("src", "images/check_off.gif");
};
});
};
var i, l = 114;
for(i=1;i<=114;i++){
run_select(i);
}
First, simplify html if you can. Use id for unique identifiers and the same name for css classes. Like this:
<div id='select2' class='select'></div>
Then use .each() if you want to get all your items:
$('.select').each(function() {
// use $(this) here to refer to the current item
});
But in your case, you can simply apply the 'click' event like this:
$('.select').click(function(e) {
// use $(this) or $(e.target) here to refer to the current item
// if you need to get the id number you could get it from the id
// (supposing has id='select2')
var id = $(this).attr('id').substring(6); // it returns 2
});

Categories

Resources