Modifying HTML elements using jquery - javascript

I am trying to use jquery to add and remove a class from <li> elements according to a variable's value ( i ).
Here is a jsfiddle of what I have done so far http://jsfiddle.net/LX8yM/
Clicking the "+" increments i by 1 ( I have checked this with chrome's javascript console ).
One should be able to click "+" and the class .active should be removed from and added to the <li> elements accordingly.
...I can get the first <li> element to accept the class, that's all...

No need for if statements:
$(document).ready(function (){
$('#add').click(function (){
$('.numbers .active').removeClass('active').next().addClass('active');
});
});
jsfiddle
Do note that I added an 'active' class to first list item. You could always do this via JS if you do not have control over the markup.

Your if..else.. is hanging in document.ready. Wrap the increment inside a function and call it respectively.
Like
$(document).ready(function (){
//variable
var i = 1;
//if statments
function incre(i){ // wrap into a function and process it
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
}
//change i
$('#add').click(function (){
incre(i++); // pass it as a parameter
});
});
Working JSFiddle

This would be easier:
$(document).ready(function(){
var i = 0; // set the first value
$('#something').click(function(){
i++; // every click this gets one higher.
// First remove class, wherever it is:
$('.classname').removeClass('classname');
// Now add where you need it
if( i==1){
$('#one').addClass('classname');
} else if( i==2){
$('#two').addClass('classname');
} else if( i==3){
$('#three').addClass('classname');
}
}):
});

See this code. Initially you have to add class to one.
$(document).ready(function (){
//variable
var i = 1;
$('#one').addClass('active');
//if statments
//change i
$('#add').click(function (){
i++;
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
});
});

It's being called only once, not in the click event function. This edit of your fiddle works: http://jsfiddle.net/LX8yM/2/
put it in the
'$('#add').click(function (){}'

Related

How to disable actions on a webpage for first mouse click using javascript?

On clicking any element on a web page (say links, button etc), I need to stop the action. However, if the user clicks on them again (on second click), the actions should happen and it should redirect to next page.
I have this code to stop the action:
event.preventDefault();
event.stopPropagation();
I need to write condition to check for mouse clicks. Please help.
UPDATE 1:
var count=0;
var elements = document.querySelectorAll("*");
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("click", nonJQuery, false);
var nonJQuery = function (event) {
//some code
count++;
if(count<2){
event.preventDefault();
event.stopPropagation();
}
//some code
}
Thanks for the help. I'm writing something like this. I need to stop execution on all the elements on the web page and not on a particular element. So, my code looks like this.
If count is declared globally, and it is incremented in the function, next element I click will have wrong value. Can someone correct me?
P.S: Same if I use boolean as well.
Use counter for each element. You can use data attribute to store counter on the element itself.
$('mySelector').on('click', function(e) {
// Get counter of this element
var counter = parseInt($(this).data('clickCount'), 10) || 0;
if (counter++ % 2 === 0) {
//
} else {
e.preventDefault();
e.stopPropagation();
}
$(this).data('clickCount', counter);
});
EDIT
Without jQuery:
data docs
element.addEventListener('click', function (e) {
// Get counter of this element
var counter = parseInt((this.dataset.counter), 10) || 0;
if (counter++ % 2 === 0) {
//
} else {
return false;
}
this.dataset.counter = counter;
});
You can keep a counter and increase it at every click. The counter can be item specific or global depending on your requirement. Then you can check the counter value and have the conditional logic.
You can do like this:
var inc = 0;
element.addEventListener('click',function(event){
inc++;
if(inc < 2){
event.preventDefault();
}
});
http://jsfiddle.net/turutosiya/kLausy7x/1/
<ul>
<li>Click Here 1</li>
<li>Click Here 2</li>
<li>Click Here 3</li>
<li>Click Here 4</li>
</ul>
(function(){
$(function(){
$('a').on('click', function(event){
if(!$(this).data('clicked')) {
$(this).data('clicked', true);
return false;
} else {
return true;
}
});
});
})();
Use a boolean variable. Do:
var check= true;
element.addEventListener('click',function(event){
if(check){
check= false;
event.preventDefault();
event.stopPropagation();
}else{// do your task
}
});

How to check entered value is exist or not using Jquery or javascript

I have one textbox and one button and on button I have written below code. problem is suppose first I have entered in textbox 10 than its worked but when another time I enter 10 than also it prints value is not in array. so pls help me whats the issue...
jQuery(document).ready(function()
{
jQuery("#mybutton").live('click',function ()
{
var sel_fam_rel=jQuery("#my_textbox").val();
var ids = [];
code =sel_fam_rel;
if($.inArray(code,ids) >= 0)
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
This line:
if($.inArray(code,ids) >= 0)
should be changed to:
if($.inArray(code,ids) != -1)
and put your ids var outside of click.
Try the snippet below.
var ids = [];
jQuery("button").on('click', function() {
var sel_fam_rel = jQuery("#my_textbox").val();
code = sel_fam_rel;
if ($.inArray(code, ids) != -1) {
alert("Value is in array");
} else {
alert("Value is not in array");
ids.push(code);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='my_textbox'>
<button>check</button>
Create your array var ids=[];global outside button event, as whenever you click button it is creating new empty array. It will fix your problem.
A few changes are needed:
var ids = []; // `ids` needs to be in the global scope to work as you want it,
// or you could use a different method like localstorage
jQuery(document).ready(function()
{
jQuery("#mybutton").on('click',function () // use `on` not `live` which is deprecated
{
var sel_fam_rel=jQuery("#my_textbox").val();
code =sel_fam_rel;
if($.inArray(code,ids) != -1) // inArray() returns -1 if the value is not in the array, you can use it the way you have it, IMO (purely subjective), using `!=-1` is preferable as it's more clear what the code in intend to do
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_textbox" value="10"/><br>
<input type="button" id="mybutton" value="Click me"/>
use below code . take your ids out side of click event . as per your code each time when you click button ids reset .
var ids = []; // declare as global variable
jQuery(document).ready(function()
{
jQuery("#mybutton").live('click',function ()
{
var sel_fam_rel=jQuery("#my_textbox").val();
code =sel_fam_rel;
if($.inArray(code,ids) >= 0)
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
I made a fiddle to your problem, Use indexOf
http://jsfiddle.net/go8o34fq/
jQuery-
var array=["A","B","C","D"];
$('button').click(function(){
var code=$('input').val();
if(array.indexOf(code)==-1)
{
array.push(code);
console.log("if "+array)
}
else
{
console.log("else "+array)
}
});
Just a bit requirement if your need is case-sensitive then use- code.toUpperCase()

IE click event span not triggered

I'm having this webpage
http://pocolocoadventures.be/reizen/
And it should filter (with isotope.js) the travelboxes on the page.It does in safari, chrome, firefox, opera, .. but in IE, the filter doesn't work. Even worse, JS doesn't react at all at a click event on te span.
This is the piece of js
// Travel Isotope
var container = $('#travel-wrap');
container.isotope({
animationEngine : 'best-available',
itemSelector: '.travel-box ',
animationOptions : {
duration : 200,
queue : false
},
});
$(".filters span").click(function(){
var elfilters = $(this).parents().eq(1);
if( (elfilters.attr("id") == "alleReizen") && elfilters.hasClass("non-active") )
{
$(".label").each(function(){
inActive( $(this) );
});
setActive(elfilters);
}
else{
//set label alleReizen inactive
inActive( $("#alleReizen") );
if( elfilters.hasClass("non-active") ){
setActive(elfilters);
}
else{
inActive(elfilters);
}
}
checkFilter();
var filters=[];
$(".search.filters").children().each(function(){
var filter = $(this).children().children().attr("data-filter");
if( $(this).hasClass("non-active") ){
filters = jQuery.grep(filters, function(value){
return value != filter;
});
}
else{
if(jQuery.inArray(filter,filters) == -1){
filters.push(filter);
}
}
});
filters = filters.join("");
filterItems(filters);
});
function filterItems(filters){
console.log("filter items with filters:" + filters);
container.isotope({
filter : filters,
}, function noResultsCheck(){
var numItems = $('.travel-box:not(.isotope-hidden)').length;
if (numItems == 0) {
$("#no-results").fadeIn();
$("#no-results").css("display", "block");
}
else{
$("#no-results").fadeOut();
$("#no-results").css("display", "none");
}
});
}
function setActive(el){
el.removeClass("non-active");
var span = el.find('i');
span.removeClass("fa-check-circle-o").addClass("fa-ban");
}
function inActive(el){
el.addClass("non-active");
var span = el.find('i');
span.removeClass("fa-ban").addClass("fa-check-circle-o")
}
function checkFilter(){
var filterdivs = $('.filters span').parent().parent();
if( filterdivs.not('.non-active').length == 0 ){
setActive( $("#alleReizen") );
}
var filterLabels = $(".filters .label");
if( filterLabels.not('.non-active').length == 0){
setActive( $("#alleReizen") );
}
}
function noResultsCheck() {
var numItems = $('.item:not(.isotope-hidden)').length;
if (numItems == 0) {
//do something here, like turn on a div, or insert a msg with jQuery's .html() function
alert("There are no results");
}
}
Probably something small and stupid; but I can't find it..
Thanks in advance!
On your website you've build the buttons like this:
<button>
<span>
</span>
</button>
Now the button element is designed to be a button. It differs from the input button. In the latter you'd set the caption using value. In the button element you set it as a text node. The button element can contain elements like a span. The spec isn't very clear about whether or not you should have event handlers on the children of the button element. It's a browser developers interpretation of allowing it or not.
This problem has been posted here before (a few times)
span inside button, is not clickable in ff
Missing click event for <span> inside <button> element on firefox
It seems that Firefox is allowing it, based upon your findings. IE isn't. So to be on the safe side: use the button the way it was intended.
Wrap the button inside a span (not really logical)
Put the click handler on the button.
$(".filters button").click(...);
played around in the console a bit, and this seemed to work well.
$(".filters").on('click', 'span', function(){
// foo here
console.log('foo');
});
Maybe the filters are manipulated by one of your js files after page load?
.on will allow you to select a container which listens on changes that happen inside it, passing the element you want the actual action to work on.
If it's ok for you, I'd suggest to use the <button> element, instead of the <span>.
Let me know if that works for you.

How to apply .one() not for every object

I'm having some difficulties with a certain task. I've got the following code
$(document).ready(function() {
var Result = 0;
var stop_process = false;
$('img').click(function(){
if( !stop_process ){
if( $(this).hasClass( 'home' ) ){
stop_process = true;
$('body').append('<div class="message">Your Result is: </div>' + Result);
}
if( $('img.home').length == 0 )
$(this).addClass('home');
var $elem1 = $(this).parent();
var $elem2 = $('span.last');
$(this).toggleClass('selected');
if ($elem2.length > 0) {
connect($elem1[0], $elem2[0], "#0F0", 5);
} else {
$elem1.addClass('last');
}
$('span').removeClass('last');
$elem1.addClass('last');
Result++;
}
});
I want to forbid a second click, so that I'll have a complete circle and I have gone through all objects once. If I apply .one() I get what I want, but I can't complete the circle, since the home object is still unclickable. Is there any way to solve this issue? To apply .one() to every object, but not the 'home' one?
Thanks in advance!
Whole code:
http://jsfiddle.net/N2Pdc/
Try to use jQuery off, you can build if statements around it to help you achieve this. Store in a variable the first elem you click, and have a counter, so you can make sure you can only click the first object (close the circle) when you have clicked all other elements before.
If you want to use .one you can use the jQuery filter :not() like $(body:not(.home))

jQuery.css('display') only returns inline

I am trying to get checked options from a table which are set inline. There is a search function, which sets $(element).css('display','none') on objects in which there is no match with the search. Anyways, this piece of code will only return inline, no matter what the elements are set to. Even if I manually set all of them to display: none in the table itself, the alert will return inline for every single object in the table. Is there any solution to this?
JS code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).css('display') === 'inline') {
array.push($(this).val());
}
});
}
Fundamentally, css("display") does work, so something else is going on.
I suspect one of two things:
The checkboxes that you're making display: none are never checked, and so you don't see them in your each loop.
You're not making the checkboxes display: none, but instead doing that to some ancestor element of them. In that case, $(this).is(":visible") is what you're looking for.
Here's an example of #2: Live Copy | Live Source
<div id="ancestor">
<input type="checkbox" checked>
</div>
<script>
$("#ancestor").css("display", "none");
console.log("display property is now: " +
$("input:checkbox:checked").css("display"));
console.log("visible tells us what's going on: " +
$("input:checkbox:checked").is(":visible"));
</script>
...which outputs:
display property is now: inline-block
visible tells us what's going on: false
Applying that to your code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).is(':visible')) {
// Change is here -----------------^^^^^^^^^^^^^^
array.push($(this).val());
}
});
}
Side note: Every time you call $(), jQuery has to do some work. When you find yourself calling it repeatedly in the same scope, probably best to do that work once:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
var $this = $(this); // <=== Once
i++;
alert($this.css('display'));
if ($this.val() !== 0 && $this.is(':visible')) {
// Other change is here -------^^^^^^^^^^^^^^
array.push($this.val());
}
});
}
try following:
$("input:checkbox:checked").each(function(i,o){
console.log($(this).css("display"));
});
working fiddle here: http://jsfiddle.net/BcfvR/2/

Categories