I'am trying (without luck) to implement a Swal inside a If statement.
here is what i've done:
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("numero");
//check if try to copy with the empty input
if(document.getElementById("numero").value == ""){
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Nothing to copy!'
})
// alert("Nothing to copy!!")
} else {
}
And here is the links in my html:
<!-- dark theme for swal -->
<link href="//cdn.jsdelivr.net/npm/#sweetalert2/theme-dark#4/dark.css" rel="stylesheet">
<!-- javascript file -->
<script src="app.js"></script>
<!-- swal link -->
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
Any tip to how can I make this work? I guess my problem is inside the If statement, but I don't know how to fix it
In your code, I am not seeing an event listener. Use keyup to verify that the value of the elemnt is empty.
var copyText = document.getElementById("numero");
copyText.addEventListener('keyup', () => {
if (document.getElementById("numero").value == "") {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Nothing to copy!'
})
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<head>
<link href="//cdn.jsdelivr.net/npm/#sweetalert2/theme-dark#4/dark.css" rel="stylesheet">
<script src="app.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
</head>
</head>
<body>
<input type="text" id="numero">
</body>
</html>
First of all, make sure your imports are correct. You can try debugging by using something simple like: swal("Hello world") anywhere in your code.
I roughly copied yours and used a different CDN import from the Swal documentation on their website:
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
In your Javascript code, you're missing a } at the end of your function. Might also be a miscopy, but never too sure.
Also, if you want to make sure your if statement is correct, you can try debugging with console.log("Hello world") at every fork in your code. Then, open the console in your browser to see what is logged. This will help you figure out whether or not your code is running when you want it to.
Also, watch out when you use document.getElementById("numero").value. For instance, your code wouldn't work with <p> because <p> has no value, but it would with <input> or <option>.
Here is a sample of code that is working on my end:
function myFunction() {
var copyText = document.getElementById("numero");
if (document.getElementById("numero").innerHTML == "") {
swal({
icon: 'error',
title: 'Oops...',
text: 'Nothing to copy!'
})
} else {
swal("Copied!")
}
}
end up that everything was working nice, but... I forget to put this in my code
event.preventDefault()
That prevent the Swal to not work well.
By the end, the final code went like this:
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("numero");
if(document.getElementById("numero").value == ""){
Swal.fire(
'Ooops...',
'Nothing to copy here!',
'error'
)
event.preventDefault()
} else {}
/*code here
}
Thanks for giving me that tips guys 😉
Related
I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?
Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.
document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>
I am getting the error "cannot read property'innerHTML' of null" at line 11 in the file letterbyletter.js. Its code is this:
function printLetterByLetter(destination, message, speed){
let h = 0;
var interval = setInterval(function(){
if (h===0) {
stop=false
}
if (h > message.length||(stop===true&&h!==0)){
clearInterval(interval);
stop=false
}else if (message.charAt(h)!=="<") {
document.getElementById(destination).innerHTML += message.charAt(h);
h++;
}else {
document.getElementById(destination).innerHTML += "<br>"
h+=4
}
}, speed);
}
It is being called here:
function run(num9) {
if (stats[3][1]>enemies[num9].speed) {
let r=Math.ceil(Math.random()*100)
if (r>=50) {
battlechk=false
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox","You escaped from "+enemies[num9].name+"!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"supdateGUI3()\">Confirm</button>"
}else {
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox",enemies[num9].name+" blocks your path! "+enemies[num9].name+" attacks you!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"battle("+num9+")\">Confirm</button>"
}
}else {
let r=Math.ceil(Math.random()*100)
if (r>=90) {
battlechk=false
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox","You escaped from "+enemies[num9].name+"!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"supdateGUI3()\">Confirm</button>"
}else {
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox",enemies[num9].name+" blocks your path! "+enemies[num9].name+" attacks you!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"battle("+num9+")\">Confirm</button>"
}
}
battle(num9)
}
Every one of the calls in the above code cause the same error. A deeper look reveals that the textbox is there when printLetterByLetter is called and that the destination is textbox. When I console logged document.getElementById(destination) I got null. printLetterByLetter has worked every other time I have used it and I haven't gotten an error when I have used other commands that are similar. My entire code can be found here: https://github.com/Fish767/Space-Clones. The files in question are run.js and letterbyletter.js. Destination is a string and the line before I called printLetterByletter I added the element with an id of textbox.
Steps to reproduce: press move and left twice and then move and explore until you get into a battle. Then press run.
The html doc is this:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/first.css">
<title id="title">Lives in Space</title>
</head>
<body id="body">
<script src="js/globalvars.js"></script>
<script src="js/sleep.js"></script>
<script src="js/letterbyletter.js"></script>
<script src="js/format.js"></script>
<script src="js/cleardoc.js"></script>
<script src="js/doEffects.js"></script>
<script src="js/use.js"></script>
<script src="js/toss.js"></script>
<script src="js/battleresults.js"></script>
<script src="js/friend.js"></script>
<script src="js/run.js"></script>
<script src="js/attack.js"></script>
<script src="js/battle.js"></script>
<script src="js/event.js"></script>
<script src="js/explore.js"></script>
<script src="js/moveto.js"></script>
<script src="js/second.js"></script>
<script src="js/rpgland.js"></script>
<script src="js/loop.js"></script>
</body>
</html>
I can easily do what I want in another way. What I am asking is why doesn't this way work.
I cloned the repo.
There is no "#textbox" in DOM when the error happen, it was replaced with "#statsbox" on battle function. You'll want to use chrome dev tool to debug step by step and it'll help you develop this game more easier also.
Happy coding!
It is because when you click the "confirm" button, you execute battle(0), and the first instruction in this function is to overwrite the entire DOM : document.getElementById("body").innerHTML="<div id=\"statsbox\"></div><div id=\"option-container\"></div>". So everything else disappears.
The reason why you can console.log the element at the beginning of printLetterByLetter() and then 10 lines later it logs null is because those 10 lines are within a setInterval which gets executed later, at the end of the lifecycle. The DOM has been overwritten in-between.
I've added a web resource in the shape of a button onto a form in our CRM online instance. I've been debugging for a while now and I don't understand what I'm missing here.
Below is the web resource (I've omitted the javascript URL for obvious reasons)
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<button onclick="TriggerNPS()" class=".btn-default">
<i class="glyphicon glyphicon-check"></i>
Send NPS Now
</button>
<script src="Javascript URL" type="text/javascript"></script>
</body>
</html>
Javascript that the URL links to
function TriggerNPS() {
var NoTick = parent.Xrm.Page.getAttribute("ondemandnps").getValue();
if ((NoTick) ==null);
parent.Xrm.Page.getAttribute("ondemandnps").setValue("1");
parent.Xrm.Page.data.entity.save();
return
if ((NoTick) !=null)
parent.Xrm.Page.getAttribute("ondemandnps").setValue("0");
parent.Xrm.Page.data.entity.save();
return;
}
What I'm seeing is that if the field which this is looking at (tick box) contains data, then sure it strips the tic. However if the box is empty. I cannot get the script to add the check. Testing this in the console though the command does work. It runs over the lines and doesn't step out of them, but does nothing.
Any help will be appreciated.
Maybe try this:
function TriggerNPS() {
var NoTick = parent.Xrm.Page.getAttribute("ondemandnps").getValue();
if (NoTick == null) {
parent.Xrm.Page.getAttribute("ondemandnps").setValue(true);
}
else {
parent.Xrm.Page.getAttribute("ondemandnps").setValue(false);
}
parent.Xrm.Page.data.entity.save();
}
I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}
I am new to Javascript.
I am making my first Adventure Game.
I tested the following code out with an onClick and it worked fine:
// JavaScript Document
function changeColour()
{
if (document.getElementById('colourTest').style.backgroundColor='yellow')
{
document.getElementById('colourTest').style.backgroundColor='red';
}
else
{
document.getElementByID('colourTest').style.backgroundColor='yellow';
}
}
var direction;
direction = prompt("Which direction would you like to go ?");
if ( direction == "North" )
{
changeColour();
}
else
{
console.log("You can't go in that direction ?");
}
This is the HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script language="javascript" type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body>
<div id="colourTest">
</div>
</body>
</html>
I want the Yellow div to turn red when the user enters the word North, otherwise, the user is told that they can't go in that direction.
I am sure that this is some kind of syntax error :D
Hi, Here is an update:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<script type="text/javascript" ></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body onload="load();">
<img id="myimg" alt="My Image" src="images/image1.jpg" />
<form>
<input name="heading" type="text" id="which" value="" />
</form>
</body>
</html>
Here is JS:
// JavaScript Document
var img = new Image();
img.src = "images/image1.jpg";
function whichImage(b)
{
var image = document.getElementById("myimg");
if (b == "North")
{
image.src = "images/image2.jpg";
}
else
{
image.src = "images/image1.jpg";
}
}
function whichDirection (x)
{
if (x == "North" || x == "South" || x == "East" || x == "West" )
{
document.write("You choose to go " + direction);
}
else
{
document.write("You can't go in that direction");
}
}
function load()
{
var direction = document.getElementById('which').value;
whichDirection(direction);
whichImage(direction);
}
I don't understand why the input direction from the user isn't allowing the image to change to image2.jpg, when the word, North is input by the user.
Can JS actually capture text input from html and then use this with variables in functions?
More over, with this version, the DOM doesn't seem to have loaded, as there is no image to be seen.
The two errors I see right away (there may be more) are...
if (document.getElementById('colourTest').style.backgroundColor='yellow')
You're assigning instead of comparing. Use == for comparison (as you do elsewhere). And...
document.getElementByID('colourTest').style.backgroundColor='yellow';
JavaScript is case-sensitive. The function name should be getElementById (as you do elsewhere).
In this case there was a logical error and a syntax error. The latter can often be noticed by looking at the JavaScript console in your browser's debugging tools. If it tried to execute that line of code, you'd see an error there. Logical errors, on the other hand, can be trickier to pinpoint. For those you'll want to familiarize yourself with the debugger in your browser's debugging tools.
You can click on a specific line of JavaScript code to set a "breakpoint" where the execution of code will pause. Once paused, you can examine the runtime values of your variables, step through the execution line-by-line to check its behavior, etc. This is how you validate that the code is doing what you expect it to do.