Hide Div if Other Div contains Text? - javascript

var message = document.getElementById("es_msg_pg");
var videos = document.getElementById("x-section-2");
if (message.innerHTML.indexOf("Email Address already exists!") {
videos.style.display = "block";
} else {
videos.style.display = "none";
}
}
This seemed to be so straight forward but it's not working on my website.
Any suggestions?
Here is the HTML I am trying to check if it contains the text Email Address already exists!
<div class="es_msg" id="es_shortcode_msg">
<span id="es_msg_pg"></span>
</div>

indexOf returns a number. The number is the position of a string in another string, starting at 0. If the string doesn't exist, then it returns -1, which evaluates to true. You want to compare the the return value like this:
if (message.innerHTML.indexOf("Email Address already exists!") >= 0) { ... }

You can use this
var message = document.getElementById("es_msg_pg");
var videos = document.getElementById("es_shortcode_msg");
console.log(message.innerHTML);
// returns -1 if message doesnt contain your custom text
if (message.innerHTML.indexOf("Email Address already exists!") == -1)
{
videos.style.display = "block";
} else
{
videos.style.display = "none";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="es_msg" id="es_shortcode_msg">
<span id="es_msg_pg">Email Address already exists!</span>
</div>
<div>Hello</div>

Related

Special Characters Validation Not Working as expected

I'm trying to apply Regular Expression Validation to a textbox User Control and it's only working when I enter something at the end of the text in the textbox. And when I type something somewhere in the middle of the text, it's not working.
For Example: Hey Man! (When I type '!' at the end of the text, my Code's working fine)
Hey! Man! (But when I insert '!' somewhere in the middle of the text after the entire text is typed, not working)
Below is my Code:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+$');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
Any help would be greatly appreciated! Thanks!
This should work. Your ending $ is what is keeping it from matching anything within the string:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
> Most simple code ....Special Characters Validation
function checkForm(theForm) {
var result = /^[a-z0-9\\.;,:'\\s]{1,100}$/i(theForm.data.value);
if (!result) {
alert("No legal characters entered");
}
return !!result;
}

Show/Hide Div Dependant on URL Variable

If the word email appears in the URL div id='sociallocker' should show and div id ='emaillocker' should hide.
If the word email is not in the URL: div id='sociallocker' should hide and div id='emaillocker' should show.
So:
URL contains email:
Show div: #sociallocker
Hide div: #emaillocker
URL doesn't contain email:
Show div: #emaillocker
Hide div: #sociallocker
Live link: https://www.moneynest.co.uk/test-page-for-stack/
With the current code both div's are showing regardless?
HTML
<div id="sociallocker">
[sociallocker id="1505"]
</div>
<div id="emaillocker">
[emaillocker]
[/emaillocker]
</div>
JS
<script>
if(document.location.href.indexOf("email") >= 0) {
$("#sociallocker").css(‘display’, ‘none’);
}
</script>
As per my best understanding, I have tried to simulate your question with fake URL string give you an answer.
You have 2 possibilities of hash params either sociallocker or emaillocker and it will show in URL following way #sociallocker or #emaillocker.
As you have tried to do code in core javascript I have given you an answer in core javascript as well.
Here I suppose that you have below url scheme for example.
https://www.moneynest.co.uk/test-page-for-stack/
// When you do in programming uncomment following line.
//var _href = document.location.href;
// When you do in programming comment following line.
var _href= "https://www.moneynest.co.uk/test-page-for-stack/#sociallocker";
var params = _href.split("#")[1];
var divEmailLocker = document.getElementById("emaillocker");
var divSocialLocker = document.getElementById("sociallocker");
if (params.indexOf("sociallocker") > -1) {
divSocialLocker.style.display = "block";
divSocialLocker.style.visibility = "visible";
divEmailLocker.style.display = "none";
divEmailLocker.style.visibility = "hidden";
}else if (params.indexOf("emaillocker") > -1) {
divSocialLocker.style.display = "none";
divSocialLocker.style.visibility = "hidden";
divEmailLocker.style.display = "block";
divEmailLocker.style.visibility = "visible";
}
div#sociallocker, div#emaillocker{
display:none;
}
<div id="sociallocker">
[sociallocker id="1505"]
</div>
<div id="emaillocker">
[emaillocker] [/emaillocker]
</div>
Try this. Use show() and hide() of jQuery.
//str="https://stackoverflow.com/questions/49467845/show-hide-div-dependant-on-url-variable/email";
if(document.location.href.indexOf("email") >= 0) { //insted of 'str' use document.location.href
$("#sociallocker").show();
$("#emaillocker").hide();
}
else{
$("#sociallocker").hide();
$("#emaillocker").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sociallocker">
[sociallocker id="1505"]
</div>
<div id="emaillocker">
[emaillocker]
[/emaillocker]
</div>
try
document.location.href.includes("email")
to check if the word "email" is present in the url

If statement for when an array has no value (Javascript + HTML)

I have an input box storing various texts into an array and it is displaying on another page, but I want the page to say "No Events" when there is no value in the array
here is the javascript that appends the array to the page
function getEvents(){
//get the localstorage from the new event page
events = JSON.parse(localStorage.getItem("events"));
for (var i = 0; i < events.length; i++)
{
if (events === "undefined" || null || "") {
document.getElementById("none").innerHTML = "No events";
} else {
// title output
var title = document.createElement("h1"); //creates h1 element
var titleText = document.createTextNode(events[i].name); //assigns title
text
title.appendChild(titleText); //appends text to h1
document.getElementById("output").appendChild(title); //appends to the
page
// date output
var date = document.createElement("p"); //creates p element
var dateText = document.createTextNode(events[i].date); //assigns date
text
date.appendChild(dateText); //appends text to p
document.getElementById("output").appendChild(date); //appends to the page
}
}
}
And here is the html on the event loader page
<body onload="getEvents()">
<!-- Title -->
<center>
<h1>My Events</h1>
</center>
<p id="none"></p>
<div id="output">
</div>
</body>
You are looping through the array so you should test on the array elements not the array itself. Your for loop won't even run if there is no array. So the if that runs tests on the array itself under the scope of the loop has basically no sense.
You can proceed this way just before going beneath the loop:
if (events.length == 0)
document.getElementById("none").innerHTML = "No events";
Take your if statement out of the for loop
Use proper syntax for the OR clauses
properly test for undefined
Also test for length == 0
if (toString.call(events) == "undefined" || events.length == 0) {
document.getElementById("none").innerHTML = "No events";
} else {
for(){/*...*/}
}

Jquery Array. How to display array elements that match if statements at once?

This is my script:
<script>
$('.change_password_button').click(function() {
var error = [];
if (!$('.password').val()) {
error[0] = "Current password field is empty.";
}
if (!$('.new_password').val()) {
error[1] = "New password field is empty.";
}
if (!$('.confirm_password').val()) {
error[2] = "Confirm password field is empty.";
}
if ($('.new_password').val() != $('.confirm_password').val()) {
error[3] = "Your new password and confirm password fields do not match.";
}
for (var i = 0; i < error.length; i = i + 1) {
$('#errors').show();
$('#errors').html(error[i]);
}
});
</script>
I wanna to display all errors which occurs at once, but right now it just display one error message. Thanks in advance for your answers.
You have multiple problems.
Problem 1: First what happens to index zero if there is no error? It is undefined.
Solution: Use push, do not set an index.
Problem 2: Second, you are just setting the innerHTML in a loop so you keep overriding it.
Solution: Join the array
Problem 3: You val() checks will not work,
Solution: You need to check the length
$('.change_password_button').click(function(){
var error = [];
if (!$('.password').val().length) {
error.push("Current password field is empty.");
};
if (!$('.new_password').val().length) {
error.push("New password field is empty.");
};
if (!$('.confirm_password').val().length) {
error.push("Confirm password field is empty.");
};
if ($('.new_password').val() != $('.confirm_password').val()) {
error.push("Your new password and confirm password fields do not match.");
};
if(error.length) {
$('#errors').html( error.join("<br/>").show();
} else {
$('#errors').hide();
}
}
Try error.join('') instead of iterating and updating the element
$('.change_password_button').click(function () {
var error = [];
if (!$('.password').val()) {
error.push("Current password field is empty.");
};
if (!$('.new_password').val()) {
error.push("New password field is empty.");
};
if (!$('.confirm_password').val()) {
error.push("Confirm password field is empty.");
};
if ($('.new_password').val() != $('.confirm_password').val()) {
error.push("Your new password and confirm password fields do not match.");
};
$('#errors').show();
$('#errors').html(error.join(''));
});
If you want to use the looping then append the html instead of overriding it
var $errors = $('#errors').empty()
for (var i = 0; i < error.length; i = i + 1) {
$errors.append(error[i]);
}
$errors.show();
Rather than over-write your HTML each time, start appending:
var current = $('#errors').html();
$('#errors').html( current + " " + error[ i ] );
Appending a ul of errors may be more appropriate, but this will get you started.
To answer the question: you overwrite the HTML of the #errors element for every error, so it ends up displaying only the last error. You need to append every error message to the previous one.
You could do as tymeJV suggests, but that requires to fetch the HTML of that div every time the loop runs. jQuery already provides append functionality out of the box, so why not use that? The jQuery team put a lot of effort into it.
...
$('#errors').show(); // Notice I moved this statement. Once it is shown, you do not need to show it again.
for (var i = 0; i < error.length; i = i + 1) {
$('#errors').append(error[i]); // .append() instead of .html().
}
...
note that .html():
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content.
so you always replace the content of #errors from error[0] to error[length-1],only with one error message at any time.
i suggest use .append():
The .append() method inserts the specified content as the last child of each element in the jQuery collection

<textarea> what key was pressed with javascript

I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>

Categories

Resources