Hello im a little bit new on doing javascript and jquery please kinda help me on my problem. i would really appreciate it. Thank you!
On page 7-8 how can I remove the "disabled" on the "new game" button
Using jquery?
Here's the index.html:
<!DOCTYPE>
<html>
<head>
<link href="assets/css/blackjack.css" type="text/css" media="screen" rel="stylesheet">
<script src="assets/js/Modernizr.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/Mustache.js"></script>
<script src="assets/js/blackjack.js"></script>
</head>
<body>
<div class="wrapper">
<img src="assets/images/rocket-u-logo-large.png">
<h1>Blackjack</h1>
<p>Hi, thanks for stopping by our blackjack table. Pull up a chair and let's play...</p>
<div id="card-table">
<h2>Dealer</h2>
<div id="dealer-hand"></div>
<div id="status"></div>
<div id="player-hand"></div>
<h2>Player</h2>
<div id="player-options">
<button class="bj" id="new-game" disabled>New Game</button>
<button class="bj" id="hit">Hit</button>
<button class="bj" id="stand">Stand</button>
</div>
</div>
</div>
</body>
</html>
and Here's the js:
$('#bj').click(function () {
$('#hit').show();
$('#stand').show();
});
function initGame() {
var initErrors = [];
var errorMessage;
// Test if browser supports local storage
if (Modernizr.localstorage) {
// console.log("Local storage is supported.");
} else {
var errorStatus = "Local storage is not available"
// console.log(errorStatus);
initErrors.push(errorStatus);
}
// Test if browser supports mustache.js
var mustacheScript = $('script[src*="js/Mustache.js"]').length;
if (mustacheScript != 0) {
// console.log("Mustache loaded!");
} else {
var errorStatus2 = "Mustache not loaded."
// console.log(errorStatus2);
initErrors.push(errorStatus2);
}
function displayErrorMessage() {
// Test if initErrors array has any errors
if (initErrors.length != 0) {
if (errorStatus2 === undefined) {
errorStatus2 = "";
} else if (errorStatus === undefined) {
errorStatus = "";
}
var errorMessage = "Houston, we have a problem (" + errorStatus + ', ' + errorStatus2 + ").";
// console.log(errorMessage);
$('#status').append("<p>" + errorMessage + "</p>");
} else {
var successMessage = "Ready to play? Click 'New Game' to start...";
$('#status').append("<p>" + successMessage + "</p>");
// console.log(successMessage);
}
}
displayErrorMessage();
//Test 'boolean' return values
if (initErrors.length != 0) {
return false;
$('#new_game').attr("disabled", "disabled");
} else {
return true;
$('#new_game').removeAttr("disabled");
}
}
console.log(initGame());
$(document).ready(function () {
initGame();
});
You wrote the code yourself. but it was below return statement which will make it in accesible.
bring the return statement below
$('#new_game').removeAttr("disabled");
It should work.
You can try this:
$('#new_game').prop('disabled',false);
You can use anyone of listed below
$('#new_game').attr("disabled", false);
OR
$("#new_game").removeAttr("disabled");
OR
$("#new_game").prop("disabled",false);
$('#new-game').removeAttr('disabled');
Looks like your JS code has an error: in HTML <button class="bj" id="new-game", but in JS $('#new_game').removeAttr("disabled");. You use underscore instead of '-' in id.
Related
There are already some answers on this site but couldn't figure out what I need.
Using the answer accepted as good given here: How can I change text after time using jQuery?
But, instead of having an alert, I'd like to make it reload to its first message (adding full codes for clarity:
function nextMsg() {
if (messages.length == 0) {
// once there is no more message, I don't know how to start the script over (loop it)
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var messages = [
"Hello!",
"This is a website!",
"You are now going to be redirected.",
"Are you ready?",
"You're now being redirected..."
].reverse();
$('#message').hide();
nextMsg();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>
On another answer I had also find something similar, but I couldn't add fade in and fade out:
var example = [' link1', ' link2'];
textSequence(0);
function textSequence(i) {
if (example.length > i) {
setTimeout(function() {
document.getElementById("sequence").innerHTML = example[i];
textSequence(++i);
}, 5000); // milliseconds
} else if (example.length == i) { // Loop
textSequence(0);
}
}
<div id="sequence"></div>
This may seem like a simple answer, but while I understand html and css to an extent, jscript is still out of my reach, so an answer with some clarity onto it would be great.
Thanks to anyone that will answer.
Using pop in the first example is actively removing elements from your messages array - so you can't "start the script over" because you have basically destroyed your data.
Think of pop as taking an items out of a bag one at a time and throwing them away - obviously when there are no items left in the bag - you can't then start again trying to get items out of the bag - because there is nothing left in the bag.
function nextMsg(index) {
if (messages.length === index) {
nextMsg(0);
} else {
$('#message').html(messages[index])
.fadeIn(500)
.delay(1000)
.fadeOut(500, () => nextMsg(index + 1));
}
};
var messages = [
' link1',
' link2',
' link3',
' link4'
];
$('#message').hide();
nextMsg(0);
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
As you can see there is no need to copy or duplicate the data - nor is there any need to reverse the messages.
Simply use the message index to keep track of which message to display and loop the index.
You are using pop to empty the original list. You need to keep the original list in place in order to start over:
function nextMsg() {
if (messages.length == 0) {
messages = copy(originalMessages);
nextMsg();
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var originalMessages = [
"Hello!",
"This is a website!",
"You are now going to be redirected.",
"Are you ready?",
"You're now being redirected..."
].reverse()
var messages = copy(originalMessages);
function copy(x){
return JSON.parse(JSON.stringify(x));
}
$('#message').hide();
nextMsg();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>
Try it :
var example = [' link1', ' link2'];
textSequence(0);
function textSequence(i) {
$('#sequence').html(example[i])
$('#sequence').fadeIn(500)
if (example.length > i) {
setTimeout(function() {
$('#sequence').fadeOut(500);
setTimeout(function() {
textSequence(++i);
},600);
}, 5000);
} else if (example.length == i) { // Loop
textSequence(0);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id='sequence'></div>
Hi I am storing the input from user in localstorage using the alertify prompt in javascript but when trying to display the localstorage variable using innerhtml it is only showing the last prompt which a user is adding. adding the code and demo to explain my problem. I think the localstorage is working fine and it has something to do with the loop and the innerhtml not working outside the if condition maybe?
if (localStorage.getItem("username") === null) {
alertify.prompt( "What is your name?", function (e, str) {
if (e) {
var myname = str;
localStorage.setItem('username', myname);
document.getElementById("welcometext").innerHTML = localStorage.getItem("username");
} else {
alertify.error("You've clicked Cancel");
}
});
}
//add the status
if (localStorage.getItem("status") === null) {
alertify.prompt( "Are you assigned to any role as of now? (FT, PT, NA)", function (e, str3) {
if (e) {
var mystatus = str3;
localStorage.setItem('status', mystatus);
document.getElementById("registeredstatus").innerHTML = localStorage.getItem("status");
} else {
alertify.error("You've clicked Cancel");
}
});
}
//add the email
if (localStorage.getItem("email") === null) {
alertify.prompt( "What is your email?", function (e, str2) {
if (e) {
var myemail = str2;
localStorage.setItem('email', myemail);
document.getElementById("registeredemail").innerHTML = localStorage.getItem("email");
} else {
alertify.error("You've clicked Cancel");
}
});
}
//add the starting date
if (localStorage.getItem("date") === null) {
alertify.prompt( "When did you started your bootcamp training? FORMAT: (DD-MM-YEAR)", function (e, str4) {
if (e) {
var mydate = str4;
localStorage.setItem('date', mydate);
document.getElementById("registereddate").innerHTML = localStorage.getItem("date");
} else {
alertify.error("You've clicked Cancel");
}
});
}
//for inside html
document.getElementById("welcometext").innerHTML = localStorage.getItem("username");
document.getElementById("registeredemail").innerHTML = localStorage.getItem("email");
document.getElementById("registeredstatus").innerHTML = localStorage.getItem("status");
document.getElementById("registereddate").innerHTML = localStorage.getItem("date");
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/alertify.js/0.3.10/alertify.core.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/alertify.js/0.3.10/alertify.default.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/alertify.js/0.3.10/alertify.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#rc/dist/js.cookie.min.js"></script>
</head>
<body>
<h4>Welcome to your Bootcamp Tracker: <span id="welcometext"></span></h4>
<h4>Your Registered Email with us is : <span id="registeredemail"></span></h4>
<h4>Your Bootcamp Starting Date : <span id="registereddate"></span></h4>
<h4>Your current status for work is : <span id="registeredstatus"></span></h4>
</body>
</html>
I tried many times to submit my app to Samsung but I always get rejected because the back button or exit button of the watch doesn't work.
My app is a multiple page in one single HTML, as explained in the Tizen Documentation.
I don't know if it's a problem with the code within the app.js file where a problem with the multiple page in one single HTML file.
App.js file:
( function () {
window.addEventListener( 'tizenhwkey', function( ev ) {
if( ev.keyName === "back" ) {
var page = document.getElementsByClassName( 'ui-page-active' )[0],
pageid = page ? page.id : "";
if( pageid === "main" ) {
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {
}
} else {
tau.changePage("#main");
}
}
} );
} () );
index.html file:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no">
<title>BRStocks</title>
<link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" href="lib/tau/wearable/theme/default/tau.circle.min.css">
<!-- load theme file for your application -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="ui-page ui-page-active" id="main">
<header>
<h2 class="ui-title">BR Stocks</h2>
</header>
<div class="ui-content content-padding">
<ul class="ui-listview">
<li>BVSP</li>
<li>IBOV</li>
<li>ABEV3</li>
<li>AZUL4</li>
<li>BTOW3</li>
</ul>
</div>
</div>
<div class="ui-page" id="two">
<span id='ABEV3'>START</span>
<header>
<h2 class="ui-title" id="title">Loading...</h2>
</header>
<div class="ui-content">
<div id="container">
<pre><span id="ticker"></span></pre>
<pre><span id="price"></span></pre>
<pre><span id="pctChange"></span></pre>
<a class="back" href="main" onClick="Clear();">Voltar</a>
</div>
</div>
</div>
<script>
function Clear()
{
document.getElementById('title').innerHTML="Loading...";
document.getElementById('ticker').innerHTML = '';
document.getElementById('price').innerHTML = '';
document.getElementById('pctChange').innerHTML = '';
}
function link(event) {
var element = event.target;
var ticker_id = element.getAttribute("ticker_id");
// do what you will with hike_id
console.log(ticker_id);
getPrice(ticker_id);
return;
}
function getPrice(y) {
if (self.fetch) {
console.log("fetch ok!")
fetch('xxxxxxxxxxxxxxxx')
.then(response => response.json())
.then(data => {
console.log("Fetching...")
//document.getElementById('title').innerHTML = data[y]['name']
var CompanyName = data[y]['name'];
var CompanyTicker = data[y]['ticker'];
var lastPrice = Number(data[y]['lastPrice']);
var pctChange = Number(data[y]['pctChange']);
pctChange = pctChange.toFixed(2);
document.getElementById('ticker').innerHTML = CompanyTicker;
document.getElementById('title').innerHTML = CompanyName;
document.getElementById('price').innerHTML = lastPrice.toLocaleString('pt-BR');
document.getElementById('pctChange').innerHTML = pctChange.replace('.',',') + '%';
if (pctChange < 0) {
console.log('Achou o sinal negativo');
document.getElementById('pctChange').className = 'redFont';
}else{
document.getElementById('pctChange').className = 'greenFont';
}
});
} else {
console.log("Something went wrong...")
}
}
function red(){
var elements = document.getElementById('pctChange').innerHTML;
console.log('Elemento: '+elements);
if (elements.includes('-')) {
console.log('Achou o sinal negativo');
document.getElementById('pctChange').className = 'redFont';
}else{
document.getElementById('pctChange').className = 'greenFont';
}
}
</script>
<script src="lib/tau/wearable/js/tau.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lowBatteryCheck.js"></script>
<script src="js/circle-helper.js"></script>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
</body>
</html>
The html file is pretty simple. The multiple page works with href pointing to id tags (in this case is #two and #main the pages).
For any reason, the button back in the emulator and real gadget is not working. Neither back to previous page, nor exit the application.
instead of
<a class="back" href="main" onClick="Clear();">Voltar</a>
try
<a class="back" href="main" ontouchend="Clear();">Voltar</a>
(I took a random eg in your code you can apply that change to every 'onClick' attribute)
I have just figure out that for the buttons to work (and also the function tizenhwkey) you have to setup the config.xml file of your project.
I have just added the line below:
<tizen:setting background-support="disable" encryption="disable" hwkey-event="enable"/>
And now the function and buttons work fine!
I'm trying to create a palindrome checker. And now it seems that my lengthChecker() is no longer being called, nor is the condition whenever a word isn't a palindrome, then say it's not a palindrome. What could be the issue?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lesson #6 Homework</title>
<script type="text/javascript" src="./js/palindrome.js"></script>
</head>
<body>
<h1>Is it a Palindrome?</h1>
<div id="mainCont">
<p>Hello. Please enter a word, and I'll see if it is a palindrome.</p>
<p>Word:
<input type="text" id="str" name="string" />
<button id="checkInput">Submit</button>
</p>
</div>
</body>
</html>
Here is the JS as of now:
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10 ) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert ("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome();
}
function palindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for (var j = i; j >= 0; j--) {
revStr = revStr + str.charAt(j);
}
if (str == revStr) {
isPalindrome();
} else {
alert(str + " -is not a Palindrome");
}
}
function isPalindrome() {
alert(str + " is a Palindrome.");
}
document.addEventListener("DOMContentLoaded" , function(e){
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
You have your Javascript linked in the head element, so it is executed before the <button id="checkInput"> gets into the DOM. Move it to the end of body or make it deferred.
Because you are tying to access your button, before your page is properly loaded.
You need to get your button and bind your event handler, when DOM is loaded.
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
I am working to get response from SOLR using jquery. When I use the below code I got the error saying Typeerror:data is null
When looked at the code in firebug, data in on_data function is null. I think I am missing something in the Solr URL.The URL I am using is http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q=%3A&version=2.2&start=0&rows=10&indent=on&wt=json.
Can you please take a look at my code, and also suggest me the URL style in the code
<html>
<head>
<title>Solr Search</title>
</head>
<body>
<h3>Solr Search</h3>
Query: <input id="query" />
<button id="search">Search</button>
<hr/>
<div id="results">
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function on_data(data) {
$('#results').empty();
var docs = data.response.docs;
$.each(docs, function(i, item) {
$('#results').prepend($('<div>' + item.name + '</div>'));
});
var total = 'Found ' + docs.length + ' results';
$('#results').prepend('<div>' + total + '</div>');
}
function on_search() {
var query = $('#query').val();
if (query.length == 0) {
return;
}
var url='http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q='+query+'&version=2.2&start=0&rows=50&indent=on&wt=json';
$.getJSON(url, on_data);
}
function on_ready() {
$('#search').click(on_search);
/* Hook enter to search */
$('body').keypress(function(e) {
if (e.keyCode == '13') {
on_search();
}
});
}
$(document).ready(on_ready);
</script>
Here is the working version of your code, and list of changes:
1) added wrf: adds a wrapper-function around the JSON response, useful in AJAX with dynamic script tags for specifying a JavaScript callback function
2) added callback: need to use JSONP instead of an ordinary JSON request, due to JavaScript’s cross-domain security restrictions.
<html>
<head>
<title>Solr Search</title>
</head>
<body>
<h3>Solr Search</h3>
Query: <input id="query" />
<button id="search">Search</button>
<hr/>
<div id="results">
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function on_data(data) {
$('#results').empty();
var docs = data.response.docs;
$.each(docs, function(i, item) {
$('#results').prepend($('<div>' + item.name + '</div>'));
});
var total = 'Found ' + docs.length + ' results';
$('#results').prepend('<div>' + total + '</div>');
}
function on_search() {
var query = $('#query').val();
if (query.length == 0) {
return;
}
var url='http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q='+query+'&version=2.2&start=0&rows=50&indent=on&wt=json&callback=?&json.wrf=on_data';
$.getJSON(url);
}
function on_ready() {
$('#search').click(on_search);
/* Hook enter to search */
$('body').keypress(function(e) {
if (e.keyCode == '13') {
on_search();
}
});
}
$(document).ready(on_ready);
</script>
Since you are using $.getJSON, you might need to add &wt=json to your query.
So your query should be: http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q=search_query&version=2.2&start=0&rows=10&indent=on&wt=json
By default Solr gives XML response. You need to specify if you need JSON response by adding &wt=json
Mode detail: http://wiki.apache.org/solr/SolJSON
I have installed solr 5.2.1: item.name in the function on_data is not provided anymore. I used item.id and it worked.