Loop for tabbing - javascript

HI i am pretty new to javascript,
following is my scenario, i want to make a function in which i pass the value of 'n' for number of iterations. i am writing my test script in javascript.
var tab6 = browser.actions().sendKeys(protractor.Key.TAB);
tab6.perform();
page.pause(3);
var tab7 = browser.actions().sendKeys(protractor.Key.TAB);
tab7.perform();
page.pause(3);
var tab8 = browser.actions().sendKeys(protractor.Key.TAB);
tab8.perform();
page.pause(3);
var tab9 = browser.actions().sendKeys(protractor.Key.TAB);
tab9.perform();
page.pause(3);
var tab10 = browser.actions().sendKeys(protractor.Key.TAB);
tab10.perform();
page.pause(3);
var tab11 = browser.actions().sendKeys(protractor.Key.TAB);
tab11.perform();
page.pause(3);

is this what you want ?
function performTab(n) {
for (var i = 0; i < n; i++) {
var tab = browser.actions().sendKeys(protractor.Key.TAB);
tab.perform();
page.pause(3);
}
}
If not, please, be more precise.

You want to count how many times you press tab, following a predetermined direction?
i'm really having a hardtime understanding what you want.
document.onkeypress = tabCount;
var ix = 0;
function tabCount(e){
var charCode = (typeof event.which == "number") ? event.which : event.keyCode
if (charCode == 9) ix++;
}
<input type=button tabIndex=1>
<input type=button tabIndex=2>
<input type=button tabIndex=3>
<input type=button tabIndex=4>
<input type=button tabIndex=5>

in context of test scenario, I'd do:
function testTabs( n )
{
for ( let i = 1; i <= n; i++ )
{
it(`Select tab #{i}`, () => {
browser.actions().sendKeys( protractor.Key.TAB ).perform();
page.pause(3);
};
};
}

Related

How to reuse code block in javascript

I am new to learning javascript and apologize if this question is too basic. I have tried to search for a solution but nothing has been clear to me. I have created this code in this link.
https://jsfiddle.net/5p7wzy9x/3/
var btn = document.getElementById("calc");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
var totalTb = document.getElementById("total");
totalTb.value = count ? output : "NaN";
});
var btn = document.getElementById("calcTwo");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = (total / count);
var totalTb = document.getElementById("total");
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
My question is, how would I go about being able to use the same code for the second "grade" button without having to copy and pasting the same code?
I saw that you can use functions to invoke the same code block but am confused how I would go about it. I apologize if this question has already been answered, but I have diligently searched and tried to figure this out on my own. Thank you in advanced.
Instead of passing anonymous functions (functions with no names) to your event handlers as data:
btn.addEventListener("click", function() { ...
set up those functions as "function declarations" so that you can call them by name. Then, instead of passing them into the .addEventListner() method call, you reference them by name (without parenthesis next to the name).
Here's an example:
// Both buttons are configured to call the same event handling function:
document.getElementById("btn1").addEventListener("click", doSomething);
document.getElementById("btn2").addEventListener("click", doSomething);
function doSomething(){
console.log("Hello!");
}
<input type=button id="btn1" value="Click Me">
<input type=button id="btn2" value="Click Me">
Here is how you can combine common code in one function:
var btn = document.getElementById("calc");
var btn2 = document.getElementById("calcTwo");
var totalTb = document.getElementById("total");
btn.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output < Infinity ? output : "NaN";
});
btn2.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
function getTotal() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
return output;
}
<form id="form1">
<input class="value" type="text" value="80" /><br />
<input class="value" type="text" value="50" /><br />
<input class="value" type="text" value="15" /><br />
<input class="value" type="text" value="30" /><br />
<input class="value" type="text" value="90" /><br />
<br />
<input type="text" id="total" />
<button type="button" id="calc">Calculate</button>
<button type="button" id="calcTwo">Grade</button>
</form>

Make calculation based on information provided

I am building a website and I want to do calculations based on information provided. I obviously need to have information provided in two out of the three fields to calculate the third's value.
The three fields are:
Price Per Gallon
Gallons Bought
Total Sale
I obviously know that I can calculate the amount of gas bought by dividing the Total Sale amount by the Price Per Gallon.
However I want to calculate based on whatever two fields are entered. I am trying to find out the best way to do this.
I know this much:
Check to see which fields are empty
Determine which type of calculation to make
Here is what I have so far:
<form>
<input type="number" id="totalSale" placeholder="Total Sale Amount" class="calculate" />
<input type="number" id="gallonPrice" placeholder="Price Per Gallon" class="calculate" />
<input type="number" id="gallons" placeholder="Gallons" class="calculate" />
</form>
<script>
var e = document.getElementsByClassName("calculate");
function calc(){
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
if (sale_amt || ppg !== null) {
var calc_gallons = sale_amt.value / ppg.value;
gallons.value = calc_gallons.toFixed(3);
}
}
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
}
</script>
the logic should take into consideration which element is currently being entered (that will be this in calc). Also, you need to take into consideration what happens when all three have values, and you change one ... which of the other two should be changed?
See if this works for you
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
function calc(){
var els = [sale_amt, ppg, gallons];
var values = [sale_amt.value, ppg.value, gallons.value];
var disabledElement = els.find(e=>e.disabled);
var numValues = els.filter(e => e.value !== '' && !e.disabled).length;
var calc_gallons = function() {
gallons.value = (values[0] / values[1]).toFixed(3);
};
var calc_ppg = function() {
ppg.value = (values[0] / values[2]).toFixed(3);
};
var calc_sale = function() {
sale_amt.value = (values[1] * values[2]).toFixed(2);
};
if (numValues < 3) {
if (numValues == 1 && disabledElement) {
disabledElement.disabled = false;
disabledElement.value = '';
disabledElement = null;
}
els.forEach(e => e.disabled = e == disabledElement || (numValues == 2 && e.value === ''));
}
disabledElement = els.find(e=>e.disabled);
switch((disabledElement && disabledElement.id) || '') {
case 'totalSale':
calc_sale();
break;
case 'gallonPrice':
calc_ppg();
break;
case 'gallons':
calc_gallons();
break;
}
}
var e = document.getElementsByClassName("calculate");
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
e[i].addEventListener('change', calc, false);
}

Unable to call function within jQuery

I am trying to call a function in this javascript code. My code needs to check for whether the user selects var num, var letters and var symbols to be true or false. In the code, I preset the values but I still search the object choices for the variables that are true and push it into the array choices_made. However, since I need to randomly choose the order in which the num, letters and symbols appear, I randomly choose the class based on the Math.random(). However, it doesn't show me the alert(jumbled_result) afterwards.
http://jsfiddle.net/bdaxtv2g/1/
HTML
<input id="num" type="text" placeholder="Enter desired length">
<br/><br/>
<input id="press" type="button" value="jumble it up">
JS
$(document).ready(function(){
var fns={};
$('#press').click(function(){
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
function gen(len, num, letters, sym){
var choices = {
1:num,
2:letters,
3:sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for(x in choices){
if(choices[x]==true){
choice_made.push(x);
}
}
for(i=0;i<len;i++){
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length-1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result){
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
});
You never declare functions within document.ready of jQuery. The functions should be declared during the first run(unless in special cases).
Here is a working code made out of your code. What I have done is just removed your functions out of document.ready event.
$(document).ready(function() {
$('#press').click(function() {
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
});
var fns = {};
function gen(len, num, letters, sym) {
var choices = {
1: num,
2: letters,
3: sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for (x in choices) {
if (choices[x] == true) {
choice_made.push(x);
}
}
for (i = 0; i < len; i++) {
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length - 1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result) {
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="num" type="text" placeholder="Enter desired length">
<br/>
<br/>
<input id="press" type="button" value="jumble it up">
Its because of the way the object choices have been intitialized.. Try this..
var choices = {
0:num,
1:letters,
2:sym
};
And also
var choice_made = [];
JS fiddle link : http://jsfiddle.net/8dw7nvr7/2/

Sorting table using javascript sort()

I am trying to sort a table. I've seen several jQuery and JavaScript solutions which do this through various means, however, haven't seen any that use JavaScript's native sort() method. Maybe I am wrong, but it seems to me that using sort() would be faster.
Below is my attempt, however, I am definitely missing something. Is what I am trying to do feasible, or should I abandon it? Ideally, I would like to stay away from innerHTML and jQuery. Thanks
var index = 0; //Index to sort on.
var a = document.getElementById('myTable').rows;
//sort() doesn't work on collection
var b = [];
for (var i = a.length >>> 0; i--;) {
b[i] = a[i];
}
var x_td, y_td;
b.sort(function(x, y) {
//Having to use getElementsByTagName is probably wrong
x_td = x.getElementsByTagName('td')[index].data;
y_td = y.getElementsByTagName('td')[index].data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
A td element doesn't have a .data property.
If you wanted the text content of the element, and if there's only a single text node, then use .firstChild before .data.
Then when that is done, you need to append the elements to the DOM. Sorting a JavaScript Array of elements doesn't have any impact on the DOM.
Also, instead of getElementsByTagName("td"), you can just use .cells.
b.sort(function(rowx, rowy) {
x_td = rowx.cells[index].firstChild.data;
y_td = rowy.cells[index].firstChild.data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
var parent = b[0].parentNode;
b.forEach(function(row) {
parent.appendChild(row);
});
If the content that you're comparing is numeric, you should convert the strings to numbers.
If they are text strings, then you should use .localeCompare().
return x_td.localeCompare(y_td);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>All Sorting Techniques</title>
<script type="text/javascript">
var a = [21,5,7,318,3,4,9,1,34,67,33,109,23,156,283];
function bubbleSort(a)
{
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("bublsrt").innerHTML = "Bubble Sort Result is: "+a;
}
var b = [1,3,4,5,7,9,21,23,33,34,67,109,156,283,318];
function binarySearch(b, elem){
var left = 0;
var right = b.length - 1;
while (left <= right){
var mid = parseInt((left + right)/2);
if (b[mid] == elem)
return mid;
else if (b[mid] < elem)
left = mid + 1;
else
right = mid - 1;
}
return b.length;
}
function searchbinary(){
var x = document.getElementById("binarysearchtb").value;
var element= binarySearch(b,x);
if(element==b.length)
{
alert("no. not found");
}
else
{
alert("Element is at the index number: "+ element);
}
}
function quicksort(a)
{
if (a.length == 0)
return [];
var left = new Array();
var right = new Array();
var pivot = a[0];
for (var i = 1; i < a.length; i++) {
if (a[i] < pivot) {
left.push(a[i]);
} else {
right.push(a[i]);
}
}
return quicksort(left).concat(pivot, quicksort(right));
}
function quicksortresult()
{
quicksort(a);
document.getElementById("qcksrt").innerHTML = "Quick Sort Result is: "+quicksort(a);
}
function numeric(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
function insertionsorting(a)
{
var len = a.length;
var temp;
var i;
var j;
for (i=0; i < len; i++) {
temp = a[i];
for (j=i-1; j > -1 && a[j] > temp; j--) {
a[j+1] = a[j];
}
a[j+1] = temp;
}
document.getElementById("insrtsrt").innerHTML = "Insertion Sort Result is: "+a;
}
function hiddendiv()
{
document.getElementById("binarytbdiv").style.display = "none";
document.getElementById("Insertnotbdiv").style.display = "none";
}
function binarydivshow()
{
document.getElementById("binarytbdiv").style.display = "block";
}
function insertnodivshow()
{
document.getElementById("Insertnotbdiv").style.display = "block";
}
function insertno(a)
{
var extrano = document.getElementById("Insertnotb").value;
var b= a.push(extrano);
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("insrtnosearch").innerHTML = "Sorted List is: "+a;
alert("Index of "+extrano +" is " +a.indexOf(extrano));
}
</script>
</head>
<body onload="hiddendiv()">
<h1 align="center">All Type Of Sorting</h1>
<p align="center">Your Array is : 21,5,7,318,3,4,9,1,34,67,33,109,23,156,283</p>
<div id="main_div" align="center">
<div id="bubblesort">
<input type="button" id="bubblesortbutton" onclick="bubbleSort(a)" value="Bubble Sort">
<p id="bublsrt"></p>
</div><br>
<div id="quicksort">
<input type="button" id="quicksortbutton" onclick="quicksortresult()" value="Quick Sort">
<p id="qcksrt"></p>
</div><br>
<div id="insertionsort">
<input type="button" id="insertionsortbutton" onclick="insertionsorting(a)" value="Insertion Sort">
<p id="insrtsrt"></p>
</div><br>
<div id="binarysearch">
<input type="button" id="binarysearchbutton" onclick="binarydivshow();" value="Binary Search">
<div id="binarytbdiv">
<input type="text" id="binarysearchtb" placeholder="Enter a Number" onkeypress="numeric(event)"><br>
<input type="button" id="binarysearchtbbutton" value="Submit" onclick="searchbinary()">
<p id="binarysrch">Sorted List is : 1,3,4,5,7,9,21,23,33,34,67,109,156,283,318</p>
</div>
</div><br>
<div id="Insertno">
<input type="button" id="insertno" onclick="insertnodivshow()" value="Insert A Number">
<div id="Insertnotbdiv">
<input type="text" id="Insertnotb" placeholder="Enter a Number" onkeypress="numeric(event);"><br>
<input type="button" id="Insertnotbbutton" value="Submit" onclick="insertno(a)">
<p id="insrtnosearch"></p>
</div>
</div>
</div>
</body>
</html>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources