click only one random button from the true condition response jquery/javascript - javascript

I'm a newbie in jquery/javascript and i need some help!
I'm trying to click only one button from the true condition response, but all the time the script will click on all the buttons of the true condition response.. I don't know how to solve this.
$(".enemy-box").each(function(index) {
var pret = Number($(this).find('.attack-price').text().replace(/,/g, '').split('$')[1]);
var name = $(this).find('.enemy-name').text().replace(/\s+/g, " ");
var x = $(this).find(document.getElementsByClassName("btn attack-btn")); // this will click on all the true conditions buttons
/* I have tried with this but stil not working. the script will click on all the true conditions buttons!
var len = $(this).find(document.getElementsByClassName("btn attack-btn")).length;
var random = Math.floor( Math.random() * len ) + 0;
var x = $(this).find(document.getElementsByClassName("btn attack-btn")).eq(random);
*/
if (name.indexOf("Test") == -1 && pret <= 39.99 ) {
x.click();
}
});
Any help is much appreciated, thank you in advance!

Try replacing $(this).find(document.getElementsByClassName("btn attack-btn")); with $(this).find('.attack-btn:first);.
getElementByClassName is unnecessary when using jQuery. :first will return only the first occurrence of the selector.

This is happening because you are passing the document as context to the find() function. And, since you are using jQuery, you don't need to use JS method. Simply pass the selector to the method find().
You can do that either by
var x = $(this).find('btn.attack-btn:first');
or
var x = $(this).find($('btn.attack-btn').eq(0));

Related

The problem of changing multiple of 3 to red using jquery on the presented screen

Only jquery script should be used to mark the number of multiples of 3 in red.
Each number is made up of <table>.
I made the code below, but there's an error.
$(function(){
$("#Q2_1").find(function(){
var num = $("#Q2_1").val();
num = Number(num) + 1;
return num % 3 == 0;
});
.css({"color":"#f00"});
});
Please advise me what the problem is.
Or can you give me a similar but simple example?
Use a selector that returns all the td elements in the table.
Use filter() to restrict this based on a condition.
The condition should get the text of the element; value is for user inputs.
Get rid of the ; after the call, so you can append .css().
$(function() {
$("#tableid td").filter(function() {
let num = Number(this.innerText);
return num % 3 == 0;
}).css("color", "red");
});

Trying to make a super simple clicker game but im getting NaN instead of numbers

I'm really out of ideas, I've tried everything I can try but can't get this simple thing to work.
JavaScript
var gurus = document.getElementById('clicks')
var x = gurus.value+1
function guru() {
document.getElementById('clicks').innerHTML = x
}
HTML
<p id='clicks'>0</p>
<button onclick='guru()'>Click</button>
I made this in a codepen (link).
First of all you need innerHTML not values , since p tag does not have values attribute. Secondly you need to get the content of the p tag on every click, so put it inside the function. Use parseInt to convert the string to number
var gurus = document.getElementById('clicks')
function guru() {
var x = parseInt(gurus.innerHTML, 10) + 1
document.getElementById('clicks').innerHTML = x
}
<p id='clicks'>0</p>
<button onclick='guru()'>Click</button>
Below is a clearner way to achieve the same thing youre trying to do. The code below makes use of addEventListener and removes JavaScript function calls from inline HTML (it's not best practice). Make sure to use parseInt to convert the innerHTML as that was your original issue with the code you posted:
document.addEventListener('DOMContentLoaded', () => {
const p = document.querySelector('#clicks');
const b = document.querySelector('#btn');
p.append(document.createTextNode("0"));
b.addEventListener('click', function() {
p.innerHTML = parseInt(p.innerHTML) + 1;
});
});
<p id='clicks'></p>
<button id="btn">Click</button>
And the answer is super simple too! You are treating the <p> element as if it was an input field. You need .innerHTML instead of .value. Then, you need to convert that inner HTML into a number (using Number()). Finally, you should move the increment statement:
var x = gurus.value + 1
into the function, otherwise x is just a constant. Here is a working snippet:
var gurus = document.getElementById('clicks');
function guru() {
var x = Number(gurus.innerHTML) + 1;
document.getElementById('clicks').innerHTML = x;
}
<p id='clicks'>0</p>
<button onclick='guru()'>Click</button>

jQuery Math - No calculation with empty fields

I have a simple parse to get the sum of a collection of textareas. It works fine, but if there's no value placed in the field, then the calculation just doesn't run.
How can I make the default value 0 without having the contents actually have to be 0? Like, I don't want the fields to load up with a 0 already waiting in the box - I just want the formula to not worry about empty fields.
Here's the jQuery:
jQuery(document).ready(function(){
jQuery(".button1").click(function(){
var set1 = function() {
var calc1 = 0;
$('.calc1').each( function(index,item) {
calc1 += parseInt(jQuery(item).val());
});
$('.result1').html(calc1);
}
set1();
});
});
The codepen can be seen here if you'd like to get a better idea: https://codepen.io/JTBennett/pen/NENMdP
I appreciate any help with this! I know it's probably a stupid mistake, but I've tried a few different things and not gotten anywhere yet.
Try parseInt(jQuery(item).val() || 0). The || operator will return the second value if the first is falsey. Therefore if the value is empty, it will try to parse '0' which it will successfully.
Just make an if statement that looks for an empty field and then replace it with 0.
$('.calc1').each( function(index,item) {
var itemValue = jQuery(item).val();
if (itemValue === "") {itemValue = 0;}
calc1 += parseInt(itemValue);
});
You can just replace your line with this:
calc1 += parseInt(jQuery(item).val() || 0);

Looping through objects in an array JS

I'm putting together this script which pulls two child elements from a containing div #mini_ads, adds them to an array. I want to be able to use the array to select them via index in order to manip. them individually.
I know I can just select them w/o even using an array of course, but I want this array as I may add multiple more elements later.
The issue is that I am not able to select the items individually by their index in the array. The current script I've got going is selecting and manipulating both objects in the array as if they're both index[0].
var miniAds = $('#mini_ads');
var elements = miniAds.children();
var changeWtime;
var adsArr = new Array();
var i = 0;
var x = 0;
adsArr.push(elements);
console.log(adsArr);
adsArr[i].css("display", "none");
var changeWtime = setInterval(function () {
for (x; x < 1; x++) {
return x;
while (x > i) {
adsArr[1].css("display", "block");
}
};
}, 5000);
console.log(x);
changeWtime;
I am not sure where I'm going wrong here. Assistance will be much appreciated. Thanks in advance.
Issues with your code
You're creating a double array when you push elements into 'adsArr':
adsArr.push(elements);
You're throwing a return statement in the for loop:
for (x; x < 1; x++ ){
return x;
// ...
You have a double loop for no reason while inside of the for.
Solution
I was going to explain the solution to this verbally, but after coding an example I realized that there is too much to explain this is another solution similar to yours:
var miniAds = $('#mini_ads'),
elements = miniAds.children(),
i = 2,
x = 0;
elements.hide();
var changeWtime = setInterval(function () {
if ( x < i ) {
$(elements[x]).show();
}
x++;
}, 5000);
Link to example on jsbin.
Hi u should push child divs as below function does and after that i believe u can perform ur task...
var adsArr= [];
$('#mini_ads').children().each(
function(i){
adsArr.push(this);
});
In plain Javascript use .styles()
.css() which is a JQuery method but not Javascript
ref http://www.w3schools.com/js/js_htmldom_css.asp

Javascript sort not working with IE9?

the problem is I have a list with contacts and when someone change his/her status I try to move them to the top of the list. Everything worked till now, with IE9, and Firefox 4 is not working. I show you the code:
function sortByStatus()
{
var divs = getElementsByClassName(document,"status_sort");
divs.sort(compare);
for (var i = 0; i < divs.length; i++)
{
$("#contact_info").append(divs[i]);
}
}
function compare(div1, div2)
{
var id1 = div1.getAttribute("id");
var id2 = div2.getAttribute("id");
if (id1 > id2)
return 1;
else if (id1 < id2)
return -1;
else
return 0;
}
Any idea or possible fix? Thank you.
update
I have tried MrBuuBuu solution and it works patially, because now the sort by status works but the alphabetic sort is not working. I had to change part of MrBuuBuu solution, the compare function, because I compare the name of the contacts with a number just before the name that represent the status (ex. 2John , 2 means offline, and 1 online) so I have to compare with '<' and '>' and return 1, -1 or 0.
But what is worst, now it doesn't work with IE7 or IE8... the sort by status is not working.
Really weird, any idea?
document.getElementsByClassName returns a NodeList, not an array. So you have to convert it to an array first. I also cleaned up your compare() function.
function compare(div1, div2)
{
var id1 = div1.id;
var id2 = div2.id;
if (id1 < id2) {
return - 1;
}
if (id1 == id2) {
return 0;
}
return 1;
}
function sortByStatus()
{
var divs = document.getElementsByClassName("status_sort");
var divArray = $.map(divs, function(div) { return div; });
divArray.sort(compare);
$.each(divArray, function(i, div){
$("#contact_info").append(div);
});
}
If you're using the browser's native getElementsByClassName function, you may be ending up with a DOM node collection that is not a sortable Array.
When you say it's not working, are you getting any errors or is it just that the array doesn't get sorted? I'm assuming you're getting an error because sort in not defined.
One thing you could try is to clone the node collection to a plain JavaScript Array before sorting:
divs = [].slice.call(divs);
divs.sort(...
I don't have IE9 to test this, but with Chrome:
// undefined
document.getElementsByClassName("someclass").sort
But:
// the sort function
[].slice.call(document.getElementsByClassName("someclass")).sort
Are you sure it has been working? There's no such function as getElementsByClassName in the global scope.
Try using document.getElementsByClassName("status_sort") instead.

Categories