How to hide and visible the text content based on some value? - javascript

How to write HTML and Javascript code.
I have two text content like(Hi, Hlo how are you)& (I'm 5n what about you?).
When the values comes 3 need to show 1st content(Hi, hlo how are you).
If does not come value 3 need to show second content(l'm 5n what about you)..
Thanks.

Your question is too broad to understand, where does this value come from? Is these text in same element or two different element? what you need covering few show hide use here:
Input from API call, with two div for two output:
HTML:
<div id="when3" class="hide">Hi, hlo how are you</div>
<div id="not3" class="hide">l'm 5n what about you</div>
CSS:
/* Hide block */
.hide {
display: none
}
JS:
let value = 3; //use user input here
function show() {
if (value === 3) {
document.getElementById("when3").classList.remove("hide");
document.getElementById("not3").classList.add("hide");
} else {
document.getElementById("not3").classList.remove("hide");
document.getElementById("when3").classList.add("hide");
}
}
show();
When need to change value of same element based upon some input, no two different element:
HTML:
<div id="output"></div>
JS:
let value = 3; //use user input here
function show() {
if (value === 3) {
document.getElementById("output").innerHTML = "Hi, hlo how are you";
} else {
document.getElementById("output").innerHTML = "l'm 5n what about you";
}
}
show();
Show/Hide HTML <div> based upon some clicks. Used for navigation.
HTML:
<ul>
<li onclick="show('profile')">Profile</li>
<li onclick="show('friends')">Profile</li>
<li onclick="show('messages')">Profile</li>
</ul>
<div id="profile" class="hide">Profile Details</div>
<div id="friends" class="hide">Friends</div>
<div id="messages" class="hide">Messages</div>
CSS:
/* Hide block */
.hide {
display: none
}
JS:
function show(id) {
hideAll();
let element = document.getElementById(id);
element.classList.remove("hide");
}
function hideAll() {
document.getElementById("profile").classList.add("hide");
document.getElementById("friends").classList.add("hide");
document.getElementById("messages").classList.add("hide");
}

HTML:
<div id="sample"></div>
JS:
var test = document.getElementById("sample");
var value;
if(value === 3){
test.innerHTML = "Hi, hlo how are you";
}
else{
test.innerHTML = "l'm 5n what about you";
}

html
<input type="text" id="txt"/><br/>
<input type="button" name="go" onClick="result()" value="send"/><br/>
<div id="msg"> </div>
javascript
function result(){
var test = document.getElementById("msg");
var value=document.getElementById("txt");
if(value === 3)
{
test.innerHTML = "Hi, Hlo how are you";
}
else
{
test.innerHTML = "l'm 5n what about you";
}
}

Something like this should work
function showText(val, id) {
document.getElementById(id).innerHTML = val == 3 ? "Hi, Hlo how are you" : "l'm 5n what about you";
}
showText(3, 'text');
showText(4, 'text1');
<div id="text"></div>
<div id="text1"></div>

Related

How to show a response when filtering through a list of elements using javascript

Hello I am creating an FAQ page that has to be filtered using javascript as below
Credit : https://makitweb.com/jquery-search-text-in-the-element-with-contains-selector/
$(document).ready(function () {
$('#filter').keyup(function () {
// Search text
var text = $(this).val().toLowerCase();
var error = document.getElementById("error");
// Hide all content class element
$('.mobrog-ux-text').hide();
// Search
$('.mobrog-ux-text').each(function () {
if ($(this).text().toLowerCase().indexOf("" + text + "") != -1) {
$(this).closest('.mobrog-ux-text').show();
setTimeout(
function () {
var x = document.getElementById("myDIV");
x.style.display = "none";
}, 4000);
error.style.display = "none";
}
else if($(this).text().toLowerCase().indexOf("" + text + "") == 0) {
error.style.display = "block";
}
});
});
});
<form align="center">
<input id="filter" onkeydown="keydownFunction()" oninput="keyPress(this.value)" class="searchfield" type="text"
name="search" placeholder="Search the help center">
</form>
<div style="color: white;padding : 10px" align="center"></div>
</div>
<div class="content2">
<h2>Frequently asked questions</h2>
<div id"pag"="id" pag""="pag" ""></div>
<div align="center" class="col-10">
<div class="mobrog-tab-container maxwidth">
<div id="myDIV" class="loader"></div>
<div class="error" id="error"> No result found!!</div>
<div id="results" class="mobrog-ux-vertical-tabs">
<div id="tar" class="mobrog-tabs">
<button data-tab="tab1" class="active">sample tab button?<span></span></button>
<button class="empty"></button>
</div>
<div class="mobrog-maincontent">
<div data-tab="tab1" class="mobrog-tabcontent active">
<div class="mobrog-ux-text">
<button class="mobrog-accordion">sample button</button>
<div class="mobrog-panel">
<p>
sample text
</p>
</div>
</div>
Which works, but then I am trying to show a message when the filtered word is not found within the list of DIVS I'm searching through on my FAQ page
I tried the below with
else if ($(this).text().toLowerCase().indexOf("" + text + "") == 0) {
//error message display
}
But then it does not work
(e.g when I type in a word which does not exist within my FAQ I want to display an error message which is in a div) and vice versa when the word is found in my FAQ page)
like the way its been used in the method of RegExp
Live search on an Div with input filter
at the moment when I type in available and unavailable words the error message appears
Please how do I effectively display a message when a filtered word is found or not found
Thanks
Expanding on my comment, this is an example of how you could implement something like this.
To reiterate - the main problem was that the error was being shown if any result didn't match instead of showing if none match
To fix that, we can add a variable outside the loop to determine if any result was matched
$(document)
.ready(function () {
$('#filter')
.keyup(function () {
// Search text
var text = $(this).val().toLowerCase();
var error = document.getElementById("error");
// storing this in a variable will reduce how many times you call the function
var $ux_texts = $('.mobrog-ux-text');
// Hide all content class element
$ux_texts.hide();
// variable to update if any match is found
var has_match = false;
// Search
$ux_texts
.each(function () {
var $this = $(this);
if ($this.text().toLowerCase().indexOf("" + text + "") === -1) {
// flip the logic so we can return early - makes for cleaner code
return;
}
$this.closest('.mobrog-ux-text').show();
setTimeout(function () {
var x = document.getElementById("myDIV");
x.style.display = "none";
}, 4000);
has_match = true;
});
// error handling
if (has_match) {
error.style.display = "none";
} else {
error.style.display = "block";
}
});
});

How to connect JS functions to checkbox

Hello,
I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.
Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now.
The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.
JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/
Any help and suggestions will be greatly appreciated!
P.S I am new to Javascript.
Checkbox event listeners:
checkbox_1.addEventListener('change', function () {
console.log("checkbox_1 changed");
if (this.checked) {
myConvertFunction();
} else {
//Do nothing
}
})
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
myScrambleFunction(text);
} else {
//Do nothing
}
})
Checkbox HTML:
<div class="checkbox">
<input type="checkbox" id="checkbox_1" >
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2" >
<label for="checkbox_2">Scramble</label>
</div>
this works properly..
You just had to add the event on the button and then test which check box was checked, and other little things
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div>
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="convertText">Convert</button>
<textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="copyText">Copy</button>
</div>
<script>
var text = document.getElementById("inputText").value;
var convertText = document.getElementById("convertText");
var checkbox_2 = document.getElementById("checkbox_2");
var checkbox_1 = document.getElementById("checkbox_1");
//Capitalize every odd letter
function myConvertFunction() {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];;
}
}
return string;
}
//Scramble words
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
document.getElementById("copyText").addEventListener("click", myCopyFunction);
//Copy textarea output
function myCopyFunction() {
var copyText = document.getElementById("convertedText");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
//Delete textarea output
function eraseText() {
document.getElementById("convertedText").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
//don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("doing both options");
document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
} else if (checkbox_2.checked) {
console.log("proceeding scrumble");
document.getElementById("convertedText").value = myScrambleFunction(text);
} else if (checkbox_1.checked) {
console.log("proceeding cap");
document.getElementById("convertedText").value = myConvertFunction();
}
})
</script>
</body>
</html>
You're never updating var text.
You need to update it before using it if you want the value to be something other than an empty string.
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
text = document.getElementById("inputText").value;
myScrambleFunction(text);
} else {
//Do nothing
}

Change text on click and keep changing

I have div with "Hey". That changes to "Are you ok?" when i click on it. But I want to contiue having more texts. How can I make it so that when I click the "Are you ok" another text appears, and so on...
HTML:
$(document).ready(function () {
$("#fold").click(function () {
$("#fold_p").text("Are you ok?");
} )
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><div id="fold">
<p id="fold_p">Hey</p>
</div>
Also, is it possible to make the last text a link? Any help is much appreciated.
Thank you
Here you go! Simply create an array like described in the comments!
var text = ["Hi","One","Two","Three","Four"]
$(document).ready(function () {
var index = 0;
$("#fold").click(function () {
index++;
$("#fold_p").text(text[index]);
} )
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><div id="fold">
<p id="fold_p">Hey</p>
</div>
I'd use an array and then shift the array in order to have different blurbs to spit out.
$(document).ready(function () {
textList = ["Are you okay?", "Well that's cool.", "I like puppies"];
$("#fold").click(function () {
$("#fold_p").text(textList.shift());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><div id="fold">
<p id="fold_p">Hey</p>
</div>
We can achieve both functionality in jQuery as well as in JavaScript.
Dynamic text change on click of previous displayed text.
last text as a link
Using JavaScript
var text = ["First","Second","Third","Fourth"]
var index = 0;
document.getElementById("fold").onclick = function() {
index++;
if(index < text.length) {
if(index == text.length-1) {
document.getElementById("fold_p").innerHTML = ''+text[index]+'';
} else {
document.getElementById("fold_p").innerHTML = text[index];
}
}
}
<div id="fold">
<p id="fold_p">Hey</p>
</div>
Using jQuery
var text = ["First","Second","Third","Fourth"]
var index = 0;
$("#fold").click(function () {
index++;
if(index < text.length) {
if(index == text.length-1) {
$("#fold_p").html(''+text[index]+'');
} else {
$("#fold_p").text(text[index]);
}
}
})
<div id="fold">
<p id="fold_p">Hey</p>
</div>

How should I implement if varA not selected display not selected?

I have a simple product page with a few sizes and an add to cart button. I want to use jquery to $("").toggle(); a message saying "choose a size" if a size isn't selected onClick of the Add to Cart button.
Here is my code:
ryan.js
function ryanClicked(id, b, c){
b = b || null;
c = c || null;
document.getElementById(id).style.borderColor = "black";
document.getElementById(b).style.borderColor = "#e0e0e0";
document.getElementById(c).style.borderColor = "#e0e0e0";
}
html.html
<div class="pp">
<div id ="sizeButton1"class="sizeButton" onclick="ryanClicked('sizeButton1','sizeButton2','sizeButton3')"> S </div>
<div id ="sizeButton2"class="sizeButton" onclick="ryanClicked('sizeButton2','sizeButton1','sizeButton3')"> M </div>
<div id ="sizeButton3"class="sizeButton" onclick="ryanClicked('sizeButton3','sizeButton1','sizeButton2')"> L </div>
</div> <br>
//I want to prevent the onClick from happening if size is not selected
<p class="ryanAddButton" onclick="simpleCart.add('quantity=1','name=Black Gold','price=58','image=images/thumbs/blackGold.jpg');return false;" >Add to Cart</p>
<p class ="hiddenTilClicked"> You must select a size! </p>
I want the onclick to be called when a size is selected and I want a jquery toggle to be called if a size is not selected.
How can I do this? I can just use js if statement but I don't know how to use JS to display html.
edit: can i pass in a function to be called in js? is that a callback? the simplecart.add() will have different parameters for each item
You need to set a style and width on your border.
Use a variable to track if a style was selected or not.
b = b || null isnt needed because you always pass in a parameter
var sizeSelected = false;
function ryanClicked(id, b, c) {
sizeSelected = true;
document.getElementById(id).style.border = "1px solid black";
document.getElementById(b).style.border = "1px solid #e0e0e0";
document.getElementById(c).style.border = "1px solid #e0e0e0";
}
function addClicked() {
if (sizeSelected) {
document.getElementById('hiddenTilClicked').style.display = 'none';
simpleCart.add('quantity=1', 'name=Black Gold', 'price=58', 'image=images/thumbs/blackGold.jpg');
} else {
document.getElementById('hiddenTilClicked').style.display = 'block';
}
}
.hiddenTilClicked {
display: none;
}
<div class="pp">
<div id="sizeButton1" class="sizeButton" onclick="ryanClicked('sizeButton1','sizeButton2','sizeButton3')">S</div>
<div id="sizeButton2" class="sizeButton" onclick="ryanClicked('sizeButton2','sizeButton1','sizeButton3')">M</div>
<div id="sizeButton3" class="sizeButton" onclick="ryanClicked('sizeButton3','sizeButton1','sizeButton2')">L</div>
</div>
<br>
<p class="ryanAddButton" onclick="addClicked();">Add to Cart</p>
<p id="hiddenTilClicked" class="hiddenTilClicked">You must select a size!</p>
You can simply add a flag that tells if a button has been clicked or not. And instead of directly calling the add function of the simpleCart you can make a new function for the click and wrap your product addition to the cart happen only when a button has been clicked.
You also need to set the hidden element hidden by style and toggle the style to visible only when the customer tries to add a product to the cart without selecting a size.
HTML:
<div class="pp">
<div id ="sizeButton1"class="sizeButton" onclick="ryanClicked(this.id)"> S </div>
<div id ="sizeButton2"class="sizeButton" onclick="ryanClicked(this.id)"> M </div>
<div id ="sizeButton3"class="sizeButton" onclick="ryanClicked(this.id)"> L </div>
</div> <br>
//I want to prevent the onClick from happening if size is not selected
<p class="ryanAddButton" onclick="simpleCart.add('quantity=1','name=Black Gold','price=58','image=images/thumbs/blackGold.jpg');return false;" >Add to Cart</p>
<p id="hiddenTilClicked" style={ visibility: none }> You must select a size! </p>
JS:
var sizeSelected = false;
function ryanClicked(id){
// set the flag that some size has been selected
sizeSelected = true;
// hide the warning since a size was selected
$('#hiddenTilClicked').css('visibility', 'hidden');
// add the border colors
$('.sizeButton').each(function(i, element) {
if(element.id == id) {
element.style.borderColor = "black";
} else {
element.style.borderColor = "#e0e0e0";
}
});
}
function addToCart() {
// add to cart only when a size was selected
if(sizeSelected) {
simpleCart.add('quantity=1','name=Black Gold','price=58','image=images/thumbs/blackGold.jpg')
} else {
$('#hiddenTilClicked').css('visibility', 'visible');
}
}
Here is a fiddle where you can test it: http://jsfiddle.net/sqkosy0b/
You can set a flag and put this simpleCart.add('quantity=1','name=Black Gold','price=58','image=images/thumbs/blackGold.jpg');return false;" inside JS:
HTML:
<p class="ryanAddButton" onclick="checkIfSel()" >Add to Cart</p>
JS:
var flag=0;
function ryanClicked(id, b, c){
b = b || null;
c = c || null;
document.getElementById(id).style.borderColor = "black";
document.getElementById(b).style.borderColor = "#e0e0e0";
document.getElementById(c).style.borderColor = "#e0e0e0";
flag=1;
}
function checkIfSel(){
if(flag==1){
simpleCart.add('quantity=1','name=Black Gold','price=58','image=images/thumbs/blackGold.jpg');
$('.hiddenTilClicked').hide();
}
else{
$('.hiddenTilClicked').show(); //OR document.getElementsByClassName('hiddenTilClicked')[0].style.display="block";
}
}
You'll have to set a variable in ryanclicked that will check if a button has been clicked:
add this line to ryan clicked:
sizeselect = false;
function ryanClicked(id, b, c) {
sizeselect = true;
}
You can associate a function with the onclick button like this:
<p class="ryanAddButton" onclick="checkforclick()" >Add to Cart</p>
And you can define your function like this:
function checkforclick()
{
if(sizeselect)
{
simpleCart.add('quantity=1', 'name=Black Gold', 'price=58', 'image=images/thumbs/blackGold.jpg');
}
else
{
document.getElementsByClassName('hiddenTilClicked')[0].style.display = 'block';
}
}

Javascript time out div

I have an alert that says you're right/wrong. I want to put a div that will appear for a few seconds instead of the alert. So when the right/wrong answer is chosen this div will appear instead of the alert. I know a timeout function would be needed but I cant seem to get it to work. I've tried a few times and nothing is working for me. Does anyone know how I would go about this?
This is the html (divs)
<div id = "your wrong">
wrong answer!
</div>
<div id = "right answer">
Right answer!
</div>
This is the javascript for the alert
function characterclicked(nr) {
if (nr == oddoneout[currentQuestionIndex].answer) {
alert("You're right!");
score+= 200;;
}
else{
alert("you are wrong it was " + oddoneout[currentQuestionIndex].characterName);
}
nextQuestion();
}
Just about the only thing you're not allowed to use in an id value in HTML is a space. :-) So we'll need to change those ids.
But then it's a simple matter of having them start off invisible (display: none), showing the relevant one (display: block), and then hiding it again after a delay via setTimeout.
document.getElementById("btnRight").onclick = function() {
show("right");
};
document.getElementById("btnWrong").onclick = function() {
show("wrong");
};
function show(id) {
var element = document.getElementById(id);
element.style.display = "block";
setTimeout(function() {
element.style.display = "none";
}, 1000); // 1000ms = 1 second
}
<div id="wrong" style="display: none">
wrong answer!
</div>
<div id="right" style="display: none">
Right answer!
</div>
<div>
<input type="button" id="btnRight" value="Show Right">
<input type="button" id="btnWrong" value="Show Wrong">
</div>
I will hope help you
var score = 0;
var oddoneout = Array();
oddoneout[0] = {answer: "2"};
var currentQuestionIndex = 0;
var btnReply = document.getElementById("reply");
btnReply.onclick = function(){
var answer = document.getElementById("answer").value;
characterclicked(answer);
};
function characterclicked(nr) {
var feedback = document.getElementById("right_answer");
if (nr == oddoneout[currentQuestionIndex].answer) {
score+= 200;
}else{
//alert("you are wrong it was " + oddoneout[currentQuestionIndex].characterName);
feedback = document.getElementById("your_wrong");
}
feedback.style.display = "block";
setTimeout(function(){
feedback.style.display = "none";
}, 2000);
//nextQuestion();
}
.feedback {
display: none;
color: red
}
<div class="question">
how many is 1 + 1 ?
</div>
<input type="text" id="answer" />
<input type="button" id="reply" value="reply" />
<div id = "your_wrong" class="feedback">
wrong answer!
</div>
<div id = "right_answer" class="feedback">
Right answer!
</div>
First thing you should do is to make the element that will contain the message invisible. You can do this by using display: none, either in the element's style attribute or in a CSS style sheet (preferred).
Next, we'll craft a function that shows the message. Since it can show either one of two messages, it will take an argument, so it knows whether to show "right" or "wrong".
function showMessage(right) { ... }
The right argument can be a boolean to keep it simple. From here, we can use only a single <div> and change it's text according to whether or not right is true.
Let's give it an id of message (you were using spaces in your IDs, which you cannot do).
function showMessage(right) {
var text = "You are ";
text += right? "right" : "wrong";
// Let's get the result <div>
var messageDiv = document.getElementById("message");
// and change it's text
messageDiv.innerText = text;
}
Now, all that's left is to show the message <div>, and after a few seconds make it disappear again. Let's use 5 seconds for this example. 5 seconds are 5000 milliseconds, which is what the timeout functions use as a unit.
function showMessage(right) {
var text = "You are ";
text += right? "right" : "wrong";
// Let's get the result <div>
var messageDiv = document.getElementById("message");
// and change it's text
messageDiv.innerText = text;
// and show it, and hide it after 5 seconds
messageDiv.style.display = "block";
setTimeout(function(){
messageDiv.style.display = "none";
}, 5000);
}
And that's it! If you call the function with true as an argument, it will show you "You are right". Otherwise, it will show you "You are wrong".
Here's a Jsfiddle for you to see it working.
Edit
If you also want to show the correct answer when the user is wrong, you can do so with a second argument:
function showMessage(right, answer) {
var text = "You are ";
text += right? "right!" : "wrong. The answer was " + answer;
...
}

Categories