I'm working with the local storage for the first time and going through some JS tutorials online as I'm quite rusty. Making a dictionary where you can add words in 2 idioms then it displays. Everything is working fine with the exception of the second item in the object "dict", is not being shown although it's in the object. it shows in the console output. Might be the indexing in the loop. Cannot see it though. Any light shed will be appreciated.
function getDictionary(){
var dict = {},
dictStr = localStorage.getItem('dictionary');
if(dictStr !== null){
dict = JSON.parse(dictStr);
}
return dict;
}
function show(){
var html = "";
var resultOutput = document.getElementById("resultOutput");
var dict = getDictionary();
for(var i = 0; i < Object.keys(dict).length; i++){
key = Object.keys(dict)[i];
html += "<p class='normal-paragraph'>The english word <span style='color: green'> " + key +
" </span>in portuguese is <span style='color: green'> " + dict[key]+
"</span> <button class='removeBtn' id='"+ i +"' >x</button></p>";
resultOutput.innerHTML = html;
var buttons = document.getElementsByClassName('removeBtn');
for(var i = 0; i < buttons.length; i++){
buttons[i].addEventListener('click',remove);
}
}
console.log("");
console.log("All words: "+ JSON.stringify(dict));
}
HTML
...
<p id="sayHello"></p>
<fieldset id="translateField">
<legend> Translate english to Portuguese</legend>
<input type="text" id="newWordEng" name="newWordEng" value="" placeholder=" write the english word" >
<input type="text" id="newWordPt" name="newWordPt" value="" placeholder=" write the portuguese word">
<input type="button" id="addWordBtn" name="addWordBtn" value="Add New Word">
</form>
</fieldset>
<div id="resultOutput">
</div>
<script src="src/translate.js"></script>
</body>
I think it's because you're using the variable "i" twice. In the inner for loop, try using "j" instead:
for(var j = 0; j < buttons.length; j++){
buttons[j].addEventListener('click',remove);
}
Edit: In fact, you can probably remove the inner loop altogether, and just do:
function show(){
var html = "";
var resultOutput = document.getElementById("resultOutput");
var dict = getDictionary();
for(var i = 0; i < Object.keys(dict).length; i++){
key = Object.keys(dict)[i];
html += "<p class='normal-paragraph'>The english word <span style='color: green'> " + key +
" </span>in portuguese is <span style='color: green'> " + dict[key]+
"</span> <button class='removeBtn' id='"+ i +"' >x</button></p>";
resultOutput.innerHTML = html;
var buttons = document.getElementsByClassName('removeBtn');
buttons[i].addEventListener('click',remove);
}
}
Related
I'm having a problem I'm using a numeric keypad that I found in codepen this one
https://codepen.io/matthewfortier/pen/ENJjqR
my objective is to store the generated pin in a database but it's a little difficult to do that because I'm taking the generated pin to an input but it looks like this
<input hidden="" id="pin" value="" name="pin">9345</input>
how do i get this generated pin and save it in database
the code is the same as the link
In your html you have this:
<input type="hidden" id="pin" value="9345" name="pin" />
In your Javascript you have this:
let value = document.getElementById('pin').value;
console.log(value);
$(function() {
var container = $(".numpad");
var inputCount = 6;
// Generate the input boxes
// Generates the input container
container.append("<div class='inputBoxes' id='in'></div>");
var inputBoxes = $(".inputBoxes");
inputBoxes.append("<form class='led' class='form-group' action='cadastro.php' method='post'></form>");
var led = $(".led");
// Generates the boxes
for(var i = 1; i < inputCount + 1; i++){
led.append("<input type='password' maxlength=1 class='inp' id='" + i + "' />");
}
led.append("<input type='password' maxlength=12 name='numero' value='93445566' id='numero' />");
led.append("<input type='text' name='te' id='te' placeholder='' />");
led.append("<button id='btn1' type='submit' onclick=''>enviar</button>");
container.append("<div class='numbers' id='inb'><p id='textoo'><span class='bolded'>PIN</span> do serviço MULTICAIXA</p></div>")
var numbers = $(".numbers");
// Generate the numbers
for(var i = 1; i <= 9; i++){
numbers.append("<button class='number' type='button' name='" + i + "' onclick='addNumber(this)'><span class='pin_font'>" + i + "</span></button>");
}
addNumber = function take(field,vall) {
if (!$("#1").val())
{
$("#1").val(field.name).addClass("dot");
}
else if (!$("#2").val())
{
$("#2").val(field.name).addClass("dot");
}
else if (!$("#3").val())
{
$("#3").val(field.name).addClass("dot");
}
else if (!$("#4").val())
{
$("#4").val(field.name).addClass("dot");
}
else if (!$("#5").val())
{
$("#5").val(field.name).addClass("dot");
}
else if (!$("#6").val())
{
$("#6").val(field.name).addClass("dot");
vall = $("#1").val() + $("#2").val() + $("#3").val() + $("#4").val()+ $("#5").val()+ $("#6").val();
document.getElementById("pini").innerHTML = vall;
}
}
Basically, I'm making a TODO list, the functions are save and delete records, which are already implemented and mark as important and mark as done, which are the functions that I'm having trouble with.
This is the method that I use to retrieve the items saved in Local Storage as an array.
function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
This is the method that I use to save records in Local Storage
function add() {
var task = "00"+document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
As you can see, I add the records with two 00 at the beginning, the first number is 0 when that item of the TODO list is "undone", and 1 when it is marked as done, the second number is 0 when that item if the TODO list is "not important", and 1 when it is marked as important, for changing those numbers on the local storage, I do this:-
//if the second digit is 0 then the task is not important
function markAsImportant(){
var id = parseInt(this.getAttribute('id'));
var todos = get_todos();
var task = todos[id].replaceAt(1, "1");
console.log(task);
todos.splice(id, 0, task);
todos.splice(id+1, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
That method is already well implemented and working as it should.
Now, knowing what item of the TODO is important and which one is not, I simply want to add a class to the items which second character is a one, and that is what I try to do here:-
function show() {
var todos = get_todos();
var html = '<div class="list">';
for(var i=0; i<todos.length; i++) {
//HERE HERE HERE HERE HERE
if (todos[i].charAt(1) == '1') {
console.log("important");
$('.item').addClass('important');
}
else{
console.log("not important");
}
html += '<div class="item"> <input type="checkbox" class="check" id="' + i + '"> ' +' <div class="title">' + todos[i].substring(2) + '</div> <div class="tools"> <span class="tag" id="' + i + '"> <img class="important-img" src="resources/important.png"> </span> <span class="delete remove " id="' + i + '"> <img src="resources/thrash.png"> </span> </div></div>';
};
html += '</div>';
document.getElementById('todos').innerHTML = html;
var deleteButtons = document.getElementsByClassName('remove');
for (var i=0; i < deleteButtons.length; i++) {
deleteButtons[i].addEventListener('click', remove);
};
var doneButtons = document.getElementsByClassName('check');
for (var i=0; i < doneButtons.length; i++) {
doneButtons[i].addEventListener('click', markAsDone);
};
var importantButtons = document.getElementsByClassName('tag');
for (var i=0; i < importantButtons.length; i++) {
importantButtons[i].addEventListener('click', markAsImportant);
};
var listItems = document.getElementsByClassName('item');
for (var i=0; i < listItems.length; i++) {
console.log(listItems[i]);
$(listItems[i]).attr('id', i);
};
}
But it simply won't add anything at all to the .item tags, how can I make it actually add the class important to the items that I want ?
You are not adding the html to DOM so $(".item") won't work. This should work:
for (var i = 0; i < todos.length; i++) {
html += '<div class="item';
if (todos[i].charAt(1) == '1') {
console.log("important");
html += ' important'; // The space must be there, so change just the "important" bit, but don't remove the space
} else {
console.log("not important");
}
html += '"><input type="checkbox" class="check" id="' + i + '"> ' + ' <div class="title">' + todos[i].substring(2) + '</div> <div class="tools"> <span class="tag" id="' + i + '"> <img class="important-img" src="resources/important.png"> </span> <span class="delete remove " id="' + i + '"> <img src="resources/thrash.png"> </span> </div></div>';
}
Paste this instead your for loop and post the result in comments under this answer.
Below are two different checkbox and the javascript below seems to be trigger by termsChkbx checkbox instead of chosen. How do I change this portion
var chosen = item.parentElement.querySelector('[type="checkbox"]'); ?
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' id='selectChkbx' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}' /></span>
</div>\n";
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
JS:
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("selectChkbx").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total;
}
createCheckbox();
You can try something like this:
JSFiddle
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
<div id="content"></div>
<p id="total">0</p>
Edit 1
I believe reason why you are not getting value is because of element structure. You have a span tag which holds price and another span tag holds checkbox. For such structure, you will have to navigate to that span and fetch its value. Following is depicted below.
Fetching Span's value
var price = chk[i].parentNode.previousSibling.textContent;
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<span>" + num + "</span>";
html += "<span><input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>Check</span><br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
var price = chk[i].parentNode.previousSibling.textContent;
total += parseFloat(price);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
.chk{
}
<div id="content"></div>
<p id="total">0</p>
I want to make list of all the form elements (including the FORMs inside the nested FRAME or IFRAME) within a HTML document.
The list would look like:
Forms For Page: (1)www.example.com
frmTestNameB
frmTestNameB
Forms For Page: (1)(1)www.example.com/IFramePage.htm
frmFormOfIFrame
Forms For Page: (1)(1)(1)www.example.com/Nested/NestedIFramePage.htm
frmFormOfNestedIFrameA
frmFormOfNestedIFrameB
frmFormOfNestedIFrameC
Forms For Page: (1)(2)www.example.com/IFramePage.htm
frmFormOfIFrame.htm
etc.
CORRECT/MODIFIED JavaScript code to perform this action is needed, please.
I am exploring on this below code but it fails:
var sFormNames = '';
function getFormsNamesForAnyDoc(objDoc) {
var arrForms = objDoc.Forms;
sFormNames += '\n\n List of Forms for WebPage' + objDoc.location.href + '\n';
for (k = 0; k < objForm.length; k++) {
sFormNames += objForm[k].name + '</td>\n';
}
}
function getAllFormsName(objWindow) {
getFormsNamesForAnyDoc(objWindow.document);
if (objWindow.frames.length > 0) {
for (i = 0; i < objWindow.frames.length; i++) {
getAllFormsName(objWindow.frames[i]);
}
}
}
//Calling
getAllFormsName(window);
console.log(sFormNames);
The following code was made available by Chris Pietschmann in the article JavaScript: Loop through all elements in a form
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
for (var i = 0; i < elem.length; i++) {
str += "<b>Type:</b>" + elem[i].type + "  ";
str += "<b>Name:</b>" + elem[i].name + " ";
str += "<b>Value:</b><i>" + elem[i].value + "</i> ";
str += "<BR>";
}
document.getElementById('lblValues').innerHTML = str;
}
<form id="frmMain" name="frmMain">
<input type="hidden" name="ElemHidden" value="some hidden text" />
<input type="text" name="ElemText" value="some text" />
<br />
<textarea name="ElemTextArea">Some text area text</textarea>
<br />
<br />
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
This code for the and elements is provided by Jan Pfeifer in the post How to access to iframe element?
var iframes = document.getElementsByTagName('iframe'); //all iframes on page
for(var i=0; i<iframes.length; i++){
alert(iframes[i].parentNode.id); // LI.id
alert(iframes[i].contentWindow.myVar); //iframe's context
}
My script is in just HTML and Javascript and I can't find what's wrong. I have a html-page that contains 8 products all with the same html-style. But when I click on product 2 or 8 it always only list the first product on the list. And I can't figure out what I need to do to get it to work. (some text in scripts are in my home language Swedish)
HTML code
<div id="Tama">
<h2>TAMA</h2>
<img src="images/trummor/tama.jpg">
<br/>
<p>TAMA Superstar. </p>
<p>Pris: 25000 kr</p>
<hr style="border: 1px solid #000;">
<form name="order">
<input type="hidden" id="IDnumber" value="004">
<input type="hidden" id="pris" value="25000">
<input type="hidden" id="item" value="Tama Superstar">
Välj antal:
<input type="text" id="antal" value="1" name="antal" onChange="this.value=CKquantity(this.value)" style="width:30px;" maxlength="1"> |
<input type="button" value="Köp" onclick="addElement(this.form);">
</form>
<hr style="border: 1px solid #000;">
<p>
Tillbaka till produkter
</p>
</div>
Javascript Cart File
// -- CHECK IF ANTAL IS A NUMBER -- //
function CKquantity(checkString) {
var strNewQuantity = "";
for ( i = 0; i < checkString.length; i++ ) {
ch = checkString.substring(i, i+1);
if ( (ch >= "0" && ch <= "9") || (ch == '.') )
strNewQuantity += ch;
}
if ( strNewQuantity.length < 1 )
strNewQuantity = "1";
return(strNewQuantity);
}
// -- ADD TO CART -- //
// still problem - only enter the first item on the list either you click on the
second or last product
function addElement(thisForm)
{
var itemId = document.getElementById('IDnumber').value
var itemName = document.getElementById('item').innerHTML;
var antal = document.getElementById('antal').value;
var pris = document.getElementById('pris').value;
var parent = document.getElementById('cart');
var newElement = document.createElement('li');
newElement.setAttribute('class','item');
var sum = antal * pris;
newElement.innerHTML = "("+itemId+") "+ antal + " x " + itemName + " - " + pris + " kr, Totalt: " + sum + " kr";
parent.appendChild(newElement);
}
JavaScript is Case Sensitive scripting language, which means its keywords should be written in the right-case. You should write function instead of FUNCTION.
Try This:
function addElement()
{
var itemName = document.getElementById('item').innerHTML;
var antal = document.getElementById('antal').value; // 'value' not 'VALUE'
var parent = document.getElementById('cart');
var newElement = document.createElement('li');
newElement.setAttribute('class','item');
newElement.innerHTML = antal + " x " + itemName;
parent.appendChild(newElement);
}