jquery show alert on click - javascript

I have a simple log in at the top of my page, when the user enters their id thats on my json file their name appears in a welcome alert(the welcome alert is avaiable on ready and the name appears inside when the user logs in). I want the alert to be hidden but when the users enters their code (there is no username just a code) this alert appears with the name.
Here is the log in text and button:
<div class="alert alert-info"><input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
Here is the alert:
<div class="alert alert-success" id="loginalert"<strong>Welcome</strong></div>
and here is the js getting the corresponding name to appear:
$(document).ready(function() {
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
}
}
});
}); });
the json file includes the users id (which is the code for now) : 001
and their name
when the code is entered to the login text box their name appears on the page to indicate what user has logged in
I also wanted to know.. if there was no corresponding id to the four i have included in my json is there any way to get this alert to appear instead of the login alert, this would be like a you have entered an invalid code -
<div class="alert alert-danger"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
(also to be hidden on page load/ready)
Can anyone help out guys please?
Kind regards

Try this: I have modified your script.
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function () {
$('#contact').fadeIn('slow');
});
}
}
});
});
});
For Error Message try:
Modify your div to this,
<div class="alert alert-danger" id="ErrorMessageAlert"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
Thereafter modify your scripts again to this:
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#ErrorMessageAlert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").show();
}else
{
$("#ErrorMessageAlert").show();
}
);
}
}
});
});
});

You can make your both alert forms hidden by default by adding hidden class and then through query show()-http://api.jquery.com/show/ display needed one
<style>
.hidden{
display:none;
}
</style>
<div class="alert alert-info hidden"><input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
<div class="alert alert-danger hidden"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
<script>
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
// Defined to keep if match found in loop
var matchFound = false;
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
// Show Welcome alert
$(".alert-info").show();
matchFound = true;
break;
}
}
// which means no match found and matchFound is not equal to true
if( !matchFound ){
// Show Error alert
$(".alert-danger").show();
}
});
</script>

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";
}
});
});

Clear input and start chat scroll from bottom

I'm trying to clear the input on a message submit. And also on chat window load keep the scroll at the bottom.
I've tried many scripts, I've also tried different approaches, outsourcing. But I think due to my structure something just isn't right. I will admit I'm no expert when it comes to anything JavaScript related. I'm just dying to get this done out the way, its been bugging me for months now that I cannot get it to work.
Here is my code
var scrolled = false;
function updateScroll() {
if (!scrolled) {
var element = document.getElementById("ChatPopScroll");
element.scrollTop = element.scrollHeight;
}
}
$("#ChatPopScroll").on('scroll', function() {
scrolled = true;
});
$(function() {
$('form#SendForm').on('submit', function(e) {
$.post('elements/sendmessagefriend.php', $(this).serialize(), function(data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
$('#message').val('');
var form = document.getElementById("SendForm");
form.reset();
$('#SendForm').trigger("reset");
})
.error(function() {
$('#message').val('');
});
e.preventDefault();
$('#message').val('');
});
});
$(document).ready(function() {
$('div.message-window').each(function(index, messageWindow) {
messageWindow = $(messageWindow);
// Run fetchMessages() once, when the page is loaded.
fetchMessages(messageWindow);
// Set an interval timer for checking messages.
// Not ideal, but it works for now.
setInterval(fetchMessages, 500, messageWindow);
// in milliseconds!!!!!! (1000ms = 1s)
});
});
function fetchMessages(messageWindow) {
// For each message window, check for new chats
// Get the friend_id from the window
var friend_id = messageWindow.attr("friend_id");
// Get the last chat message_id from the last chat message in this window.
var last_message_id = messageWindow.find("ul > li:last").attr("message_id");
// Ask the server for the latest messages.
// Send over the friend_id and last_message_id, so it can send back new messages from this friend.
$.get("elements/chat-load.php", {
last_message_id: last_message_id,
friend_id: friend_id
}, function(messages) {
// This function is run when the AJAX request succeeds.
// Append the new messages to the end of the chat
messageWindow.find("ul").append(messages);
});
}
function openPopup(ID) {
$('.popup');
$("#" + ID).fadeIn(200);
}
function closePopup(ID) {
$('.popup');
$("#" + ID).fadeOut(200);
}
function MinPopup(ID) {
$('.popup');
$("#" + ID).addClass('ChatMinPop').removeClass('ChatActivePop');
}
function UpPopup(ID) {
$('.popup');
$("#" + ID).addClass('ChatActivePop').removeClass('ChatMinPop');
}
<div id="ChatPopScroll" class="ChatPopMsg">
<div id="messages" class="messages message-window" friend_id="<?=$FriendName->id ?>">
<ul id="ScrollAuto" class="message">
</ul>
</div>
</div>
<div class="ChatPopFoot">
<form autocomplete="off" id="SendForm" class="SendMsg" role="form" method="post">
<input autocomplete="off" id="message" class="ChatPopFootTxt" type="text" name="message">
<input style="" id="submit" class="submit MsgInputHidden" type="submit" name="submit" value="Submit" />
</form>
</div>

.click show alert from json

I have a button and text box that reads an id for a specific user on my json file. If the user enters 001 their name will appear on the alert, the alert is hidden on page load but when the user enters this information the alert shows - Welcome (users name and details from the json file)
This script works, however when I wait a few seconds it disappears, how so I get it to stay on the page when it appears?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function () {
$('#contact').fadeIn('slow');
});
}
}
});
}); });
also is there any way to add like a slide down or slide up animation when he alert box appears?
Alert box:
<div class="alert alert-success" id="loginalert"> <strong>Welcome!</strong></div>
The login box that requires the user to enter their ID:
div class="alert alert-info">
<input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
this now works if i take away the fade out
Is there any way to display the message
<div class="alert alert-danger">
<strong>Danger!</strong> Indicates a dangerous or potentially negativeaction.</div>
if a user enters an invalid id or enters nothing?
many thanks
Remove the fadeOut() part. That code is responsible for hiding it again.
$(function() {
//Hide alert when page loads
var alertBox=$("#loginalert");
alertBox.hide();
$("#loginbtn").on('click',function(e){
// console.log("clicked login");
e.preventDefault();
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
// console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
// show the alert if d.user[i].ID is idafter
var message= "<p> Welcome: ' + jd.user[i].name + '</p>'";
alertBox.html(message).fadeIn('slow',function(){
$('#contact').fadeIn('slow')
})
} else {
// show the alert if d.user[i].ID is not idafter
var message= "<p> Error </p>'";
alertBox.html(message).fadeIn('slow')
}
}
})
})
});

pull json data from a json file on a .click

I have a text box and a button. On the button . click function the name appears but I want id (that the user enters into the text box for the corresponding name to appear)
this is a snip from the json:
{"user":[{"ID" : "001","name": "Zara Ali"}]}
This is the button/text ( that i have inside an alert div because i think it looks cool in my page and works with the .click)
<div class="alert alert-info">
<input type="text" id="userName" value>
<button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button>
</div>
and this is the js i have used for the .click
$(document).ready(function() {
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
$('#details').html('<p> Name: ' + jd.name + '</p>');
});
});
});
the result is going inside:
<div id = "details">
</div>
Try this:
$(document).ready(function() {
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#details').html('<p> Name: ' + jd.user[i].name + '</p>');
}
}
});
});
});

Javascript document.getElementById set input

I got some input validator, that checks if user e-mail and username not registered on website. My code looke like that:
Javascript:
$(document).ready(function()
{
$('#email').blur(function(event) {
$.get(BaseUrl + 'auth/email/check/' + $(this).val(), function(data)
{
if (data == 1) {
$('input#email').removeClass('valid');
$('input#email').addClass('error');
document.getElementById('div-error').style.display = "block";
} else {
document.getElementById('div-error').style.display = "none";
}
});
});
$('#username').blur(function(event) {
$.get(BaseUrl + 'auth/username/check/' + $(this).val(), function(data)
{
if (data == 1) {
$('input#username').removeClass('valid');
$('input#username').addClass('error');
document.getElementById('div-error').style.display = "block";
} else {
document.getElementById('div-error').style.display = "none";
}
});
});
});
DIV code after username input:
<div id="div-error" style="display: none;">username has alerdy registered</div>
DIV code after e-mail input:
<div id="div-error" style="display: none;">email already registered</div>
But then username is not-registered and email already registered i'm getting error on all this 2 inputs... How can i set document.getElementById for special inputs?
Your error-divs got the same id. An ID in HTML must be unique.
Try giving these elements classes like
<div class="div-error" id="div-error-username" style="display: none;">...</div>
<div class="div-error" id="div-error-email" style="display: none;">...</div>

Categories