I have this code but it doesn't work:
HTML:
<button id="btn_search">Search</button>
<input id="srh" type="search">
JS:
var btnSearch = document.getElementById("btn_search");
var search = document.getElementById("srh");
if (document.addEventListener) {
btnSeach.addEventListener('click',activeSearch);
} else if (document.attackEvent) {
btnSearch.attackEvent('onclick',activeSearch);
}
function activeSearch (event) {
event.preventDefault();
if (search.style.width == '0') {
search.style.width = '14.8em';
search.style.opacity = '1';
} else if (search.style.width == '14.8em') {
search.style.width = '0';
search.style.opacity = '0';
}
I need a toggle button
What should I do?
I might think about using a CSS class and toggle() to show/hide you element.
var btnSearch = document.getElementById("btn_search");
btnSearch.addEventListener('click', function(event){
var search = document.getElementById("srh");
search.classList.toggle("hidden");
event.preventDefault();
});
#srh { width: 14.8em; }
#srh.hidden { display: none; }
<button id="btn_search">Search</button>
<input id="srh" type="search" />
You can simply use JQuery to simplify all the proccess. Make all the code as simple as:
function magictoggle(a) {
if (a == 1) {
$("#btn1").attr("onclick", "magictoggle(0)");
$("#searchbox").hide(1000);
//1000 Are the miliseconds will take the box to hide
} else {
$("#btn1").attr("onclick", "magictoggle(1)");
$("#searchbox").show(1000);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="magictoggle(1)">Search</button>
<input type="text" id="searchbox" placeholder="A search Box">
Related
I am making a to do list in JavaScript where I want to add an item to the list when I press the Add button or hit enter. I have the button click working, but I can't get the enter to work to do the same task.
Here is the HTML:
<input type="text" id="myInput" placeholder="Add new task">
<span onclick="addToList()" class="addBtn">Add!</span>
My addToList function:
function addToList() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("Please input a value");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("X");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
Currently I have it onclick for my button. I tried to use onkeypress for the input but it doesn't work. I also tried onkeydown and selecting the enter button:
<input onkeydown = "if (event.keyCode == 13)
document.getElementById('addBtn').click()" type="text" id="myInput" placeholder="Add new task">
But this also didn't work.
How can I edit my existing addToList function to also add an item on Enter? Or is it better to create a completely new function for that?
<input type="text" id="myInput" placeholder="Add new task">
<span onclick="addToList()" id="addBtn">Add! (be carefull you wrote addBtn class)</span>
document.getElementById('myInput').addEventListener('keydown', function(e){
if (e.keyCode == 13) {
document.getElementById('addBtn').click()"
}
})
Html form will take care of submitting it when click enter
<form onsubmit="addToList()">
<input type="text" id="myInput" placeholder="Add new task">
<button class="addBtn" type="submit">Add!</button>
</form>
Using event delegation makes your life so much easier ... Rewritten/-factored your code to this snippet:
document.addEventListener("click", documentWideHandler);
document.addEventListener("keyup", documentWideHandler);
document.addEventListener("focusin", documentWideHandler);
function documentWideHandler(evt) {
const origin = evt.target;
// action depends on the event and/or origin characteristics
if (evt.type === "focusin" &&
origin.id === "myInput") {
return document.querySelector("#warn").textContent = "";
}
if (evt.type === "keyup" &&
origin.id === "myInput" &&
evt.key === "Enter" || // note: event.keyCode is deprecated
origin.classList.contains("addBtn")) {
return addToList();
}
if (origin.classList.contains("close")) {
// removing seems more applicable
return origin.closest("li").remove();
}
}
function addToList() {
const inputElem = document.querySelector("#myInput");
// typically this is the first thing you do
// so you don't have to do anything else if
// the input is not provided
if (!inputElem.value.trim().length) {
// more user friendly 'alert'
return document.querySelector("#warn")
.textContent = "Please enter a task!";
}
// using insertAdjacentHTML
document.querySelector("#myUl").insertAdjacentHTML(`beforeend`,
`<li><span class="close"></span>${inputElem.value}</li>`);
// typically this would be the last thing to do
inputElem.value = "";
}
body {
margin: 2rem;
font: normal 12px/15px verdana, arial;
}
.addBtn,
.close {
cursor: pointer;
}
li {
list-style-type: none;
margin-left: -2rem;
}
.close:before {
content: "\274c";
margin-right: 0.3rem;
}
#warn {
color: red;
display: inline-block;
margin-left: 1rem;
}
<input type="text" id="myInput" placeholder="Add new task">
<span class="addBtn">Add!</span>
<span id="warn"></span>
<ul id="myUl"></ul>
I'm building a simple trivia app and so far its great, but I have a problem with proceeding to the next question.
oddly enough when the user Answer correctly to the question and presses the submit button it does increment to the next question but if they answer correctly again it does nothing.
Here is my code:
<div class="app">
<h2 id="question"></h2>
<button class="options" type="button" value="val"></button>
<button class="options" type="button" value="val"></button>
<button class="options" type="button" value="val"></button>
<button class="options" type="button" value="val"></button>
</br>
<button id="submit" type="button" name="button">Submit</button>
<button id="back" type="button" name="button">Back</button>
</div>
var data = {
currentQuestion: 0,
questions:[
{
answers:[1,3,5,6],
question:'how much is 3+3',
correctAnswer:6
},
{
answers:[1,3,5,2],
question:'how much is 1+1',
currectAnswer:2
},
{
answers:[1,8,5,6],
question:'how much is 4+4',
correctAnswer:8
},
{
answers:[1,8,10,6],
question:'how much is 4+6',
correctAnswer:8
}
]
}
var options = document.querySelectorAll('.options');
var question = document.querySelector('#question');
var backBtn = document.querySelector('#back');
var submitBtn = document.querySelector('#submit');
function init() {
newQuestion();
optionClick();
evaluate();
back();
}
function newQuestion() {
question.textContent = data.questions[data.currentQuestion].question;
for(var i = 0; i< data.questions.length; i++) {
options[i].textContent = data.questions[data.currentQuestion].answers[i]
}
}
function optionClick() {
options.forEach(function(elem) {
elem.addEventListener('click', function() {
this.classList.toggle('picked')
})
})
}
function evaluate() {
submitBtn.addEventListener('click', function() {
for(i = 0; i < options.length; i++) {
if(options[i].classList.contains('picked') && options[i].textContent == data.questions[data.currentQuestion].correctAnswer && data.currentQuestion <= 6){
options[i].classList.remove('picked')
data.currentQuestion++
newQuestion();
}
}
})
}
As has already been answered in the comments, the problem was a typo, currectAnswer rather than correctAnswer. It's kind of moot answering now, but I also wanted to suggest some other improvements.
The first thing I would do is instead of using a group of buttons, use a group of radio buttons. You can style them to look like a button if you want, plus you get free functionality by doing that. Radio buttons enforce only having one answer selected without any need to check for multiple answers in code.
Instead of using named functions that when called attach an anonymous function as an event handler, just create a named function and then attach them directly to the elements.
Pulling it together it would look something like this:
'use strict';
var data = {
currentQuestion: 0,
questions:[
{
answers:[1,3,5,6],
question:'how much is 3+3',
correctAnswer:6
},
{
answers:[1,3,5,2],
question:'how much is 1+1',
correctAnswer:2
},
{
answers:[1,8,5,6],
question:'how much is 4+4',
correctAnswer:8
},
{
answers:[1,8,10,6],
question:'how much is 4+6',
correctAnswer:10
}
]
}
var options = document.querySelectorAll('#options input');
var question = document.querySelector('#question');
var backBtn = document.querySelector('#back');
var submitBtn = document.querySelector('#submit');
function nextQuestion () {
if (data.currentQuestion < data.questions.length - 1) {
data.currentQuestion += 1;
displayQuestion();
} else {
data.currentQuestion = data.questions.length;
submitBtn.removeEventListener('click', evaluate);
backBtn.removeEventListener('click', prevQuestion);
question.textContent = "Done!"
}
}
function prevQuestion () {
if (data.currentQuestion > 0) {
data.currentQuestion -= 1;
displayQuestion();
}
}
function displayQuestion () {
question.textContent = data.questions[data.currentQuestion].question;
options.forEach(function (option, index) {
let answer = data.questions[data.currentQuestion].answers[index];
// set the value of the radio button
option.value = answer;
// set the text of the label next to it
option.nextElementSibling.textContent = answer;
// reset the selected value
option.checked = false
});
}
function evaluate () {
let correctAnswer = data.questions[data.currentQuestion].correctAnswer;
// get the value of the currently selected answer
let selectedAnswer = document.querySelector('#options :checked');
if(selectedAnswer && selectedAnswer.value == correctAnswer){
nextQuestion();
}
}
submitBtn.addEventListener('click', evaluate);
backBtn.addEventListener('click', prevQuestion);
displayQuestion();
fieldset {
border: none;
}
/* highlight the label immediately after the selected radio button */
#options input:checked + label {
border: 3px red solid;
}
/* hide the actual radio button
that the labels are controling. */
#options input {
display: none;
}
/* make the label look like a button */
#options label {
padding: .5em;
background: #eee;
border: outset 1px #eee;
}
<div class="app">
<h2 id="question"></h2>
<fieldset id="options">
<input id="answer1" type="radio" name="answers"> <label for="answer1"></label>
<input id="answer2" type="radio" name="answers"> <label for="answer2"></label>
<input id="answer3" type="radio" name="answers"> <label for="answer3"></label>
<input id="answer4" type="radio" name="answers"> <label for="answer4"></label>
</fieldset>
<button id="submit" type="button" name="button">Submit</button>
<button id="back" type="button" name="button">Back</button>
</div>
I would like to show my div when the email isn't validated. And hide it when it is.
This is what I tried, but it isn't working.
$("#fes-email").on("change.validation keyup.validation", function () {
var email = $(this).val();
$("#fes-submit").prop("disabled", email.length == 0 || !isValidEmailAddress(email));
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled')
$("#notification-container").show("slide");
});
}).trigger('change.validation');
You exit the function before you show it.
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled') <---exits function
$("#notification-container").show("slide"); <-- will never be called
});
AND you have a BIGGER problem. On every single change you are binding a submit handler to the form. That is BAD. Take the submit handler OUT of the change event.
(function() {
var isValid = false;
$("#fes-email").on("change.validation keyup.validation", function() {
var email = $(this).val();
isValid = email.length && isValidEmailAddress(email);
}).trigger('change.validation');
$('#fes-form').submit(function() {
if (isValid) {
$("#notification-container").slideUp();
} else {
$("#notification-container").slideDown();
}
return isValid;
});
}());
function isValidEmailAddress(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
#notification-container {
background-color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="fes-form">
<label for="fes-email">Email</label>
<input type="text" id="fes-email" name="fes-email" class="validation" />
<input type="submit" />
</form>
<div id="notification-container">Invalid Email</div>
I need to save a div with localstorage. When i press a button the div becomes visible but when i close the browser and open it again the div needs to be visible.
This is my code so far:
<script>
function openDiv() {
var film = document.getElementById("bookingDiv");
if(film.style.display == "none"){
film.style.display = "block";
}
}
function save() {
openDiv()
var saveDiv = document.getElementById("bookingDiv")
if(saveDiv.style.display == "block"){
localstorage.setItem("text", saveDiv)
}
}
function load() {
var loadDiv = localstorage.getItem("text")
if(loadDiv){
document.getElementById("bookingDiv") = loadDiv
}
}
</script>
<body onload="load()">
<input type="button" id="testButton" value="Save" onclick="save()" />
<div style="display:none" id="bookingDiv" type="text">
hello
</div>
</body>
You can only store strings using the localStorage. So you have to store the state of this element instead of the element itself.
function save() {
openDiv();
var saveDiv = document.getElementById("bookingDiv");
if (saveDiv.style.display == "block") {
localStorage.setItem("isTextVisible", true);
}
}
function load() {
var isTextVisible = localStorage.getItem("isTextVisible");
if (isTextVisible == "true") {
openDiv();
}
}
note: do not forget the semicolon after each statement as it might lead to wrong behavior!
I have a problem with changing type of input in javascript.
When I change from hidden to text is ok and is proper displayed but when I change to file input isn't showing.
<script type="text/javascript">
function show(x,y) {
if (document.getElementById(y).checked) {
document.getElementById(x).setAttribute('type', 'file');
} else {
document.getElementById(x).setAttribute('type', 'hidden');
}
}
</script>
/*JQUERY
function show(x,y){
$(y).change(function() {
$("#txtAge").text(this.checked);
if(this.checked) $(x).attr('type','text')
else $(x).attr('type','file');
});
}
show('#a','#isAgeSelected');*/
//JAVASCRIPT
function show(x,y,z){
var typedefault=document.getElementById(x).type;
document.getElementById(y).onchange=function(){
document.getElementById('txtAge').innerText=this.checked;
if(this.checked){
document.getElementById(x).type = z;
} else {
document.getElementById(x).setAttribute('type',typedefault);
}
};
}
show('a','isAgeSelecteda','text');
show('b','isAgeSelectedb','text');
show('c','isAgeSelectedc','file');
/*
function supportsFileInput() {
var dummy = document.createElement("input");
dummy.setAttribute("type", "file");
return dummy.disabled === false;
}
alert(supportsFileInput());
*/
<input id="isAgeSelecteda" type="checkbox">
<input id="isAgeSelectedb" type="checkbox">
<input id="isAgeSelectedc" type="checkbox">
<p id="txtAge"></p>
<input type="hidden" id="a">
<input type="file" id="b">
<input type="hidden" id="c">
Try this:
function show(x, y) {
if (document.getElementById(y).checked) {
document.getElementById(x).type = 'text';
} else {
document.getElementById(x).type = 'file';
}
}
Fiddle1
function show(x, y) {
if (document.getElementById(y).checked) {
document.getElementById(x).type = 'text';
} else {
document.getElementById(x).type = 'hidden';
}
}
Fiddle2
Fiddle3
Below code should work.
Javascript code
document.getElementById(selector).setAttribute("type","file");
jQuery Code
$(selector).attr('type', 'file');
Sample code
HTML
<input type="checkbox" id="chkTest" onclick="myFunction()">
<input type="hidden" id="hdnFld" />
Java script
function myFunction() {
if(document.getElementById("chkTest").checked) {
document.getElementById("hdnFld").setAttribute("type","text");
} else{
document.getElementById("hdnFld").setAttribute("type","file");
}
}