All buttons have same width - jQuery - javascript

Im programming a calculator and Im trying that all the buttons in the same column has the same width. For that Im using jQuery (Im doing it this way cause I have an exam in some days and I wanna practice).
My HTML code:
<html>
<head>
<meta charset="UTF-8">
<title>CORE2017 P3</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="calculadora.js"></script>
<link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
</head>
<body onload="igualarBotones()">
<header>
<p>Calculator</p>
</header>
<section id="main">
<p>
Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
</p>
<p>
<button id="suma" class="columna1">+</button>
<button id="resta" class="columna2">-</button>
<button id="cuadrado" class="columna3">x<sup>2</sup></button>
</p>
<p>
<button id="inverso" class="columna1">1/x</button>
<button id="raiz" class="columna2">sqrt(x)</button>
<button id="pentera" class="columna3">parte_entera(x)</button>
</p>
<p>
<button id="potencia2" class="columna1">2<sup>x</sup></button>
<button id="factorial" class="columna2">x!</button>
<button id="igual" class="columna3">=</button>
</p>
</section>
</body>
</html>
My JavaScript code:
$(function() {
function igualarBotones(){
var columna1 = $(".columna1");
setMax(columna1);
var columna2 = $(".columna2");
setMax(columna2);
var columna3 = $(".columna3");
setMax(columna3);
}
function setMax(columna){
var maxColumna = -1;
for(i=0; i<columna.length; i++){
if(columna[i].css("width") > maxColumna){
maxColumna = columna[i].css("width");
}
}
for(i=0; i<columna.length; i++){
columna[i].css("width",maxColumna);
}
}
});
Anyone knows why it isnt working?
EDIT: I used $(columna[i]).css instead of columna[i].css and it worked. However I dont achieve that my function igualarBotones() gets defined when loading the body, I think it must be something related to how I named or wrote the function. If I write the Javascript this way:
$(function() {
var columna1 = $(".columna1");
setMax(columna1);
var columna2 = $(".columna2");
setMax(columna2);
var columna3 = $(".columna3");
setMax(columna3);
function setMax(columna){
var maxColumna = -1;
for(i=0; i<columna.length; i++){
if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
maxColumna = $(columna[i]).css("width");
}
}
columna.css("width",maxColumna);
}
});
it works, but I want to do it with a function igualarBotones() that gets loaded with the body. Any idea what am I doing wrong?
Thank you all, Luis.

The issue is understanding the different between jquery representation of elements and "raw" elements in javascript.
Given var columna1 = $(".columna1"); what this means is that it will return a jquery object that is a collection of all elements that the selector (.column1 in this case) has specified.
When you iterate through this jquery collection (columna[i]) you don't get a jquery representation of the elements but actually the raw elements themselves (or a native javascript representation of the elements). Native javascript elements do not have a .css function.
So when you wrap each element around $(...) by doing this $(columna[i])you are then once again dealing with a jquery representation of each element and as such you are able to use .css. That is why the former does not work and the later works.
EXTRA SUGGESTION
Since you are learning jquery let me add this: Jquery has a .each function that you should actually use to loop over a jquery object that contains elements.
So this function:
function setMax(columna){
var maxColumna = -1;
for(i=0; i<columna.length; i++){
if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
maxColumna = $(columna[i]).css("width");
}
}
columna.css("width",maxColumna);
}
Could/Should be:
function setMax(columna){
var maxColumna = -1;
columna.each(function(){
// note the use of "this" to represent each
// element currently being iterated over.
// this = raw element, $(this) = jquery object representing element.
if(parseFloat($(this).css("width")) > parseFloat(maxColumna)){
maxColumna = $(this).css("width");
}
});
columna.css("width",maxColumna);
}
LAST TIP
I personally assist/help myself remember jquery object in my javascript code by prepending $ to all variables that are jquery objects so as to not forget them.
So this:
var columna1 = $(".columna1");
Would be:
var $columna1 = $(".columna1");

I'm not familiar with a .css function in vanilla javascript. I changed that so it would call the jQuery .css function. Also, at least in the pen, the function wasn't defined when the body was loading. Something is still off in how you're finding the max size, but this should get you started.
function igualarBotones(){
var columna1 = $(".columna1");
setMax(columna1);
var columna2 = $(".columna2");
setMax(columna2);
var columna3 = $(".columna3");
setMax(columna3);
}
function setMax(columna){
var maxColumna = -1;
for(var i=0; i<columna.length; i++){
if($(columna[i]).css("width") > maxColumna){
maxColumna = $(columna[i]).css("width");
}
}
for(i=0; i<columna.length; i++){
$(columna[i]).css("width",maxColumna);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<title>CORE2017 P3</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="calculadora.js"></script>
<link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
</head>
<body onload="igualarBotones();">
<header>
<p>Calculator</p>
</header>
<section id="main">
<p>
Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
</p>
<p>
<button id="suma" class="columna1">+</button>
<button id="resta" class="columna2">-</button>
<button id="cuadrado" class="columna3">x<sup>2</sup></button>
</p>
<p>
<button id="inverso" class="columna1">1/x</button>
<button id="raiz" class="columna2">sqrt(x)</button>
<button id="pentera" class="columna3">parte_entera(x)</button>
</p>
<p>
<button id="potencia2" class="columna1">2<sup>x</sup></button>
<button id="factorial" class="columna2">x!</button>
<button id="igual" class="columna3">=</button>
</p>
</section>
</body>
</html>

Related

Block all inappropriate words in the textbox when click button

Below is my code which show me notice of inserting kill , fight, slap when i insert in the textbox.
But i want to block all inappropriate words possible in the textbox like f**k and so on. DO you guys have any ideas. Thanks
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="wrapper" style="width:600px; margin:0 auto;">
<h2></h2>
<input id="txtWords" style="width:300px;" />
<br />
<input type="button" id="btnCheck" onclick="fnCheckForRestrictedWords();" value="Check For
Restricted Words">
</div>
<script type="text/javascript">
function fnCheckForRestrictedWords() {
var restrictedWords = new Array("kill", "fight", "slap");
var txtInput = document.getElementById("txtWords").value;
var error = 0;
for (var i = 0; i < restrictedWords.length; i++) {
var val = restrictedWords[i];
if ((txtInput.toLowerCase()).indexOf(val.toString()) > -1) {
error = error + 1;
}
}
if (error > 0) {
alert('You have entered some restricted words.')
}
else {
// Your logic here
}
}
</script>
</body>
</html>
You need to define all "bad" words and put them in your blacklist. You can use some existing lists as a starting point for your list:
https://github.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/blob/master/en
https://github.com/dariusk/wordfilter/blob/master/lib/badwords.json
http://www.bannedwordlist.com/lists/swearWords.txt
http://www.frontgatemedia.com/new/wp-content/uploads/2014/03/Terms-to-Block.csv
Source: Reddit
If you want to include obfuscated "bad" words you may need to add the to the list as well.
The
includes()
method should work: txtInput.includes(restrictedWords[i]) which returns either true or false. You also want to include more bad words and different ways to write them

How to get element inside other specific element using its id and getElementById?

I'm writing a really big script and performance is a big deal for me, especially that it has to work as fast as it can in IE (employer requirements). I have to do some innerHTML and stuff like that but for an element that has some class or id and is nested into some other element with some id or class.
I can do it using querySelector(), but as I saw in some performance tests for IE, querySelector is a few times slower than getElementById or even getElementsByClassName(). That's why I want to use these getElement... functions.
Here's an example:
<div id='firstID' class='someClass'>
<div id='secondID' class='someClass2'></div>
</div>
<div id='thirdID' class='someClass'>
<div id='secondID' class='someClass2'></div>
</div>
And I want to get this secondID element but it has to be one in firstID element. Like I said before, I can use querySelector('#firstID #secondID'); or a jQuery equivalent but it is much slower than getElementById() so I'm asking you how can I translate it into getElementById?
P.S. In my tests getElementById was performed 1 300 000 times per second whereas querySelector was perfomed about 400 000 times. So, you see where I'm getting with that.
Never ever use the same ID twice ( ID stand for identity and two elements can't have the same identity ). You can use the class name instead
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="a">
<div id="b" class="someClass2"></div>
</div>
<div id="c">
<div id="d" class="someClass2"></div>
</div>
<script type="text/javascript">
var parent = document.getElementById("a");
var childs = parent.getElementsByClassName("someClass2");
var firstSomeClass2Element = childs[0];
firstSomeClass2Element.innerHTML = "Example";
</script>
</body>
</html>
More about ID:
The Element.id property represents the element's identifier,
reflecting the id global attribute.
It must be unique in a document, and is often used to retrieve the
element using getElementById. Other common usages of id include using
the element's ID as a selector when styling the document with CSS.
https://developer.mozilla.org/es/docs/Web/API/Element/id
Here is the solution you need but is very very bad
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="a">
<div id="b" class="someClass2">a</div>
</div>
<div id="c">
<div id="b" class="someClass2">s</div>
</div>
<script type="text/javascript">
var parent = document.getElementById("a");
var childs = parent.childNodes;
for (var i = 0; i < childs.length; i++) {
if (childs[i].nodeType == Node.ELEMENT_NODE) {
if(childs[i].id == "b") {
console.log("Done");
}
}
}
</script>
</body>
</html>
Example with attached function
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="a">
<div id="b" class="someClass2">a</div>
</div>
<div id="c">
<div id="b" class="someClass2">s</div>
</div>
<script type="text/javascript">
HTMLElement.prototype.findId = function(_id) {
var childs = this.childNodes;
for (var i = 0; i < childs.length; i++) {
if(childs[i].nodeType == Node.ELEMENT_NODE) {
if(childs[i].id == _id) {
return childs[i];
}
}
}
return null;
}
// Usage Example
var parent = document.getElementById("a");
console.dir(parent.findId("b"));
</script>
</body>
</html>

What is the best way to implement previous and next page logic

I have a webpage which is a huge form (6 pages long). In order to make it more user friendly, I decided to break this down into different sections (div tags).
I have placed Previous and Next button on page. On previous click it should display the previous div tag I was at and next should display the next div tag. I was wondering what would be the best way to implement it? So far I have this function which I know is hardcoded for div tag called GeneralSection. Just like GeneralSection, I have 20 more sections. Any ideas how should I go about it ? Help appreciated! :)
$(document).ready(function () {
$("#imgNext").click(function () {
$("#GeneralSection").hide();
});
});
You could just iterate through an array of elements.
Here's a simple JSBin that should get you going: https://jsbin.com/siyutumizo/edit?html,js,output
$(document).ready(function() {
var $steps = $('.step');
var currentStep = 0,
nextStep;
$steps.slice(1).hide(); //hide all but first
$('#next').on('click', function(e) {
e.preventDefault();
nextStep = currentStep + 1;
if (nextStep == $steps.length) {
alert("You reached the end");
return;
}
$($steps.get(currentStep)).hide();
$($steps.get(nextStep)).show();
currentStep = nextStep;
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wizard">
<div class="step">1</div>
<div class="step">2</div>
<div class="step">3</div>
<div class="step">4</div>
<div class="step">5</div>
<div class="step">6</div>
</div>
<button id="next">Next</button>
</body>
</html>
Another way of implementing this is through siblings.
Jsbin: https://jsbin.com/tarajuyusu/edit?html,js,output
$(function() {
$('div#GeneralSection').slice(1).hide(); // hide all section, except for first one
$('#imgNext').on('click', function() {
var section = $('div#GeneralSection').filter(':visible');
if ($(section[0].nextElementSibling).attr('id') != "GeneralSection")
return;
section.hide();
$(section[0].nextElementSibling).show();
});
$('#imgPrev').on('click', function() {
var section = $('div#GeneralSection').filter(':visible');
if ($(section[0].previousElementSibling).attr('id') != "GeneralSection")
return;
section.hide();
$(section[0].previousElementSibling).show();
});
});
Give each section class pages and per section ids page-1, page-2 like that
$(document).ready(function () {
var pages = $(".pages").length;
$("#imgNext").click(function () {
var nextPageNo = parseInt($(".pages:visible")[0].id.split('-')[1])+1;
if(nextPageNo > pages)
return false;
$(".pages:visible").fadeout();
$("#page-"+nextPageNo).fadeIn();
});
});
Havent fully tetsted but this should get you going.
Update
HTML
<div id="container">
<div id="page-1" class="pages">1</div>
<div id="page-2" class="pages">2</div>
<div id="page-3" class="pages">3</div>
<div id="page-4" class="pages">4</div>
<div id="page-5" class="pages">5</div>
<div id="page-6" class="pages">6</div>
</div>
CSS
.pages{
display: none;
}
#page-1{
display: block;
}

Changing a paragraph via a text field using javascript

I want to type in text in a text field, press a button, and the text of a paragraph will change. What would I need to do for this to happen and is there an easier way to do it other than javascript?
Since I didn't know what I needed to do, here's the code I originally had:
<html>
<head>
<title>Moving Text</title>
<link rel="stylesheet" type="text/css" href="stlye.css">
</head>
<body>
<div id="text">
<p id="new">new text</p>
Main News:<input type="text" name="update"><br>
<input type="button" value="Update" onClick="update();">
<script type="text/javascript">
function update(){
document.getElementById('new').innerHTML = 'Update';
}
</script>
</div>
</body>
I'm pretty sure it's wrong or way off. Any suggestions?
HTML:
<p id="your_paragraph">This text will change, after clicking the button.</p>
Main News: <input type="text" id="theText" />
<input type="button" id="btn" value="Update" />
JavaScript:
var p = document.getElementById('your_paragraph');
var btn = document.getElementById('btn');
var txt = document.getElementById('theText');
btn.onclick = function(){
p.textContent = txt.value;
};
http://jsfiddle.net/3uBKC/
No, you'll need to use javascript. Without an example of your markup nobody will be able to provide you a specific example, but here's a general one using the jQuery library.
// get the textarea, watch for change, paste, and keyup events
$('textarea').on('change paste keyup', function(){
// Store the text field as a variable, get it's value
var thiis = $(this),
value = thiis.val();
// replace the paragraph's content with the textrea's value
$('p').html(value);
});

javascript for loop function

I have this index.html
<html>
<head>
<script type="text/javascript" src="scripts.js" > </script>
</head>
<body>
<center><h1>Images</h1></center>
<center>
<img id="b1" onclick="image()" src="1.jpg">
<img id="b2" onclick="image()" src="2.jpg">
<img id="b3" onclick="image()" src="3.jpg">
<img id="b4" onclick="image()" src="4.jpg">
</center>
</body>
</html>
and this scripts.js
function image(){
for(var i = 1; i < document.images.length; i++)
{
document.write(i);
}
when i click the first image it just show the number 1 on screen and the browser get stuck thinking.
why is doesnt show 123?
The reason why your loop isn't working is because the first time you call
document.write
it's removing all of the images from the page, and thus, reducing the length of the document.images node list to zero.
If you want to see 1234, instead of using document.write (which is deprecated anyway as Dai pointed out) use:
document.body.innerHTML += i;
Also, as Dai correctly points out, the first array index is 0 not 1, so your for loop should be as follows:
for(var i = 0; i < document.images.length; i++)
{
document.body.innerHTML += i;
}
Notice: var i = 0;
Array indexes start at 0 in ECMAscript, not 1, you'll need to rewrite your loop as so:
for(var i=0;i<document.images.length;i++) {
}
Note that document.write is now considered bad-practice as it triggers a lot of heavy-lifting in the browser's DOM and layout engines. Instead use document.createElement.

Categories