.click show alert from json - javascript

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

Related

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>

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

jquery show alert on click

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>

Increase/decrease numeric value of a span and removeClass of a link if either id up/down clicked in jQuery

I am using jquery.upvote.js to display a voting system on my posts.
I am first checking if the user is not logged in, if he is not, and he votes on a post, I wanna display him an alert which I've already achieved.
But I would also like to remove the class upvote-on and downvote-on depending on which button the user has clicked, and I would like to reset the vote .count to it's original state. If the post has 2 points, and the user clicked upvote, the number would go up to 3 automatically, I would like to bring it back to 2 by decreasing its value. And if he clicked downvote the number would automatically go down by, here I'd like to increase it by 1 and bring it back to its original state.
I would also like to do this only once. Because from what I've seen, it would keep increasing/decreasing the number as long as the user keeps clicking the voting buttons (while logged out).
This is the HTML markup
<div class="upvote topic" data-post="{{ $post->id }}">
<a id="up" class="upvote vote {{ $post->votes && $post->votes->contains('user_id', Auth::id()) ? ($post->votes->where('user_id', Auth::id())->first()->value > 0 ? 'upvote-on' : null) : null}}" data-value="1" data-post-id="{{ $post->id }}"></a>
<span class="count">{{ $post->votes->sum('value') }}</span>
<a id="down" class="downvote vote {{ $post->votes && $post->votes->contains('user_id', Auth::id()) ? ($post->votes->where('user_id', Auth::id())->first()->value < 0 ? 'downvote-on' : null) : null}}" data-value="-1" data-post-id="{{ $post->id }}"></a>
</div>
I've managed to removeClass from both upvote and downvote links but I wasn't able to increase/decrease the value of the span and I didn't do any checking, I just initialized it on $('.vote').on('click') so it didn't matter if it's upvote or downvote, the class upvote-on and downvote-on both got removed whenever a vote was performed.
if(data.status == false) {
sweetAlert("Oops...", "You are not logged in!", "error");
$('a.upvote').removeClass('upvote-on');
$('a.downvote').removeClass('downvote-on');
}
Then I tried to take it further by checking if whether id #up or #down was clicked, but that didn't yield any results. Classes were not removed and the numeric value turned to NaN
$.get( "http://localhost/r2/public/data/islogged", function(data)
{
data.status == false ? console.log('not logged in') : console.log('logged in');
$('.vote').on('click', function (e) {
e.preventDefault();
var $button = $(this);
var postId = $button.data('post-id');
var value = $button.data('value');
if(data.status == false) {
sweetAlert("Oops...", "You are not logged in!", "error");
$("#up").click(function() {
$('a.upvote').removeClass('upvote-on');
$(".count").text(Number($(".count").text()) - 1);
});
$("#down").click(function() {
$('a.downvote').removeClass('downvote-on');
$(".count").text(Number($(".count").text()) + 1);
});
} else {
$.post('http://localhost/r2/public/votes', {postId:postId, value:value}, function(data) {
// success here
}).fail(function() {
sweetAlert("Oops...", "Something went wrong...", "error");
}, 'json');
}
});
How do I go about doing this? Is there a better way?
UPDATE
I changed the code a little bit, but it's still not working. Class doesn't even get removed. As if $('.upvote .vote').on('click') doesn't exist.
$('.upvote .vote').on('click', function (e) {
e.preventDefault();
$('a.upvote').removeClass('upvote-on');
$('span.count').val(parseInt($('span.count').val()) - 1);
});
$('.downvote .vote').on('click', function (e) {
e.preventDefault();
$('a.downvote').removeClass('downvote-on');
$(".count").text(Number($(".count").text()) + 1);
});
$("#up").click(function() {
$('a.upvote').removeClass('upvote-on');
$(".count").text(Number($(".count").text()) - 1);
});
$("#down").click(function() {
$('a.downvote').removeClass('downvote-on');
$(".count").text(Number($(".count").text()) + 1);
});
this code not reachable when user logged in because it inside if(data.status == false)
Try parseInt($(".count").text()) instead of Number()

Div contents disappears about milliseconds of appearing

HTML:
<form id='pool_play'>
<?php
$PLAYERS = 8;
for ($i=1; $i <= $PLAYERS; $i++) {
print $i . ' <input type="text" class="initial_players" autofocus> <br/>';
}
?>
<br>
<button type="submit" class="random"> Randomize bracket</button>
</form>
<p class="debug"></p>
js:
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
});
I'm basically trying to do is that when the form of #pool_play is submitted, print the contents of the input boxes in the .debug paragraph tag.
What happens is that it appears for a few milliseconds and then disappears. My guess is when the page is submitted, the old data(meaning the content of the .debug paragraph after it gets filled) gets thrown away. Tips?
You need to prevent the submit action or the page will just reload without your changes to the page.
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
event.preventDefault();
return false;
});
It may be a better idea however to change your button to a button instead of a submit
<button type="button" class="random"> Randomize bracket</button>
You can prevent the page from submitting using event.preventDefault()
$("#pool_play").submit(function(event) {
var participants = $('.initial_players').map(function() {
return $(this).val();
}).get();
for (var i = 0; i < participants.length; i++) {
$('p.debug').append(participants[i] + " ");
}
event.preventDefault();//stops submit
});
Look at code. You catching submit event, getting data printing them... And then you go out from your function, so default action for submit event are executed by browser, because you don't stop it. Thats why you see this content only in miliseconds - browser is refreshing page.
You should use event.preventDefault() function to prevent browser from submiting form after execution your function.

Categories