I'm working in a view that deals with creating account information and resetting passwords. Where I'm stuck: depending if the password request was sent, approved, or denied, this will in turn change how the log in screen/password request appears. I want it to change the present text in the form and update it with a message and the user can submit OK, etc. so the browser will close automatically (or have the current form be hidden so I can create a new one with the information, whichever is easier).
Before I had an alert to send the message, but now I need it as HTML to style it.
//All of this is in a Javascript script tag
var reset = getParameterByName('reset');
if (reset == "sent") {
//alert("Done! Please check your email to confirm.")
//How can I change the current text on the form?
document.getElementsByClassName('panel-login').innerHTML = "<div class='panel-login' style='color: white; background-color: blue;'><p>Done! Please check your email to confirm.</p></div>";
//Here so I know something is updating on the site...
var message = "<div style='color: white; background-color: blue;'><p>Done! Please check your email to confirm.</p></div>";
document.write(message);
}
if (reset == "fail") {
alert("Password reset request failed.")
}
if (reset == "approved") {
alert("Confirmed! A password reset email has been issued.")
#*var url = '#Url.Action("Login", "Account")';
window.location = url;*#
}
(Whatever works with the first if (sent) will be copied and pasted into the last two once I get this working.)
This is the HTML for the above:
<div class="panel_login" style="opacity: 0.9;">
<div class="">
#using (Html.BeginForm("ResetPassword2", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-signin mg-btm" }))
{
<div class="" style="padding-left: 20px; padding-right: 20px; padding-bottom: 20px; padding-top: 10px; ">
<div class="">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "Password reset was unsuccessful. Please check email and try again.")
<label>Email</label>
<div class="input-group">
<span id="emailinput" ng-model="user.EMAIL" class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", placeholder = "" })
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
</div><div class="panel-footer">
<div class="row centered">
<div class="col-xs-12">
<button id="singlebutton" name="singlebutton" class="btn btn-primary" onclick="Back(); return false;">Cancel</button>
<button class="btn btn-large btn-danger" type="submit" ng-click="resetpassword(user)">Request Password Reset</button>
</div>
</div>
</div>
}
</div>
I've tried hiding the panel-login so I can create a new div/element to display the message/form. It didn't work (doing something wrong):
document.getElementsbyClassName('panel-login').style.display = 'none';
Learned that since it was an array, I will need something else since the above produces a null and error. Tried using a variable to get the class and then a for statement to target it to style. Again, no avail.
I'm not familiar with Razor (still learning) and copying what I need in JavaScript seems to just replicate things instead of changing what's already there. Thanks in advance.
If I follow you, getElementsByClassName is the culprit. Try:
var loginPanel = document.getElementsbyClassName('panel-login')[0];
This will find the first match in the array.
I ended up figuring this out.
Essentially, I created other divs which is styled similarly to the log in screen and in the same position, but kept them hidden until they're called by their function to appear depending on user input and URL. Log in screen originally is visible but later hidden when another div is made visible to display the tailored message.
I first created this through Javascript (using functions to create HTML), but later changed it to HTML and CSS but still used JS to call the functions. The main reason I had to switch is because some messages after being confirmed either submitted something or was supposed to close the tab or go back and I had trouble doing so since apparently a script can't close the current page that didn't initially open it. Still having that problem in Chrome TBH.
Related
That's my first ever question, and it's about my very first project, it's an online RPG Forum/PlayByChat game. I know it's kinda of an ambitious project.
So, i'm stuck from months into a problem that i feel i'm close to solve, premise (I'm self-taught).
The idea is to activate an if statement by a keyword/password given by an NPC, if there isn't no keyword in the message that it's supposed to be sent, then nothing should to happen.
That's what i've been able to put together and modify a little bit (it's not the entire code, just the interested parts), it works but it gets activated by any words or even by just one letter/empty messagges, i recently added the attribute "required" to the textarea so the field needs to be fill before to send messagges (even though it works only for the first click, then gives the possibility to send empty messagges which of course triggers the JoinedInTheRoom function) but anyway, that's a minor problem, the main problem remains that i cannot figured out how to make work the if statement inside the event listener under the JoinedInTheRoom function with a pre-chosen keyword/password, let's say "Mellon" (not case-sensitive if possible).
i'll explain myself better.
Let's say i'm gonna write "Mellon fellas" in the TextArea inside the Chat Log, my idea is to simply trigger the JoinedInTheRoom function by the fact that "Mellon", the keyword, has been just sent inside the messagge, i hope that my intent it's clear.
Thanks in advance.
here is the code:
HTML - CHAT LOG + TEXT AREA AND BUTTON
<!-- CHAT LOG -->
<h3>Chat Log</h3>
<div class="ChatLog">
<div class="msg left-msg">
<div class="msg-img" style="background-image: url()"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">System</div>
</div>
<div class="msg-text">Write the Keyword to join the room and unlock the NPCs and Quests</div>
</div>
</div>
</div>
<!-- TEXT AREA AND BUTTON -->
<form class="FormInputArea">
<textarea class="InputCamp" id="TextArea" placeholder="Explain your move in max 200 characters..." required></textarea>
<button class="button" type="submit" id="SendButton"> Send </button>
</form>
JAVA SCRIPT - CHAT LOG + TEXT AREA AND BUTTON
// CHAT LOG + TEXT AREA AND BUTTON
const ChatLog = get(".ChatLog");
const FormInputArea = get(".FormInputArea");
const InputCamp = get(".InputCamp");
JAVA SCRIPT - JoinedInTheRoom + NpcsUnlocked
// JoinedInTheRoom + NpcsUnlocked
function JoinedInTheRoom(side) {
const NpcsUnlocked = `
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${BOT_IMG})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${BOT_NAME}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">You've joined the room, feel free to choose your quest.</div>
</div>
</div>
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${BOT_IMG})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${BOT_NAME}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">
<p onclick="Npc1('RANDOM TASK DESCRIPTION 1')"> Npc 1. </p>
<p onclick="Npc2('RANDOM TASK DESCRIPTION 2')"> Npc 2. </p>
</div>
</div>
</div>
`;
ChatLog.insertAdjacentHTML("beforeend", NpcsUnlocked);
ChatLog.scrollTop += 500;
}
FormInputArea.addEventListener("submit", event => {
event.preventDefault();
const NpcsUnlocked = InputCamp.value;
if (!NpcsUnlocked) return;
const Delay = NpcsUnlocked.split(" ").length * 600;
setTimeout(() => {
JoinedInTheRoom("left", NpcsUnlocked);
InputCamp.value = " ";
}, Delay);
})
JAVA SCRIPT - PLAYER MESSAGE SCRIPT
// PLAYER MESSAGE SCRIPT
function AppendMessage(name, img, side, text) {
const msgHTML = `
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${img})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${name}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">${text}</div>
</div>
</div>
`;
ChatLog.insertAdjacentHTML("beforeend", msgHTML);
ChatLog.scrollTop += 500;
}
FormInputArea.addEventListener("submit", event => {
event.preventDefault();
const msgText = InputCamp.value;
if (!msgText) return;
AppendMessage(PERSON_NAME, PERSON_IMG, "right", msgText);
InputCamp.value = "";
});
Searching on internet i found this 11 years old stackoverflow post that i think it might help me, it seems i might use "indexOf" for this job, i'm right ? Maybe you guys can help me make it a little bit more "modern" and apply it to my code ?
Link
You could use the .includes function, like below
if (msgText.includes("mellon")) {
JoinedInTheRoom();
}
It'll search the whole string and return true if "mellon" is found. However it will also return true if someone types a word containing mellon. "smellon" or "smellonies" would return true and run the JoinedInTheRoom function too
I want to fire an onclick event from a button. The event is declared in a separate JavaScript file.
The code must reproduce a chat. If I send first text it works fine, but if I try to send something again (second text) it does not fire.
The html file contains:
var chatOutputDiv = document.getElementById("chatOutput");
chatSubmit.onclick = function () {
// Create a Json object with "displayname" being the display name and "messageText" the message.
// "displayname" is taken from URL, message from element chatInput.
//var chatMessage = { "displayname": getURLParameter("displayName"), "messageText": chatInput.value };
// We send data on the "chat", channel which is currently hard-coded
// in later versions we allow custom naming of channels.
//conference.sendData("chat", chatMessage);
// Send text in current chat
chatOutputDiv.innerHTML += "<br> user : message";
// Clear chat input
chatInput.value = "";
};
<div class="row">
<div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center">
<div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;">
<input type="text" id="chatInput"/>
<input id="chatSubmit" type="button" value="Send"/>
</div>
</div>
</div>
If you try this code, it works one time, but after that it doesn't work anymore. It seems that it doesn't fire the event.
It's because you are recreating the html inside .chatOutput when you click the button, so the HTML (which includes the button) is rewritten and the event is lost.
There are various ways around this. One would be to make the function a named function that you call, and adding chatSubmit = document.getElementById("chatSubmit"); chatSubmit.onclick = myFunctionName; to the end of your function.
However, I think a nicer way of doing it is to just use an extra div to store the response, like so:
<div class="row">
<div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center">
<div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;">
<input type="text" id="chatInput"/>
<input id="chatSubmit" type="button" value="Send"/>
<div id="chatResponse"></div>
</div>
</div>
</div>
var chatOutputDiv = document.getElementById("chatOutput")
var chatSubmit = document.getElementById("chatSubmit")
var chatResponse = document.getElementById("chatResponse");
var chatInput = document.getElementById("chatInput");
function foobar() {
chatResponse.innerHTML += "<br> user : " + chatInput.value;
chatInput.value = "";
}
chatSubmit.onclick = foobar;
Fiddle: https://jsfiddle.net/r0gm30mr/
I am building a cross-platform app using Onsen UI, Monaca and AngularJS. I need to check if a user exists based on the UserID they enter. If the UserID is found, then the name is returned to me, else the user wont be able to proceed to the next screen.
I send the UserID via API call ($http) and get a JSON object as a response. When I enter a UserID I can retrieve the JSON object (tested and working) but I am stuck on authentication.
When the user clicks the LOG IN button, I show a modal (ons-modal) window with a message of the users name if the user is found, but I am stuck on showing the message LOGIN FAIL if no user is found.
Is there perhaps a better way to handle this rather than a modal window?
Below is my code. And below is an example of the JSON that is returned.
[{"employee_name":"John Doe"}]
There is also a Controller that handles the API calls and it can be assumed this is working OK as I am able to get user names - but just stuck on authentication.
login.html
<div style="text-align: center; color: #889DA8">
Enter your<br><strong>User ID</strong>
</div>
<form class="login-form" style="text-align: center" name="myForm">
<section style="padding: 8px">
<input type="password" class="text-input--underbar" required minlength="3" maxlength="4" ng-model-options="{ debounce : 800 }" placeholder="User ID" ng-model="userIDSearch" >
</section>
<section style="padding: 0 8px 8px">
<ons-button var="saveBtn" ng-disabled="myForm.$invalid" modifier="large" onclick="modal.show('modal')">Log In</ons-button>
</section>
</form>
<!-- Displays Modal Login Confirmation Screen -->
<ons-modal var="modal">
<div class="alert-dialog-mask"></div>
<div class="alert-dialog alert-dialog--android">
<div class="alert-dialog-title alert-dialog-title--android">
<div style="text-align: center">Please confirm your name</div>
</div>
<div class="alert-dialog-content alert-dialog-content--android">
<div style="text-align: center; padding-top: 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px;">
<p ng-repeat="userID in userIDs">
<!-- If returned value != 0 then we have a valid User -->
<!-- NOT WORKING HERE -->
<span ng-if="userID.employee_name !== 0 ">
<strong>
{{userID.employee_name}}
</strong>
</span>
<!-- NOT WORKING HERE -->
<span ng-else>
<strong>
User ID not found. Please try again.
</strong>
</span>
</p>
</div>
</div>
<div class="alert-dialog-footer alert-dialog-footer--one">
<button class="alert-dialog-button alert-dialog-button--one" ng-click="modal.hide()">Cancel</button>
<button class="alert-dialog-button alert-dialog-button--primal alert-dialog-button--one" ng-click="myNavigator.pushPage('vehicle-id.html', {animation: 'slide'});" )>Ok</button>
</div>
</div>
</ons-modal>
Would this be better handled in the app-controller perhaps?
appController.js
// App Controller Start
angular.module("myApp", ['onsen']).controller("appController", function($scope, $http)
{
// Watch for changes in the User ID text field
$scope.$watch('userIDSearch', function()
{
fetchUSerID();
});
// Initialising the search field
$scope.userIDSearch = "";
function fetchUSerID()
{
$http.get("mymadeupdomain/api/login.php?userid=" + $scope.search).success(function(data)
{
$scope.userIDs = data;
});
}
});
Based on what I got from your question:
You can try initializing a $scope variable as $scope.result = false;
In the success loop of $http.get() (i.e if you get the user data), you can set it to true.
On Your modal window, you can use a condition like
<span ng-if = 'result'><{{bind user name variable here}}</span>
<span ng-if ='!result'>No User Found/ Login Failed</span>
I have a modal with a grid of buttons representing different html components. When one of the buttons is pressed, some html is supposed to be injected into the page once the modal closes. However, I'm having trouble targeting the specific column where the html is to be injected. Here's my code:
<div class="row" id="newRow">
<div class="col-md-12 column">
<button class="btn addElement" href="#" data-toggle="modal" data-target="#add-element"><i class="fa fa-plus fa-3x add-item"></i></button>
</div>
</div>
And in my js file I have some code to assign an id to the column div (since there could potentially be many columns with this addElement button) that looks like this:
...
$(this).parent().next().children().find('.column').assignId();
...
Up to this point, everything works well. I'm having no trouble getting the column a unique id (defined in my assignId() function).
As I mentioned, the addElement button gets clicked, opening a modal which is when this code is executed:
$(document).on('click', 'button.addElement', function (e) {
e.preventDefault();
$('#add-element').modal('show').draggable();
var col = $('button.addElement').parent();
// debugging in the browser verifies that the colId
// successfully stores the id attribute for the column
var colId = col.attr('id');
addElements(colId);
});
...
function addElements(colId) {
$('#insert-paragraph').on('click', function () {
var html_content = '<div class="box" data-type="paragraph">...</div>';
$("#newRow").find("#"+colId).html(html_content)
$('#add-element').modal('hide');
});
}
It's on this line: $("#newRow").find(colId).html(html_content); that I'm having the issue. My guess is that the formatting for find(...) is wrong and that I can't just insert a variable like that, but I've tried a few different things and nothing seems to be working.
Any help is very much appreciated.
Thanks!
UPDATE:
#juvian suggested writing a few of the variables' values to the console:
console.log(colId);
console.log($("#newRow")).length;
console.log($("#newRow").find("#"+colId).length);
console.log($("#newRow").find("#"+colId).html());
I logged these values twice. First, just before passing colId into the addElements function and in the addElements function immediately after $(#newRow").find("#"+colId).html(html_content); The results of those two tests are as follows:
Values prior to running addElements:
console.log(colId); = 8153-1076-641d-3840
console.log($("#newRow")).length; = Object[div#newRow.row.clearfix]
console.log($("#newRow").find("#"+colId).length); = 1
console.log($("#newRow").find("#"+colId).html()); = <button class="btn addElement"...>...</button>
Values after the insert-paragraph button is pressed:
console.log(colId); = 8153-1076-641d-3840
console.log($("#newRow")).length; = Object[div#newRow.row.clearfix]
console.log($("#newRow").find("#"+colId).length); = 1
console.log($("#newRow").find("#"+colId).html()); = <div class="box box-element" data-type="paragraph">...</div>
Interestingly enough, it appears like everything is working like I'd expect it to, however, when it's all said and done, the addElement button remains and the page still renders this:
<div id="newRow" class="row clearfix">
<div id="32aa-ab91-f50d-c3b3" class="col-md-12 column ui-sortable">
<button class="btn addElement" data-target="#add-element" data-toggle="modal" href="#">
<i class="fa fa-plus fa-3x add-item"></i>
</button>
</div>
</div>
.find as most jquery functions, takes a css selector as parametre. Unfortunately, colId is just a string, so it matches no elements (unless colId is html, span or something like that)
You are just missing adding the id selector at the beginning to do an id match:
.find("#"+colId)
I guess The parent of button is a div here which has no id.
var col = $('button.addElement').parent();
thus var colId is getting no value.give that div an id and it should be fine.
I am having a problem with dynamically generating this dropdown menu. This works if I'm not making it dynamically.
The #t.Id is working and is different every time in the loop. I'm pretty sure its the first line that's wrong as I have used the id="" before this way.
<b>tagged</b>
<div style="display: none;">
<div id="tagsdiv#(t.Id)">
<span class="menu">hhhh<br />
nnnn
#for( int i = 0; i < t.tTags.Count; i++ ) {
<b>#Html.ActionLink( t.tTags[i], "TagDetail", "Forums", new { tag = t.tTags[i], page = 0 }, null )</b>
}
</span>
</div>
</div>
Tips to debug Razor (or any server-side code rendering markup) more effectively:
View the rendered HTML! is it correct?
Remove styles/scripts until you are sure the server is rendering the values you want.
Add a breakpoint to your controller to make sure you are passing data to the view. Your rendering logic may be fine.
That said, your code appears to work fine. I dummied up some data:
#{ var t = new { Id = 1234, tTags = new List<string> { "foo", "bar", "baz" } }; }
<b>tagged</b>
<div style="display: none;">
<div id="tagsdiv#(t.Id)">
<span class="menu">
#for( int i = 0; i < t.tTags.Count; i++ ) {
<b>#Html.ActionLink( t.tTags[i], "TagDetail", "Forums", new { tag = t.tTags[i], page = 0 }, null )</b>
}
</span>
</div>
</div>
This yields:
<b>tagged</b>
<div style="display:none;">
<div id="tagsdiv1234">
<span class="menu">
<b>foo</b>
<b>bar</b>
<b>baz</b>
</span>
</div>
</div>
One thing that really looks wrong here is '#tagsdiv1234'. Are you sure your tooltip needs an ID including the CSS/jQuery ID selector ("#")?
Another thing that stands out is your tooltip container is wrapped with an outer div set to display:none. The ID'd element will always be hidden because its parent is hidden, even if the tooltip code tries to show it.
Another possibility is that your ID contains a character illegal in an element identifier.