Hiding the div and li elements when checkbox is checked/unchecked - javascript

Can anyone guide me in the correct direction please? I'm stuck with checked and not checked checkboxes. What I am trying to add:
Text in the text field & checkbox checked - hides the div element
Text in the text field & checkbox unchecked by entry - hides the first li element
Empty text field by entry & checkbox checked hides the second li element
What I have now:
let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")
but.disabled = true
divv.style.display = "block"
cons.addEventListener("input", function() {
if (cons.checked && txt.value !== '') {
consError.style.display = "none"
but.disabled = false
} else {
consError.style.display = "block"
but.disabled = true
}
})
txt.addEventListener("input", function() {
if (txt.value !== '' && cons.checked === false) {
but.disabled
} else {
but.disabled = false
}
})
function fun() {
out.textContent = "Hey " + txt.value + "!"
}
but.addEventListener("click", fun)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A checkbox</title>
</head>
<body>
<label for="name">Name</label>
<input id="name" placeholder="Name">
<label>
<input id="consent" type="checkbox">
I agree
</label>
<input id="send" type="button" value="Submit">
<p id="greeting"></p>
<div id="errors" style="color: red; display: none;">
<p>Error:</p>
<ul>
<li id="name-error">Please enter a name</li>
<li id="consent-error">Please give consent</li>
</ul>
</div>
<script src="index.js"></script>
</body>
</html>
Before I had cons.addEventListener like this and it was hiding the second li element but didn't keep the button disabled
cons.addEventListener("input", function() {
if (cons.checked){
consError.style.display = "none"
} else {
consError.style.display = "block"
}
})

move the validator outside to single function like this
function validator() {
if (cons.checked && txt.value !== '') {
but.disabled = false
divv.style.display = "none"
} else {
but.disabled = true
divv.style.display = "block"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A checkbox</title>
</head>
<body>
<label for="name">Name</label>
<input id="name" placeholder="Name">
<label>
<input id="consent" type="checkbox"> I agree </label>
<input id="send" type="button" value="Submit">
<p id="greeting"></p>
<div id="errors" style="color: red; display: none;">
<p>Error:</p>
<ul>
<li id="name-error">Please enter a name</li>
<li id="consent-error">Please give consent</li>
</ul>
</div>
<script>
let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")
but.disabled = true
divv.style.display = "block"
function validator() {
if (cons.checked && txt.value !== '') {
but.disabled = false
divv.style.display = "none"
} else {
but.disabled = true
divv.style.display = "block"
}
}
cons.addEventListener("change", function () {
if (cons.checked) {
consError.style.display = "none"
} else {
consError.style.display = "block"
}
validator();
})
txt.addEventListener("input", function () {
if (txt.value !== '') {
nameError.style.display = "none"
} else {
nameError.style.display = "block"
}
validator()
})
function fun() {
out.textContent = "Hey " + txt.value + "!"
}
but.addEventListener("click", fun)
</script>
</body>
</html>

Related

How to store task in localstorage than onload make it appear in individual tasks

I am trying to make a To Do list but I have encountered a problem with storing it in local storage. I have tried storing the task in a var than it in localStorage but than when a new task is added it overwrites the variable and when I tried to store it in array and than when I tried to retrieve it from array all tasks appeared in a single task div. I want to store the tasks in local storage and have the task be edited, deleted, marked done also for localStorage too. I am providing the code.
<--JS-->
let tasksDiv = document.getElementById("tasks");
let oldTasksDiv = document.getElementById("old-tasks");
let input = document.getElementById('input');
var clear = document.getElementById('clear');
input.value = "What do you have planned?";
addBtn.addEventListener('click' , onclickBtn);
input.addEventListener('keypress' , function(){
if(event.keyCode === 13){
onclickBtn();
}
});
input.addEventListener('click' , function (){
if(input.value === "What do you have planned?"){
input.value ="";
}
})
clear.addEventListener('click' , function (){
input.value ="";
})
function onclickBtn(){
if(input.value.length !== 0){
var tasksName = document.createElement('div');
tasksName.classList.add("tasks-div")
var task = document.createElement('p');
task.innerText = input.value;
task.classList.add("task");
var del = document.createElement('button');
del.classList.add("del");
del.innerHTML = '<i class="fas fa-solid fa-trash"></i>';
var edit = document.createElement('button');
edit.classList.add("edit");
edit.innerHTML = '<i class="fas fa-solid fa-pen-to-square"></i>';
var save = document.createElement('button');
save.classList.add("save");
save.innerHTML = '<i class="fas fa-solid fa-floppy-disk"></i>';
var chkbox = document.createElement('input');
chkbox.classList.add("chkbox")
chkbox.type = "checkbox";
tasksName.appendChild(chkbox);
tasksName.appendChild(task);
tasksName.appendChild(del);
tasksName.appendChild(edit);
tasksName.appendChild(save);
tasksDiv.appendChild(tasksName);
chkbox.addEventListener('click' , function(){
if(chkbox.checked === true){
task.style.textDecoration = "line-through red";
edit.style.display = "none";
save.style.display = "none";
}
else{
task.style.textDecoration = "none";
edit.style.display = "block";
}
})
del.addEventListener('click' , function(){
tasksDiv.removeChild(tasksName);
})
edit.addEventListener('click' , function(){
task.contentEditable = true;
task.focus();
edit.style.display = "none";
save.style.display = "block";
})
save.addEventListener('click' , function(){
if(task.innerHTML === '<br>'){
alert('This task will be deleted');
tasksDiv.removeChild(tasksName);
}
task.contentEditable = false;
task.blur();
edit.style.display = "block";
save.style.display = "none";
})
}
else{
alert("Please enter a task");
}
}
<-- HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tasks Keeper</title>
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/resp.css">
<script src="https://kit.fontawesome.com/6bf6193572.js" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/9b41c17796.js" crossorigin="anonymous"></script>
</head>
<body>
<header>
<div class="brand-div">
<h1><span class="brand">Tasks Keeper</span></h1>
<span class="made-by">Made By Raghav Srvt</span>
</div>
<div class="input-div">
<div class="input-div-clear">
<input type="text" placeholder="What do you have planned?" id="input" value="What do you have planned?">
<i class="fa-solid fa-xmark" id="clear"></i>
</div>
<button type="submit" id="add-btn">Add</button>
</div>
</header>
<div id="tasks">
</div>
<script src = "./app.js"></script>
</body>
</html>
You can insert todos as object into an Array and store it on LocalStorage.
It is a Functionality that makes it Easy for you.
function LsHandling() {
return {
get: function (key) {
const item = localStorage.getItem(key);
if (item) {
return JSON.parse(item);
}
},
set: function (todo, key) {
const item = localStorage.getItem(key);
if (item) {
const itemToArray = [...JSON.parse(item)];
for (data in itemToArray) {
if (itemToArray[data].id === todo.id) {
return;
} else {
itemToArray.push(todo)
localStorage.setItem(key, JSON.stringify(itemToArray));
}
}
} else {
const defaultArray = [todo];
localStorage.setItem(key, JSON.stringify(defaultArray));
}
},
};
}
And you can use it Like This :
for getting the todosArray : LsHandling().get(yourKey)
for setting a todo in todosArray : LsHandling().set(todoObject, yourKey)
Note : for deleting or editing todos , you must define an id for each todo

storing array of objects ang then check previous and next item

I should be able to add input for user A and user B and when I click previous it will display the previous one and when I click next it will display the next inputs back and forth. Thanks for any help.
It will ask input for user A after that we click next and will ask for input for user b after that when I click back it should display input of the previous user and if I click next if will display the next user.
but when I keep navigating next and prev it no longer display the data. waht is the issue with this guys ?
//event.js
const showModal = document.querySelector("#showModal");
const modal = document.querySelector(".modal");
const nextBtn = document.querySelector("#next-btn");
const prevBtn = document.querySelector("#prev-btn");
let userText = document.querySelector(".user-text");
showModal.addEventListener("click", e => {
modal.setAttribute("style", "display:block");
});
nextBtn.addEventListener("click", e => {
userText.textContent = "User B";
prevBtn.setAttribute("style", "display:inline-block");
});
prevBtn.addEventListener("click", e => {
userText.textContent = "User A";
prevBtn.setAttribute("style", "display:none");
});
//class.js
const mainForm = document.querySelector("#mainForm");
const fnameValue = document.querySelector("#fname");
const lnameValue = document.querySelector("#lname");
const idValue = document.querySelector("#idValue");
class User {
constructor() {
this.userArrHolder = [];
}
addUser(id, fname, lname) {
const newAddedUser = {
id: id,
fname: fname,
lname: lname,
};
if (this.userArrHolder.length > 0) {
// displaying first user in ui
this.userArrHolder.forEach(item => {
idValue.value = item.id;
fnameValue.value = item.fname;
lnameValue.value = item.lname;
console.log("display A");
});
// adding the second user
this.userArrHolder.push(newAddedUser);
} else {
// add new user
this.userArrHolder.push(newAddedUser);
fnameValue.value = "";
lnameValue.value = "";
}
}
// looping thru array
displayUser(id) {
idValue.value = id;
this.userArrHolder.forEach((item, index) => {
idValue.value = item.id;
fnameValue.value = item.fname;
lnameValue.value = item.lname;
});
}
}
const newUser = new User();
mainForm.addEventListener("submit", e => {
e.preventDefault();
// validating if adding a user or display
if (!idValue.value) {
let id = Math.floor(Math.random() * 10000);
newUser.addUser(id, fnameValue.value, lnameValue.value);
console.log("add", newUser.userArrHolder);
} else {
newUser.displayUser(idValue.value);
console.log("display", newUser.userArrHolder);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="index.css" />
<title>Document</title>
</head>
<body>
<div class="show-modal">
<button id="showModal">Show Modal</button>
</div>
<div class="modal">
<div class="modal-wrapper">
<p class="user-text">User A</p>
<form action="" id="mainForm">
<label for="fname">First Name:</label><br />
<input type="text" name="fname" id="fname" /><br />
<label for="lname">Last Name:</label><br />
<input type="text" name="lname" id="lname" />
<div class="btn-container">
<button
type="submit"
id="prev-btn"
class="pr"
style="display: none"
>
Prev
</button>
<button type="submit" id="next-btn">Next</button>
</div>
<input type="text" name="idValue" id="idValue" />
</form>
</div>
</div>
</body>
</html>
Consider the following Example (using jQuery UI for Dialog)
$(function() {
var Users = [];
var pos = 0;
function showPrev() {
pos--;
showUser(Users[pos]);
if (pos == 0) {
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(0)").addClass("hidden");
}
if ($("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").hasClass("add-user")) {
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").html("Next").removeClass("add-user ui-priority-primary");
}
}
function showNext() {
if ($("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").hasClass("add-user")) {
addUser($("#fname").val(), $("#lname").val());
showUser(Users[Users.length - 1]);
pos = Users.length - 1;
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").html("Next").removeClass("add-user ui-priority-primary");
} else {
pos++;
if (pos == Users.length) {
showUser({
fname: "",
lname: "",
id: ""
});
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").html("Add").addClass("add-user ui-priority-primary");
} else {
showUser(Users[pos]);
}
}
if (pos != 0) {
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(0)").removeClass("hidden");
}
}
function newUser(fname, lname) {
return {
id: Math.floor(Math.random() * 10000),
fname: fname,
lname: lname
};
}
function addUser(fname, lname) {
Users.push(newUser(fname, lname));
}
function showUser(data, $target) {
$target = ($target != undefined ? $target : $("#show-users"));
$("#fname", $target).val(data.fname);
$("#lname", $target).val(data.lname);
$("#idValue", $target).val(data.id);
}
function makeTable(arr, $target) {
$target = ($target != undefined ? $target : $("body"));
var tbl = $("<table>", {
class: "ui-widget ui-corner-all"
}).css({
width: "100%",
borderCollapse: "collapse",
});
if ($target != false) {
tbl.appendTo($target);
}
if (arr.length == 0) {
return tbl;
}
var head = $("<thead>", {
class: "ui-widget-header"
}).appendTo(tbl);
var body = $("<tbody>", {
class: "ui-widget-content"
}).appendTo(tbl);
$("<tr>").appendTo(head);
$("<th>").html("ID").appendTo($("tr", head));
$("<th>").html("First Name").appendTo($("tr", head));
$("<th>").html("Last Name").appendTo($("tr", head));
$.each(arr, function(i, row) {
$("<tr>").appendTo(body);
$.each(row, function(k, v) {
$("<td>", {
class: "ui-widget-content"
}).html(v).appendTo($("tr:last", body));
});
});
$("tr", body).eq(pos).addClass("ui-priority-primary");
return tbl;
}
addUser("John", "Smith");
addUser("Jane", "Smith");
showUser(Users[pos]);
$("#show-users").dialog({
autoOpen: false,
modal: true,
buttons: [{
text: "Prev",
class: (pos != 0 ? "" : "hidden"),
click: showPrev
},
{
text: "Next",
click: showNext
},
{
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}
]
});
$("#showModal").click(function() {
$("#show-users").dialog("open");
});
$("#showAll").click(function() {
var dlg = $("<div>", {
title: "All Users"
}).html(makeTable(Users, false));
dlg.dialog({
modal: true,
autoOpen: true,
close: function() {
$(this).dialog("destroy");
dlg.remove();
}
});
});
});
#mainForm label,
#mainform input {
display: block;
margin-bottom: 3px;
}
.ui-dialog .ui-dialog-buttonset button.hidden {
display: none;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="show-modal">
<button id="showModal">Show Modal</button>
</div>
<div class="show-all">
<button id="showAll">Show All Users</button>
</div>
<div class="modal" title="Show Users" id="show-users">
<form action="" id="mainForm">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" />
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" />
<input type="hidden" name="idValue" id="idValue" />
</form>
</div>
If you choose to not use the jQuery UI Dialog window, the other functions and basic ideas still apply.
You will have an Array of Users and an Pointer or Index counter, this will be set to 0 or the specific Index of the array. These should be available so you can read or modify them as needed. You will then have various functions to update the UI and modify data depending on the Users interactions.
Prev - Reduce the Pointer and show the Previous User data from the Array
Cannot drop below 0 index
Hide Prev button when Pointer is 0
Next - Increment the Pointer and show the Next User data from the Array
Cannot exceed last Index
Clear form for new User entry if on beyond the last Index
Show Prev button when Pointer is not 0

Can't select a value in the selectbox

I'm just trying to use a simple select box but when I select a value it does not get selected. While in the example it does. I have imported the css and javascript but it just doesn't work.
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div class="mdl-textfield mdl-js-textfield getmdl-select">
<input type="text" value="" class="mdl-textfield__input" id="sample2" readonly>
<input type="hidden" value="" name="sample2">
<i class="mdl-icon-toggle__label material-icons">keyboard_arrow_down</i>
<label for="sample2" class="mdl-textfield__label">Country</label>
<ul for="sample2" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
<li class="mdl-menu__item" data-val="DEU">Germany</li>
<li class="mdl-menu__item" data-val="BLR">Belarus</li>
<li class="mdl-menu__item" data-val="RUS">Russia</li>
</ul>
</div>
Your example doesn't include getmdl-select sources.
Please attach sources from http://creativeit.github.io/getmdl-select.
<!-- getmdl -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="your_path_to/material-design-lite/material.min.css">
<script defer src="your_path_to/material-design-lite/material.min.js"></script>
<!--getmdl-select-->
<link rel="stylesheet" href="path_to/getmdl-select/getmdl-select.min.css">
<script defer src="path_to/getmdl-select/getmdl-select.min.js"></script>
UPDATE: detmdl-select sources was added
{
'use strict';
(function () {
function whenLoaded() {
getmdlSelect.init('.getmdl-select');
};
window.addEventListener ?
window.addEventListener("load", whenLoaded, false) :
window.attachEvent && window.attachEvent("onload", whenLoaded);
}());
var getmdlSelect = {
_addEventListeners: function (dropdown) {
var input = dropdown.querySelector('input');
var hiddenInput = dropdown.querySelector('input[type="hidden"]');
var list = dropdown.querySelectorAll('li');
var menu = dropdown.querySelector('.mdl-js-menu');
var arrow = dropdown.querySelector('.mdl-icon-toggle__label');
var label = '';
var previousValue = '';
var previousDataVal = '';
var opened = false;
var setSelectedItem = function (li) {
var value = li.textContent.trim();
input.value = value;
list.forEach(function (li) {
li.classList.remove('selected');
});
li.classList.add('selected');
dropdown.MaterialTextfield.change(value); // handles css class changes
setTimeout(function () {
dropdown.MaterialTextfield.updateClasses_(); //update css class
}, 250);
// update input with the "id" value
hiddenInput.value = li.dataset.val || '';
previousValue = input.value;
previousDataVal = hiddenInput.value;
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
menu['MaterialMenu'].hide();
input.dispatchEvent(evt);
} else {
input.fireEvent("onchange");
}
}
var hideAllMenus = function () {
opened = false;
input.value = previousValue;
hiddenInput.value = previousDataVal;
if (!dropdown.querySelector('.mdl-menu__container').classList.contains('is-visible')) {
dropdown.classList.remove('is-focused');
}
var menus = document.querySelectorAll('.getmdl-select .mdl-js-menu');
[].forEach.call(menus, function (menu) {
menu['MaterialMenu'].hide();
});
var event = new Event('closeSelect');
menu.dispatchEvent(event);
};
document.body.addEventListener('click', hideAllMenus, false);
//hide previous select after press TAB
dropdown.onkeydown = function (event) {
if (event.keyCode == 9) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
menu['MaterialMenu'].hide();
dropdown.classList.remove('is-focused');
}
};
//show select if it have focus
input.onfocus = function (e) {
menu['MaterialMenu'].show();
menu.focus();
opened = true;
};
input.onblur = function (e) {
e.stopPropagation();
};
//hide all old opened selects and opening just clicked select
input.onclick = function (e) {
e.stopPropagation();
if (!menu.classList.contains('is-visible')) {
menu['MaterialMenu'].show();
hideAllMenus();
dropdown.classList.add('is-focused');
opened = true;
} else {
menu['MaterialMenu'].hide();
opened = false;
}
};
input.onkeydown = function (event) {
if (event.keyCode == 27) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
menu['MaterialMenu'].hide();
dropdown.MaterialTextfield.onBlur_();
if (label !== '') {
dropdown.querySelector('.mdl-textfield__label').textContent = label;
label = '';
}
}
};
menu.addEventListener('closeSelect', function (e) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
dropdown.classList.remove('is-focused');
if (label !== '') {
dropdown.querySelector('.mdl-textfield__label').textContent = label;
label = '';
}
});
//set previous value and data-val if ESC was pressed
menu.onkeydown = function (event) {
if (event.keyCode == 27) {
input.value = previousValue;
hiddenInput.value = previousDataVal;
dropdown.classList.remove('is-focused');
if (label !== '') {
dropdown.querySelector('.mdl-textfield__label').textContent = label;
label = '';
}
}
};
if (arrow) {
arrow.onclick = function (e) {
e.stopPropagation();
if (opened) {
menu['MaterialMenu'].hide();
opened = false;
dropdown.classList.remove('is-focused');
dropdown.MaterialTextfield.onBlur_();
input.value = previousValue;
hiddenInput.value = previousDataVal;
} else {
hideAllMenus();
dropdown.MaterialTextfield.onFocus_();
input.focus();
menu['MaterialMenu'].show();
opened = true;
}
};
}
[].forEach.call(list, function (li) {
li.onfocus = function () {
dropdown.classList.add('is-focused');
var value = li.textContent.trim();
input.value = value;
if (!dropdown.classList.contains('mdl-textfield--floating-label') && label == '') {
label = dropdown.querySelector('.mdl-textfield__label').textContent.trim();
dropdown.querySelector('.mdl-textfield__label').textContent = '';
}
};
li.onclick = function () {
setSelectedItem(li);
};
if (li.dataset.selected) {
setSelectedItem(li);
}
});
},
init: function (selector) {
var dropdowns = document.querySelectorAll(selector);
[].forEach.call(dropdowns, function (dropdown) {
getmdlSelect._addEventListeners(dropdown);
componentHandler.upgradeElement(dropdown);
componentHandler.upgradeElement(dropdown.querySelector('ul'));
});
}
};
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css" rel="stylesheet"/>
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div class="mdl-textfield mdl-js-textfield getmdl-select">
<input type="text" value="" class="mdl-textfield__input" id="sample1" readonly>
<input type="hidden" value="" name="sample1">
<label for="sample1" class="mdl-textfield__label">Country</label>
<ul for="sample1" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
<li class="mdl-menu__item" data-val="DEU">Germany</li>
<li class="mdl-menu__item" data-val="BLR">Belarus</li>
<li class="mdl-menu__item" data-val="RUS">Russia</li>
</ul>
</div>
I have edited your code slightly, if I understood your problem correctly I think this is what you are looking for. Here's a working example.
//grab all the list items
let listItems = document.querySelectorAll( "li[class=mdl-menu__item]" );
//grab the input field
let textField = document.getElementById( "sample2" );
//add an eventListener on selection to change value the input field as well as display text
for ( let i = 0; i < listItems.length; i++ ) {
listItems[ i ].addEventListener( "click", function() {
textField.setAttribute("value", listItems[ i ].dataset.val );
textField.value = listItems[ i ].innerHTML;
});
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div class="mdl-textfield mdl-js-textfield getmdl-select">
<input type="text" value="" class="mdl-textfield__input" id="sample2" placeholder="Country" readonly>
<input type="hidden" value="" name="sample2">
<i class="mdl-icon-toggle__label material-icons">keyboard_arrow_down</i>
<ul for="sample2" class="mdl-menu mdl-menu--bottom-left mdl-js-menu">
<li class="mdl-menu__item" data-val="DEU">Germany</li>
<li class="mdl-menu__item" data-val="BLR">Belarus</li>
<li class="mdl-menu__item" data-val="RUS">Russia</li>
</ul>
</div>

Javascript function - style change not working

I created a 2 simple functions but function 2 doesn't work, I tried to change it to style.font-weight = "bold"; but then all crashes, what to do?
function validate() {
if (document.getElementById('remember').checked) {
document.getElementById("text").innerHTML = "HELLO WORLD!";
} else {
document.getElementById("text").innerHTML = "hello world!";
}
}
function validate2() {
if (document.getElementById('remember2').checked) {
document.getElementById("text").style = "bold";
} else {
document.getElementById("text").style = "normal";
}
}
<div id="text" style="font-weight: normal">hello world!</div>
<input id="remember" type="checkbox" onclick="validate()">Caps</input>
<br>
<input id="remember2" type="checkbox" onclick="validate2()">Bold</input>
Is that a chrome problem or something?
You aren't specifying the css property to be changed:
document.getElementById("text").style.fontWeight = "bold";
Javascript uses camelCase instead of a dash(camel-case), as CSS does, so style.font-weight is invalid.
var textEl = document.getElementById("text");
function validate() {
if (document.getElementById('remember').checked) {
textEl.innerHTML = "HELLO WORLD!";
} else {
textEl.innerHTML = "hello world!";
}
}
function validate2() {
if (document.getElementById('remember2').checked) {
textEl.style.fontWeight = "bold";
} else {
textEl.style.fontWeight = "normal";
}
}
<div id="text">hello world!</div>
<input id="remember" type="checkbox" onclick="validate()" /> Caps
<br/>
<input id="remember2" type="checkbox" onclick="validate2()" /> Bold
Also note that your <input> syntax is incorrect, inputs are self-closing tags and their text is set with the value attribute(in this case the input is a checkbox, and can't have a value):
<input id="remember2" type="checkbox" onclick="validate2()" />Bold
use this may help you
function validate2() {
if (document.getElementById('remember2').checked) {
document.getElementById("text").style.fontWeight = "bold";
}
else {
document.getElementById("text").style.fontWeight = "normal";
}
}
function validate2() {
if (document.getElementById('remember2').checked) {
document.getElementById("text").style.fontWeight = "bold";
}
else {
document.getElementById("text").style.fontWeight = "normal";
}
}
You were not setting the correct style property.
var text = document.getElementById("text");
function validate(checkbox) {
if (checkbox.checked) {
text.innerHTML = text.innerHTML.toUpperCase();
} else {
text.innerHTML = text.innerHTML.toLowerCase()
}
}
function validate2(checkbox) {
if (checkbox.checked) {
text.style.fontWeight = "bold";
} else {
text.style.fontWeight = "normal";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div id="text" style="font-weight: normal">hello world!</div>
<input id="remember" type="checkbox" onclick="validate(this)">Caps</input>
<br>
<input id="remember2" type="checkbox" onclick="validate2(this)">Bold</input>
<script>
</script>
</body>
</html>

JS verify login form - where I went wrong?

I have nut to crack, that cracks my head for some time now.
I'm programming beginner, that's for introducing. I try to achieve JS form validation, that checks input fields email and password and if it match some criteria, unset "disabled" attribute on login button.
I tried components of my JS code and it works just fine, but when I merge it into function validate(), it just dont works and I cannot find reason why.
Here is my HTML:
<!DOCTYPE html>
<head>
<meta charset='UTF-8' />
<title>$title</title>
<link href='css/style.css' rel='stylesheet' type='text/css' />
<script type='text/javascript' charset='utf-8' src='js/validateInput.js'></script>
</head>
<body>
<div id='header'><h1>$title<h1></div>
<form name='login' method='post' action=''>
<table border='0'>
<tr>
<th>E-mail:</th>
<td colspan='2'><input type='text' name='email' id='email' size='30' value='$posted_email'
onkeyup='validate()' onclick='validate()' onchange='validate()' />
</td>
</tr>
<tr>
<th>Heslo:</th>
<td><input type='password' name='pword' id='pword' size='21'
onkeyup='validate()' onclick='validate()' onchange='validate()'/></td>
<td><input type='submit' name='login' class='submit' id='loginBtn' value='OK' /></td>
</tr>
</table>
</form>
</body>
Now my JS:
function $(id) {
if (id.indexOf('#') == 0 || id.indexOf('.') == 0) {
var name = id.substr(1);
return id.indexOf('#') == 0 ? document.getElementById(name) : document.getElementsByClassName(name);
}
return (typeof document.getElementById('id') !== 'undefined') ? document.getElementById(id) : document.getElementsByClassName(id);
}
function validateEmail(string) {
var re = /[\w\s\.\$\*\+\/\?\^\{\|\}\(\)]{1,64}#[\w]{1,250}\.[\w]{2,3}/;
return re.test(string);
}
function validate() {
var login = $('#loginBtn');
var email = $('#email');
var pword = $('#pword');
if (!validateEmail(email.value)) {
email.style.color = 'orange';
} else if (pword.length > 0) {
login.disabled = false;
}
return false;
}
window.onload = function() {$('#loginBtn').disabled = true;};
Any thoughts?
The problem is located at this condition :
if (!validateEmail(email.value)) {
email.style.color = 'orange';
} else if (pword.length > 0) {
login.disabled = false;
}
Change your function validate() to below :
function validate() {
var login = $('#loginBtn');
var email = $('#email');
var pword = $('#pword');
var result = false;
if (!validateEmail(email.value)) {
email.style.color = 'orange';
} else {
email.style.color = 'black';
result = true;
}
if (result && pword.value.length > 0) {
login.disabled = false;
} else {
login.disabled = true;
}
}
Fiddle demo.
Hopefully this help.

Categories

Resources