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>
Related
i made a to-do list and i am very new at this , but after adding multiple task it is adding in incomplete task and have one edit and delete button when trying to edit any list it is converting in type= text but when entering outside of this edit task it is still open to edit it should not be happening
here is java script code
var taskInput=document.getElementById("new-task");
var addButton=document.getElementsByTagName("button")[0];
var incompleteTaskHolder=document.getElementById("incomplete-tasks");
var completedTasksHolder=document.getElementById("completed-tasks");
var createNewTaskElement=function(taskString){
var listItem=document.createElement("li");
var checkBox=document.createElement("input");
var label=document.createElement("label");
var editInput=document.createElement("input");
var editButton=document.createElement("button");
var deleteButton=document.createElement("button");
label.innerText=taskString;
checkBox.type="checkbox";
editInput.type="text";
editButton.innerText="Edit";
editButton.className="edit";
deleteButton.innerText="Delete";
deleteButton.className="delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
return listItem;
}
var addTask=function(){
console.log("Add Task...");
if(taskInput.value==='')
{
alert('Required');
}
else
{
var listItem=createNewTaskElement(taskInput.value);
incompleteTaskHolder.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
taskInput.value="";
}
}
var editTask=function(){
console.log("Edit Task...");
console.log("Change 'edit' to 'save'");
var listItem=this.parentNode;
var editInput=listItem.querySelector('input[type=text]');
var label=listItem.querySelector("label");
var containsClass=listItem.classList.contains("editMode");
if(containsClass){
if(listItem.value=='')
{
alert('empty edit');
}
else
{
label.innerText=editInput.value;
}
}else{
editInput.value=label.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask=function(){
console.log("Delete Task...");
var listItem=this.parentNode;
var ul=listItem.parentNode;
ul.removeChild(listItem);
}
var taskCompleted=function(){
console.log("Complete Task...");
var listItem=this.parentNode;
completedTasksHolder.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
}
var taskIncomplete=function(){
console.log("Incomplete Task...");
var listItem=this.parentNode;
incompleteTaskHolder.appendChild(listItem);
bindTaskEvents(listItem,taskCompleted);
}
var ajaxRequest=function(){
console.log("AJAX Request");
}
//addButton.onclick=addTask;
addButton.addEventListener("click",addTask);
addButton.addEventListener("click",ajaxRequest);
$addNewTask.addEventListener("keypress",addTask);
var bindTaskEvents=function(taskListItem,checkBoxEventHandler){
console.log("bind list item events");
var checkBox=taskListItem.querySelector("input[type=checkbox]");
var editButton=taskListItem.querySelector("button.edit");
var deleteButton=taskListItem.querySelector("button.delete");
editButton.onclick=editTask;
deleteButton.onclick=deleteTask;
checkBox.onchange=checkBoxEventHandler;
}
for (var i=0; i<incompleteTaskHolder.children.length;i++){
bindTaskEvents(incompleteTaskHolder.children[i],taskCompleted);
}
for (var i=0; i<completedTasksHolder.children.length;i++){
bindTaskEvents(completedTasksHolder.children[i],taskIncomplete);
}
and here is html code where i am adding javascript
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Todo App</title>
<link rel="stylesheet" href="{{asset('css/style.css')}}">
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<div class="container">
<p>
<label for="new-task">Add List</label><input id="new-task" type="text" placeholder="Enter to do list"><button class="btn btn-default">Add</button>
</p>
<h3>To-do List</h3>
<ul id="incomplete-tasks">
</ul>
<h3>Completed Task</h3>
<ul id="completed-tasks">
</ul>
</div>
<script type="text/javascript" src="app.js"></script>
<script src="{{asset('js/index.js')}}"></script>
</body>
</html>
and here is attaching a image in which two edit input are showing and i want to when trying to do click anything other then edit should be listed , please help me
answer for your question in title
you should add id or unique identifier to that button and.
$(document).ready(()=>{
$(document.body).click((e)=>{
var button = $('#your_button_id')
if(e.target.id !== 'your_button_id' && $.contains(button[0]), e.target))
{
doSomething()
}
})
})
I'm trying to implement a simple speech to text and then text to speech as a response to the initial speech to text input!
I'm using code from another open source site for both the speech synthesis and text 2 speech, so I don't fully understand the code.
Basically, what is happening is that when I am finished speaking the input, I press the pause-record-btn which is supposed to trigger myFunction(), yet I have to press the button twice!
(I am VERY new to js but do understand a bit of front end development (css, html) so any help will be very appreciated )
Code Pen
/*-----------------------------
Voice Recognition Script
------------------------------*/
try {
var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
var recognition = new SpeechRecognition();
}
catch(e) {
console.error(e);
$('.no-browser-support').show();
$('.app').hide();
}
var noteTextarea = $('#note-textarea');
var instructions = $('#recording-instructions');
var notesList = $('ul#notes');
var noteContent = '';
// Get all notes from previous sessions and display them.
var notes = getAllNotes();
renderNotes(notes);
/*-----------------------------
Voice Recognition
------------------------------*/
// If false, the recording will stop after a few seconds of silence.
// When true, the silence period is longer (about 15 seconds),
// allowing us to keep recording even when the user pauses.
recognition.continuous = true;
// This block is called every time the Speech APi captures a line.
recognition.onresult = function(event) {
// event is a SpeechRecognitionEvent object.
// It holds all the lines we have captured so far.
// We only need the current one.
var current = event.resultIndex;
// Get a transcript of what was said.
var transcript = event.results[current][0].transcript;
// Add the current transcript to the contents of our Note.
// There is a weird bug on mobile, where everything is repeated twice.
// There is no official solution so far so we have to handle an edge case.
var mobileRepeatBug = (current == 1 && transcript == event.results[0][0].transcript);
if(!mobileRepeatBug) {
noteContent += transcript;
noteTextarea.val(noteContent);
}
};
recognition.onstart = function() {
instructions.text('Voice recognition activated. Try speaking into the microphone.');
}
recognition.onspeechend = function() {
instructions.text('You were quiet for a while so voice recognition turned itself off.');
}
recognition.onerror = function(event) {
if(event.error == 'no-speech') {
instructions.text('No speech was detected. Try again.');
};
}
/*-----------------------------
App buttons and input
------------------------------*/
$('#start-record-btn').on('click', function(e) {
if (noteContent.length) {
noteContent += ' ';
}
recognition.start();
});
$('#pause-record-btn').on('click', function(e) {
recognition.stop();
instructions.text('Voice recognition paused.');
});
// Sync the text inside the text area with the noteContent variable.
noteTextarea.on('input', function() {
noteContent = $(this).val();
})
$('#save-note-btn').on('click', function(e) {
recognition.stop();
if(!noteContent.length) {
instructions.text('Could not save empty note. Please add a message to your note.');
}
else {
// Save note to localStorage.
// The key is the dateTime with seconds, the value is the content of the note.
saveNote(new Date().toLocaleString(), noteContent);
// Reset variables and update UI.
noteContent = '';
renderNotes(getAllNotes());
noteTextarea.val('');
instructions.text('Note saved successfully.');
}
})
notesList.on('click', function(e) {
e.preventDefault();
var target = $(e.target);
// Listen to the selected note.
if(target.hasClass('listen-note')) {
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
// Delete note.
if(target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});
/*-----------------------------
Speech Synthesis
------------------------------*/
function readOutLoud(message) {
var speech = new SpeechSynthesisUtterance();
// Set the text and voice attributes.
speech.text = message;
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
/*-----------------------------
Helper Functions
------------------------------*/
function renderNotes(notes) {
var html = '';
if(notes.length) {
notes.forEach(function(note) {
html+= `<li class="note">
<p class="header">
<span class="date">${note.date}</span>
Listen to Note
Delete
</p>
<p class="content">${note.content}</p>
</li>`;
});
}
else {
html = '<li><p class="content">You don\'t have any notes yet.</p></li>';
}
notesList.html(html);
}
function saveNote(dateTime, content) {
localStorage.setItem('note-' + dateTime, content);
}
function getAllNotes() {
var notes = [];
var key;
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
if(key.substring(0,5) == 'note-') {
notes.push({
date: key.replace('note-',''),
content: localStorage.getItem(localStorage.key(i))
});
}
}
return notes;
}
function deleteNote(dateTime) {
localStorage.removeItem('note-' + dateTime);
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Voice Controlled Notes App</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/shoelace-css/1.0.0-beta16/shoelace.css">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Voice Controlled Notes App</h1>
<p class="page-description">A tiny app that allows you to take notes by recording your voice</p>
<h3 class="no-browser-support">Sorry, Your Browser Doesn't Support the Web Speech API. Try Opening This Demo In Google Chrome.</h3>
<div class="app">
<h3>Add New Note</h3>
<div class="input-single">
<textarea id="note-textarea" placeholder="Input." rows="6"></textarea>
</div>
<button id="start-record-btn" title="Start Recording">Start Recognition</button>
<button id="pause-record-btn" onClick="myFunction()" title="Pause Recording">Stop listening</button>
<p id="recording-instructions">Press the <strong>Start Recognition</strong> button and allow access.</p>
</div>
</div>
<p id="demo"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
<script>
function myFunction() {
var str = document.getElementById("note-textarea").value;
if (str.includes("hello how are you")){
document.getElementById("demo").innerHTML = "hi anthony";
responsiveVoice.speak("I am good thanks, and you?");
}
}
</script>
</body>
</html>
if (i<=5)
{
myWindow = window.open("help.html", "myWindow");
}
here it will check the input if value is 5 it will open help.html, if value is 4,3,2,1 will open or reload each time with help.html., what i need is one time it should open that html file and if values goes to 4,3,2,1 or any combination it should not again reload or open another window, same help.html page. instead it should check whether help.html is open or not if open it should stop executing., if close it can open help.html., Guide me..
var windows = {};
$('a').click(function(e){
var url = $(this).attr('href');
var name = $(this).attr('id');
if(windows.hasOwnProperty(name) && !windows[name].closed )
{
windows[name].focus();
}
else
{
windows[name]=window.open (url,name,"status=1,width=300,height=300");
}
});
i found this example but how to combine with my requirement
Here is the snippet and working DEMO
var i = 3, //hard-coded i vlaue here
myWindow = {
closed: true //needed this property
};
$('#btn').click(function () {
if (i <= 5 && myWindow.closed) {
myWindow = window.open("http://jsfiddle.net/");
}
});
<!DOCTYPE html>
<html>
<head>
<script>
var myWindow;
function openWin() {
if (!myWindow){
myWindow = window.open("", "");
}
}
function closeWin() {
if (myWindow) {
myWindow.close();
}
}
function checkWin() {
msg = ""
if (!myWindow) {
msg = "was never opened";
} else {
if (myWindow.closed) {
msg = "is closed";
} else {
msg = "is open";
}
}
document.getElementById("msg").innerHTML =
"myWindow " + msg;
}
</script>
</head>
<body>
<button onclick="openWin()">Open myWindow</button>
<button onclick="closeWin()">Close myWindow</button>
<button onclick="checkWin()">Is myWindow open?</button>
<br><br>
<div id="msg"></div>
</body>
</html>
i utilized this example and solved the issue.,
I'm working on a tournament bracketing system, and I found a library called "JQuery bracket" which can help a lot. But there are some problems:
I was planning to retrieve team names (and possibly match scores) from a PostgreSQL database and put them on the brackets. However, the data must be in JSON, and the parser is in Javascript. I can't seem to figure out a workaround.
Original code:
<html>
<head>
<title>jQuery Bracket editor</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.json-2.2.min.js"></script>
<script type="text/javascript" src="jquery.bracket.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.bracket.min.css" />
<style type="text/css">
.empty {
background-color: #FCC;
}
.invalid {
background-color: #FC6;
}
</style>
<script type="text/javascript">
function newFields() {
return 'Bracket name [a-z0-9_] <input type="text" id="bracketId" class="empty" /><input type="submit" value="Create" disabled />'
}
function newBracket() {
$('#editor').empty().bracket({
save: function(data){
$('pre').text(jQuery.toJSON(data))
}
})
$('#fields').html(newFields())
}
function refreshSelect(pick) {
var select = $('#bracketSelect').empty()
$('<option value="">New bracket</option>').appendTo(select)
$.getJSON('rest.php?op=list', function(data) {
$.each(data, function(i, e) {
select.append('<option value="'+e+'">'+e+'</option>')
})
}).success(function() {
if (pick) {
select.find(':selected').removeAttr('seleceted')
select.find('option[value="'+pick+'"]').attr('selected','selected')
select.change()
}
})
}
function hash() {
var bracket = null
var parts = window.location.href.replace(/#!([a-z0-9_]+)$/gi, function(m, match) {
bracket = match
});
return bracket;
}
$(document).ready(newBracket)
$(document).ready(function() {
newBracket()
$('input#bracketId').live('keyup', function() {
var input = $(this)
var submit = $('input[value="Create"]')
if (input.val().length === 0) {
input.removeClass('invalid')
input.addClass('empty')
submit.attr('disabled', 'disabled')
}
else if (input.val().match(/[^0-9a-z_]+/)) {
input.addClass('invalid')
submit.attr('disabled', 'disabled')
}
else {
input.removeClass('empty invalid')
submit.removeAttr('disabled')
}
})
$('input[value="Create"]').live('click', function() {
$(this).attr('disabled', 'disabled')
var input = $('input#bracketId')
var bracketId = input.val()
if (bracketId.match(/[^0-9a-z_]+/))
return
var data = $('#editor').bracket('data')
var json = jQuery.toJSON(data)
$.getJSON('rest.php?op=set&id='+bracketId+'&data='+json)
.success(function() {
refreshSelect(bracketId)
})
})
refreshSelect(hash())
$('#bracketSelect').change(function() {
var value = $(this).val()
location.hash = '#!'+value
if (!value) {
newBracket()
return
}
$('#fields').empty()
$.getJSON('rest.php?op=get&id='+value, function(data) {
$('#editor').empty().bracket({
init: data,
save: function(data){
var json = jQuery.toJSON(data)
$('pre').text(jQuery.toJSON(data))
$.getJSON('rest.php?op=set&id='+value+'&data='+json)
}
})
}).error(function() { })
})
})
</script>
</head>
<body>
Pick bracket: <select id="bracketSelect"></select>
<div id="main">
<h1>jQuery Bracket editor</h1>
<div id="editor"></div>
<div style="clear: both;" id="fields"></div>
<pre></pre>
</div>
</body>
</html>
After the data is retrieved, upon display, you are going to want to add disabled to the html input element. For instance:
<input type="text" id="bracketId" class="empty" disabled>
This will render your text field uneditable.
If you are looking to do this as people are filling out their brackets, I would suggest you either add a <button> after each bracket or fire a jquery event with the mouseout() listener that adds the disabled attribute to your input fields.
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.