JavaScript Function Activation Issues - javascript

I have another question that's been bugging my mind since I started using js fairly recently so that my app would be nicely responsive but I've been hit with another block here.
As the title says I am having serious issues with a particular code.
Here is its summarized form
window.onload = onLoadFunctions;
function onLoadFunctions(){
var show3rdDiv = document.getElementById('show3rdDiv');
var editbtnStart = document.getElementById('editbtnDiv');
var editbtnLog = 0;
editbtnStart.style.display = 'none';
show3rdDiv.onclick = function(){
document.getElementById('3rdDiv')className = "";
if (editbtnLog == 1) {
editbtnStart.style.display = 'block';
}
else {
editbtnStart.style.display = 'none';
}
}
}
function submitclick(){
var uname = document.getElementById("login").elements[0].value;
var upass = document.getElementById("login").elements[1].value;
var preuname = "john";
var preupass = "doe";
if (preuname == uname && preupass == upass) {
editbtnLog = 1;
document.getElementById('2ndDiv')className = "";
alert("The user " + preuname + " was successfully loged in and editbtnLog wass set to: " + editbtnLog);
}
else {
alert("Wrong Username or password!");
}
}
.hidden {
display:none;
}
<div id="login">
<form id="login">
Username<input type"text" placeholder="name">
Passowrd<input type"password" placeholder="password">
<input type="submit" value="Submit" onclick="submitclick()">
</form>
</div>
<div id="2ndDiv" class="hidden">
<input type="button" id="show3rdDiv" value="Continue">
</div>
<div id="3rdDiv" class="hidden">
<div id="editbtnDiv">
<input type="button" id="editbtn" value="Edit"/>
</div>
</div>
No matter what I do that editbtn won't appear or disappear the way an object that requires something should do. And if you noticed i used it's div instead? that's coz it would never appear at all if i just used the input button itself.
Someone please tell me how this is wrong is so many ways?
I tried a lot of styles and I don't really want to use the onclick="" (refer to that Submit button that I hate so much) on my html coz people say it's bad to use it. What should I do here? It got annoying like yesterday already.
Am i missing something? Did I declare this wrong? The furry mermaids i'm loosing precious eyebrow hairs on this project already. <=[
Or maybe i should just stick to the onclick="" thing when it comes to showing that edit btn?

Please Check weather your Script is calling properly or not.Check the line where you define the script.

The "id" attribute is the only
window.onload = onLoadFunctions;
function onLoadFunctions(){
var show3rdDiv = document.getElementById('show3rdDiv');
var editbtnStart = document.getElementById('editbtnDiv');
var editbtnLog = 0;
editbtnStart.style.display = 'none';
show3rdDiv.onclick = function(){
document.getElementById('3rdDiv').className = "";//error
if (editbtnLog == 1) {
editbtnStart.style.display = 'block';
}else {
editbtnStart.style.display = 'none';
}
}
}
function submitclick(){
var uname = document.getElementById("login").elements[0].value;
var upass = document.getElementById("login").elements[1].value;
var preuname = "john";
var preupass = "doe";
if (preuname == uname && preupass == upass) {
editbtnLog = 1;
document.getElementById('2ndDiv').className = "";//error
alert("The user " + preuname + " was successfully loged in and editbtnLog wass set to: " + editbtnLog);
}
else {
alert("Wrong Username or password!");
}
}
<div id="login1">
<form id="login">
Username<input type="text" placeholder="name">
Passowrd<input type="password" placeholder="password">
<input type="button" value="Submit" onclick="submitclick()">
</form>
</div>
<div id="2ndDiv" class="hidden">
<input type="button" id="show3rdDiv" value="Continue">
</div>
<div id="3rdDiv" class="hidden">
<div id="editbtnDiv">
<input type="button" id="editbtn" value="Edit"/>
</div>
</div>

Just a few minutes ago... (note: this is embarrassing!) i figured it out.
(This is not shown in the summarized codes mentioned above)
I made an element that changes its html value like a login button that turns into a logout if you are successfully logged in and changes back if you click it in its logout form so there is a loop. The button's value changes so i experimented a bit and realized that i could tie them together somehow. So i did. By declaring an onclick="" to the show3rdDiv button and a starting class of class="hidden" to editbtnDiv and stating that if the login button has a value of "login" then it keeps the hidden class but if it has a value of logout then it deletes that class.
I'm so stupid sometimes. :/

Related

Display output to multiple classes via JavaScript

I am writing a "Gamebook Engine" which offers the possibility of setting a user name. The Name is taken from an input with the id="setUserNameInput" and saved by the function setUserName(). It is displayed / loaded into an element containing the class="displayUserName" and loaded by the function displayUserName(). It works fine with only one class one the page, but as soon as I add more I have to define which one to target as it won't target them all automatically. I have tried to use document.getElementById, document.getElementsByName as well as document.querySelectorAll and document.querySelector, none of which work. (I use Bulma as my CSS Framework, by the way)
Here is the code I have so far (though it will show an error as it cannot access the localStorage inside the snippet):
This page http://scampsblog.com/docs/example-de.html contains an (working, haha) example. Since it is a documentation (page lies on my testing sever, thus the domain) you might want to take a look at http://scampsblog.com/docs/character-enginedotjs-de.html which explains / shows the individual elements (the documentation is in German but I can provide a translation if you need one).
The part of the JS I am struggling with is right in the first line but if you suggest some overall improvements, I will be happy to take them.
var userNameOutput = document.getElementsByClassName('displayUserName')[0];
function setUserName() {
var usernameinput = document.getElementById('setUserNameInput').value;
localStorage.setItem('userName', usernameinput);
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
function displayUserName() {
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
window.onload = function displayUserName() {
if (!localStorage.getItem('userName')) {
setUserName();
} else {
var storedUserName = localStorage.getItem('userName');
userNameOutput.innerHTML = storedUserName;
}
}
<input type="text" class="input" placeholder="Your name goes here" id="setUserNameInput">
<input type="button" class="button" value="Set your username" onclick="setUserName()" />
<input type="button" class="button" value="Display on click" onclick="displayUserName()" />
<br> So you shall be called <span class="displayUserName"></span>! But dont worry, <span class="displayUserName"></span>, it will be all fine.
Instead of getting the first item in the collection (using [0]) you could iterate through it (using for...of) and set the innerHTML of each element having the class displayUserName.
e.g.
var userNameOutputs = document.querySelectorAll('.displayUserName');
for (let ele of userNameOutputs) {
ele.innerHTML = userName;
}
Full code, with some optimizations to structure:
function setUserName() {
var usernameinput = document.getElementById('setUserNameInput').value;
localStorage.setItem('userName', usernameinput);
displayUserName(true); // pass true to avoid recursion
}
function displayUserName(skipSet) {
var userName = localStorage.getItem('userName');
if (!userName && !skipSet) {
setUserName();
} else {
var userNameOutputs = document.querySelectorAll('.displayUserName');
for (let ele of userNameOutputs) {
ele.innerHTML = userName;
}
}
}
window.onload = displayUserName;
<input type="text" class="input" placeholder="Your name goes here" id="setUserNameInput">
<input type="button" class="button" value="Set your username" onclick="setUserName()" />
<input type="button" class="button" value="Display on click" onclick="displayUserName()" />
<br> So you shall be called <span class="displayUserName"></span>! But dont worry, <span class="displayUserName"></span>, it will be all fine.
Working fiddle: https://jsfiddle.net/hosney/3pxfybrc/1/
var userNameOutput = document.getElementsByClassName('displayUserName')[0];
the [0] selects the first element of the array of elements of the class name.

Using number provided in submit as variable?

I need help understanding how to fix this.
<p> Enter a number in the box. </p>
<div>
<label for ="numberSubmitted"> Number: </label>
<input type="text" class="numberSubmitted">
<input type = "submit" value="Submit">
</div>
<div>
<p class="message"></p>
</div>
var numberSubmitted = Number(numberSubmitted.value);
var message = document.querySelector(".message");
if(numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
What's happening is that "You Lose!" is being printed out if I leave the variable as
var numberSubmitted = Number()
If change it to
var numberSubmitted = Number(numberSubmitted.value)
the code just doesn't work.
I don't see online any guide to tell you how to use Number() with classes.
Can anyone please point me in right direction on when to include class when defining the Number method?
So there are a few things:
The "for" in label needs to point to an id, not a class.
Your problem with it not working when you try to put numberSubmitted.value into Number() is that numberSubmitted is undefined, to fix this you need to get the html element of your input box and do .value on that.
You need to put your JavaScript in a script tag.
Try the following:
<p> Enter a number in the box. </p>
<div>
<label for="numberSubmitted"> Number: </label>
<input type="text" id="numberSubmitted">
<input type = "submit" value="Submit" onclick="submit()">
</div>
<div>
<p class="message"></p>
</div>
<script>
function submit() {
var numberSubmitted = Number(document.getElementById('numberSubmitted').value);
var message = document.querySelector(".message");
if(numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
}
</script>
Here's another option, using an event listener instead of the inline function call:
JS Fiddle Demo here.
HTML
<p> Enter a number in the box. </p>
<div>
<label for="numberSubmitted"> Number: </label>
<input type="text" id="numberSubmitted">
<input type="button" id="myBtn" value="Submit">
</div>
<div>
<p class="message"></p>
</div>
JS
//bind the listener to the button
document.getElementById('myBtn').addEventListener('click', myFunction);
//get the input element
var el = document.getElementById('numberSubmitted');
function myFunction() {
var numberSubmitted = Number(el.value);
//for debug
console.log(numberSubmitted);
var message = document.querySelector(".message");
if (isNaN(numberSubmitted)) {
message.textContent = "That isn't a number.";
return;
}
if (numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
}
As mentioned in my comments earlier, you need to wrap your JS in script tags. I've made other comments in the code segments above. You'll notice that wrapping your original JS in script tags isn't enough -- there is still an 'undefined' error pertaining to the numberSubmitted element. This is because JS has no idea what numberSubmitted is -- you need to find the element in the DOM and assign it to a variable. I've shown you how to do that above.

enable buttons in javascript/jquery based on regex match

I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>
Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>
Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().
Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

How to Pass the Email Id value after checking Captcha in Asp.Net Mvc4?

I am new one to Asp.Net Mvc4 with Entity Framework. Now i am doing Captcha verification for Forgot Password. As my code, I it is passing the Email id value to Controller when i am clicking submit button even the Captcha code is Invalid. I want to pass the Email id value to controller if the Captcha code is correct otherwise it should show the validation error and New captcha should get reloaded. Please help me to fix it. Thanks in advance.
This is my Java Script code for generation and validating the captcha:
var captchastring = '';
function getCaptcha() {
var chars = "0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9Jj0Kk1Ll2Mm3Nn4Oo5Pp6Qq7Rr8Ss9Tt0Uu1Vv2Ww3Xx4Yy5Zz";
var string_length = 7;
captchastring = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
captchastring += chars.substring(rnum, rnum + 1);
}
document.getElementById("randomfield").innerHTML = captchastring;
}
function validation() {
var text2 = document.getElementById("txtcode").value;
if (text2 == captchastring) {
var email = document.getElementById("UserEmail").value;
x = document.getElementById("demo");
// Find the element
x.innerHTML = "valid";
x.style.color = "#ff0000";
}
else {
x = document.getElementById("demo"); // Find the element
x.innerHTML = "Invalid Captcha. Try again";
x.style.color = "#ff0000";
}
}
</script>
This is my body of my cshtml code:
<div class="col-md-5">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<h5 class="nomargin">Forgot Password</h5>
#Html.TextBoxFor(u => u.UserEmail, new { #class = "form-control", placeholder = "Email" })
<br />
<div id="captcha">
<div id="captcha_gen">
<label id="randomfield">
</label>
</div>
<button type="button" onclick="getCaptcha();" style="border: 0; background: transparent;float:right; position:relative";>
<img src="../../Content/FSLBootstrapUI/images/playback_reload.png" width="25" height="25" alt="submit" />
</button>
</div>
<input type="text" id="txtcode" class="form-control" placeholder="Enter code here" />
<button class="btn btn-success btn-block" value="submit" onclick="validation()">Reset</button> <p id="demo"> </p>
}
</div>
What is happening currently? I mean, how is the application behaving?
EDIT:
You can try server side validation for example if you have a field to validate you can add a validation tag there.For example:
<input type="text" name="SampleTextBox" id="SampleTextBoxId"/>
#Html.ValidationMessage("SampleTextBox", "*")
Then you go to the controller and add this kind of code:
if (!string.IsNullOrEmpty(SampleTextBox))
{
//Your Code.
}
else
{
ViewData.ModelState.AddModelError("SampleTextBoxId", "Text should not be empty.");
}
Use Model.IsValid as your condition to write your main code.
Model.IsValid becomes False if ViewData.ModelState.AddModelError("SampleTextBoxId", "Text should not be empty."); is executed.
This is a way to add validations. You can check for your valid/invalid captcha in your controller itself and throw error.
For Example:
if (IsValidCaptcha(enteredCaptcha))
{
//Code
}
else
{
ViewData.ModelState.AddModelError("captchaId", "Enter valid captcha");
}
Lastly, add a validation summary to your page
#Html.ValidationSummary("Error Messages")

Categories

Resources