I have to use Mootools for a website but being a real newbie I'm stuck with my code:
var val = element.get('value');
// Here I get a number between 1 and 6 and I'd like to implement a loop that goes from 1 to the value of val (between 1 and 6)
$('jj_enfant' + val).addClass("validate['required']");
$('mm_enfant' + val).addClass("validate['required']");
$('aaaa_enfant' + val).addClass("validate['required']");
$('last_name_enfant' + val).addClass("validate['required','nodigit']");
$('first_name_enfant' + val).addClass("validate['required','nodigit']");
var val = element.get('value').clean().toInt();
for (var ii = 1; ii <= val; ++ii) {
$('jj_enfant' + ii).addClass("validate['required']");
$('mm_enfant' + ii).addClass("validate['required']");
$('aaaa_enfant' + ii).addClass("validate['required']");
$('last_name_enfant' + ii).addClass("validate['required','nodigit']");
$('first_name_enfant' + ii).addClass("validate['required','nodigit']");
}
// or...
while(val--) {
$('jj_enfant' + val).addClass("validate['required']");
$('mm_enfant' + val).addClass("validate['required']");
$('aaaa_enfant' + val).addClass("validate['required']");
$('last_name_enfant' + val).addClass("validate['required','nodigit']");
$('first_name_enfant' + val).addClass("validate['required','nodigit']");
}
This isn't a Mootools question, just a javascript question.
for (var counter = 1; counter < val; counter++) {
//Loop code
}
Related
The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1
In this piece of code you can see a JSON request that fetches some data. I need some help to check certain opportunities of minimizing the code and getting iterations with FOR instead of many IFs. Also, it would be nice if you advise anything on the differentiation system (how to make elements differ from each other)
<script type="text/javascript">
function deleteRow0() {
$('p.row0').remove();
};
function deleteRow1() {
$('p.row1').remove();
};
function deleteRow2() {
$('p.row2').remove();
};
function deleteRow3() {
$('p.row3').remove();
};
function deleteRow4() {
$('p.row4').remove();
};
</script>
<script type="text/javascript">
function hello2() {
//GETTING JSON INFO
$.getJSON("https://rawgit.com/Varinetz/e6cbadec972e76a340c41a65fcc2a6b3/raw/90191826a3bac2ff0761040ed1d95c59f14eaf26/frontend_test_table.json", function(json) {
$('#table-cars').css("display", "grid");
for (let counter = 0; counter < json.length; counter++) {
$('#table-cars').append("<p class='row" + counter +" main-text'>" + json[counter].title + "<br/>" + "<span class='sub-text'>" + json[counter].description + "</span>" + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].year + "</p>"
+ "<p id='color" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].color + "</p>"
+ "<p id='status" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].status + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].price + " руб." + "</p>"
+ "<p class='row" + counter +" main-text'>" + "<button class='delete' onclick='deleteRow" + [counter] + "()'>Удалить</button>" + "</p>");
// COLOR TEXT REPLACEMENT
if ($('p#color0').text("red")){
$('p#color0').text("").append("<img src='red.png'>");
}
if ($('p#color1').text("white")) {
$('p#color1').text("").append("<img src='white.png'>");
}
if ($('p#color2').text("black")) {
$('p#color2').text("").append("<img src='black.png'>");
}
if ($('p#color3').text("green")) {
$('p#color3').text("").append("<img src='green.png'>");
}
if ($('p#color4').text("grey")) {
$('p#color4').text("").append("<img src='grey.png'>");
}
// STATUS TEXT REPLACEMENT
if ($('p#status0').text("pednding")) {
$('p#status0').text("").append("Ожидается");
}
if ($('p#status1').text("out_of_stock")) {
$('p#status1').text("").append("Нет в наличии");
}
if ($('p#status2').text("in_stock")) {
$('p#status2').text("").append("В наличии");
}
if ($('p#status3').text("out_of_stock")) {
$('p#status3').text("").append("Нет в наличии");
}
if ($('p#status4').text("in_stock")) {
$('p#status4').text("").append("В наличии");
}
}
});
}
</script>
I expect this to be something like:
1) Iteration: For each p.row(i) {
compare it to many color (json.color)};
2) Any suggestion on differentiation system (i.e. changes in the FOR section, so it gives something easier to work with, not just simple p.row(n)). Of course, if it is possible.
I'm not going to rewrite the entire script, but in principle it would be something like this:
for (i = 0; i < 5; i++) {
var colors = ["red", "white", "black", "green", "grey"];
if ($('p#color' + i).text() == colors[i]){
$('p#color' + i).text("").append("<img src='" + colors[i] + ".png'>");
}
}
#Evik Ghazarian has a quality solution for the Text Translation portion of your script. Since this is the accepted answer, he allowed me to copy his solution so that the answers would be together:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}
Dynamic Iteration Counters
#Barmar mentioned in the comments below that the for loops that set a max iteration via i < 5 should actually be rewritten dynamically. I'll leave it to the OP to decide the best way to do this, but a good example might be something like i < json.length as used in the OP's original for loop.
First of all your code won't work because you are setting the text rather than comparing it. Second, you don't need to compare: just set the img src to text. Like below:
REMEMBER THIS IS FOR COLOR TEXT REPLACEMENT PART OF YOUR QUESTION
for (let i = 0; i < 5 , i ++){
let color = $("p#color"+i).text() + ".png";
$("p#color"+i).text("").append("<img src=" + color + ">");
}
FOR TEXT TRANSLATION YOU CAN USE:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}
I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}
I am new to jQuery and I cant seem to get the following code working..
for ( var i = 0; i < 2; i++ ) {
$status[i] = $('select[name="status'+ i +'"] option:selected').val();
$odd_a[i] = $("input:text[name='odd_a"+ 1 +"']").val();
$odd_b[i] = $("input:text[name='odd_b"+ 1 +"']").val();
$term[i] = $("select[name='term"+ 1 +"'] option:selected").val();
$dh_place[i] = $("input:text[name='dh_place"+ 1 +"']").val();
$dh_total[i] = $("input:text[name='dh_total"+ 1 +"']").val();
}
I have several text boxes "status1, status2, status3 etc. I need to call their name by the for loop. If I replace the "i" with the "1" it works. I cant seem to call the variable "i" at that position.
Try with
$status[i] = $('select[name="status'+ i +'"]').val();
and You need to start i value from 1 like
for ( var i = 1; i < 2; i++ ) {
One problem I can see is the i starts with 0 where as your input starts with 1, so the first loop will not return any elements.
for (var i = 0; i < 2; i++) {
$status[i] = $('select[name="status' + (i + 1) + '"]').val();
$odd_a[i] = $("input:text[name='odd_a" + (i + 1) + "']").val();
$odd_b[i] = $("input:text[name='odd_b" + (i + 1) + "']").val();
$term[i] = $("select[name='term" + (i + 1) + "']").val();
$dh_place[i] = $("input:text[name='dh_place" + (i + 1) + "']").val();
$dh_total[i] = $("input:text[name='dh_total" + (i + 1) + "']").val();
}
The script below generates random numbers, and calculates the answer.
The next thing is that I want to have the answer HIDDEN and place a text area there. Then you have to input an answer and when the answer is correct, it should make the answer green.
I know it is possible, but I've searched on the internet for it without success, so I'm creating a question instead.
Here's the script:
<div id="breuken"></div>
$(function () {
var number = document.getElementById("breuken");
var i = 0;
for (i = 1; i <= 10; i++) {
var sRandom = Math.floor(Math.random() * 10);
var fRandom = Math.floor(sRandom + Math.random() * (10 - sRandom));
var calc = Math.abs(fRandom - sRandom);
number.innerHTML += "" + fRandom + " - " + sRandom + " = " + calc + "<br />";
}
number.innerHTML;
});
Try this http://jsfiddle.net/r4QTQ/
It does basic green color change but should be enough for you to modify and do exactly what you want.
Created this jQuery demo that might help you in the right direction, if you´re using jQuery.
var $questions = $('<div />').attr('id', 'questions');
for (var i = 1; i <= 3; i++) {
var question = "Question " + i + "?";
var answer = i;
$questions.append(
$('<div />')
.attr('id', 'question' + i)
.addClass('question')
.append(
$('<span />').text(question)
)
.append(
$('<input type="text" />')
.addClass('answer')
.data('answer', answer)
)
);
}
$('#container').empty().append($questions);
Hope it helps!
This answers does practically the same as #gillesc's but uses jQuery to do the heavy lifting, which you should use if you have it at hand. (and is shorter)
Javascript code: jsFiddle
$(function() {
var checkAnswer = function(elem) {
if ($(elem).data('calc') == $(elem).val()) {
$(elem).css('background-color', 'green');
} else {
$(elem).css('background-color', 'white');
}
};
var div = $('#breuken');
for (var i = 0; i < 10; i++) {
var sRandom = Math.floor(Math.random() * 10);
var fRandom = Math.floor(sRandom + Math.random() * (10 - sRandom));
var calc = Math.abs(fRandom - sRandom);
var qa = $('<span>' + fRandom + ' - ' + sRandom +
' = <input type="text"></span><br />');
qa.find('input').change(function() {
checkAnswer(this);
}).data('calc', calc);
div.append(qa);
}
});