Javascript logic not working - javascript

The if condition is not working while the else if and else are working:
function userchk() {
var un = $('#user_name').val();
if (un.length < 3 && un.length != 0) {
$("#validateUser").html("<span style='color:red' class='status-not-available'>User Name Shoul Be Greater Then 3.</span>");
}
else if (un.length == 0) {
$('#validationUser').html("<span style='color:red' class='status-not-available'> User Name Cannot Be Empty.</span>");
}
else {
$('#validationUser').html("");
}
}
$('#btnTest').on('click', function() {
userchk();
});
input {
width: 100%;
margin-top: 20px;
float: left;
}
button {
font-size: 20px;
background-color: #555;
color: #fff;
padding: 10px 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnTest">Test userchk()</button>
<input type="text" name="user_name" id="user_name" onBlur="userchk()" class="form-control" placeholder="Username" />
<div id="validationUser"></div>

Your if condition results in an element with id #validateUser being selected and manipulated.
Your else if and else target #validationUser
The Javascript logic conditions are sound but you are not getting your expected results because you are targeting a different element in your if block.

Related

How to combine input values together

I am trying to combine Input values. Below is my working code, any help is appreciated.
Here is my code:
getCodeBoxElement(index) {
return document.getElementById("codeBox" + index);
}
onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
console.log((<HTMLInputElement>this.getCodeBoxElement(index)).value);
if ((<HTMLInputElement>this.getCodeBoxElement(index)).value.length === 1) {
if (index !== 6) {
this.getCodeBoxElement(index + 1).focus();
} else {
this.getCodeBoxElement(index).blur();
// Submit code
// for(var i=0; i<6; i++){
// this.verificationCode = (<HTMLInputElement>this.getCodeBoxElement(i)).toString;
// console.log(this.verificationCode);
// }
console.log("submit code ");
}
}
if (eventCode === 8 && index !== 1) {
this.getCodeBoxElement(index - 1).focus();
}
}
onFocusEvent(index) {
for (var item = 1; item < index; item++) {
const currentElement = this.getCodeBoxElement(item);
if (!(<HTMLInputElement>currentElement).value) {
currentElement.focus();
break;
}
}
}
/* Body Styling only end */
section {
display: flex;
/* align-items: center;
width: 100vw;
height: 100vh; */
text-align: center;
}
section form {
display: flex;
align-items: center;
width: auto;
margin-left: 12px;
/* margin: 0 auto; */
}
section form input {
width: 40px;
height: 40px;
text-align: center;
margin-left: -10px;
border: none;
border-radius: 10px;
}
section form input:last-child {
margin-right: 0;
}
section form input::-webkit-inner-spin-button,
section form input::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
section form input:focus,
section form input.focus {
border-color: green;
outline: none;
box-shadow: none;
}
<section>
<form style="margin-top: 10px;">
<input id="codeBox1" type="text" maxlength="1" (keyup)="onKeyUpEvent(1, $event)"
(focus)="onFocusEvent(1)" autocomplete="off">
<input id="codeBox2" type="text" maxlength="1" (keyup)="onKeyUpEvent(2, $event)"
(focus)="onFocusEvent(2)" autocomplete="off">
<input id="codeBox3" type="text" maxlength="1" (keyup)="onKeyUpEvent(3, $event)"
(focus)="onFocusEvent(3)" autocomplete="off">
<input id="codeBox4" type="text" maxlength="1" (keyup)="onKeyUpEvent(4, $event)"
(focus)="onFocusEvent(4)" autocomplete="off">
<input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off">
<!-- <input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off"> -->
</form>
</section>
Inputs return the value of the input as a string by default... So concatenating the values will combine them by default... If you want to add them as you would numbers, you would need to parse the value as an integer... Otherwise you can simply combine their values by using the plus symbol + => input.value + input2.value. Even the input type number value will return a string so by concatenating the values together you will be combining their values into one string, this would include numbers with typeof = string.
See my example inputs and their outputs for reference...
EDIT: For your issue, you can create an array to hold the value of each input through the iteration in your function... Once you have reached the threshold conditional, join the values of your array.
// create an array to hold your values
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
// save the value within your array with each selection
code[index] = getCodeBoxElement(index).value
if (index !== 4) {
getCodeBoxElement(index+ 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
// join the array values into a string using .join('');
let codeString = code.join('')
console.log(codeString)
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function getCodeBoxElement(index) {
return document.getElementById('codeBox' + index);
}
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
//code[index] = getCodeBoxElement(index).value also works
code.push(getCodeBoxElement(index).value)
if (index !== 4) {
getCodeBoxElement(index + 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
let codeString = code.join('');
let display = document.getElementById('display')
display.style.color = 'darkgreen';
display.textContent = `You have entered: ${codeString}`;
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function onFocusEvent(index) {
for (item = 1; item < index; item++) {
const currentElement = getCodeBoxElement(item);
if (!currentElement.value) {
currentElement.focus();
break;
}
}
}
// Body Styling only Begin ==============
body {
text-align: center;
background-color: lightcyan;
font-family: 'POPPINS', Open-Sans;
background: linear-gradient(to right, #4568dc, #b06ab3);
}
::selection {
color: #8e44ad;
}
// Body Styling only End ================
// Container-fluid Styling only Begin ===
.container-fluid {
.row {
align-items: center;
width: 100vw;
height: 100vh;
}
}
// Container-fluid Styling only End =====
// =====
// Passcode-wrapper Styling only Begin ==
.passcode-wrapper {
display: flex;
justify-content: space-between;
align-items: center;
width: auto;
margin: 0 auto;
input {
width: 50px;
height: 50px;
padding: 0;
margin-right: 5px;
text-align: center;
border: 1px solid gray;
border-radius: 5px;
&:last-child {
margin-right: 0;
}
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
&:focus,
&.focus {
border-color: green;
outline: none;
box-shadow: none;
}
}
}
// Passcode-wrapper Styling only End ====
<section class="container-fluid">
<div class="row">
<div class="col-md-8 offset-md-2">
<form class="text-center">
<div class="form-group">
<label for="password" class="text-white">Enter 4 Digit Password</label>
<div class="passcode-wrapper">
<input id="codeBox1" type="number" maxlength="1" onkeyup="onKeyUpEvent(1, event)" onfocus="onFocusEvent(1)">
<input id="codeBox2" type="number" maxlength="1" onkeyup="onKeyUpEvent(2, event)" onfocus="onFocusEvent(2)">
<input id="codeBox3" type="number" maxlength="1" onkeyup="onKeyUpEvent(3, event)" onfocus="onFocusEvent(3)">
<input id="codeBox4" type="number" maxlength="1" onkeyup="onKeyUpEvent(4, event)" onfocus="onFocusEvent(4)">
</div>
</div>
</form>
</div>
</div>
</section>
<div id="display"></div>
I just did it like this when I did something like this.
document.onkeyup = function() {
ch = document.getElementsByClassName("ch");
x = ch.length;
out = "";
for (y=0;x>y;y++) {
out += ch[y].value;
}
document.getElementById("final").innerHTML = out;
}
<input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'>
<span id="final" style="color: green;"></span>

How to add auto calculation for two inputs

I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});

Make it so 'Go/Enter' key is pressable

I have a basic form which makes it so the user cannot leave the input field empty before the form posts the page. It also prevents the user from entering gibberish and requires them to only enter numbers, but this also blocks all keys that aren't numbers including the Go/Enter on mobile keyboards. My question is, is there a way to make it so that the user has to enter only numbers, but also be able to press Go after they have entered the field?
FIDDLE:http://jsfiddle.net/schermerb/nX8Hx/
Currently a user has to input a zip THEN tap back on the screen and THEN click submit.
$(document).ready(function () {
$("#quantity").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Enter Valid Zip!").show().fadeOut("5000");
return false;
}
});
});
var initVal = "Have a good name for it? Enter Here";
$(document).ready(function () {
$(".submit-name").attr("disabled", "true");
$(".recipe-name").blur(function () {
if ($(this).val() != initVal && $(this).val() != "") {
$(".submit-name").removeAttr("disabled");
} else {
$(".submit-name").attr("disabled", "true");
}
});
});
input {
width: 100%;
background: #FFFFFF;
border-radius: 4px;
border: 2px solid #acd50b;
padding: 10px 15px;
text-align: center;
-webkit-appearance: none;
color: #999999;
font-size: 11px;
}
input[type="focus"] {
outline: none;
}
input[type="submit"] {
border-radius: 4px;
border: 2px solid #2d8b1b;
-webkit-appearance: none;
background: #acd50b;
padding: 6px 10px;
color: #444444;
width: 100%;
font-size: 18px;
cursor:pointer;
}
.box {
width: 85px;
}
.boxtwo {
width: 160px;
}
<form action="google.html" method="get" id="recipename">
<div class="box">
<input onFocus="this.value=''" type="text" value="Enter Your Zip" placeholder="Enter Your Zip" /><span id="errmsg"></span>
</div>
<div class="boxtwo">
<input type="submit" value="Compare" id="register" disabled value="Compare" class="submit-name" />
</div>
</form>
It would be better to use keydown and test the resulting value and revert it rather than only allowing certain characters to be inserted.
$("#quantity").keydown(function (e) {
var self = this;
var tempVal = this.value;
setTimeout(function () {
if (!isValidZip(self.value)) {
self.value = tempVal;
}
}, 0);
});
function isValidZip(zip) {
return /^[0-9]{1,5}$/.test(zip);
}
http://jsfiddle.net/nX8Hx/3/
This could also be done with keyup or keypress, however keydown makes it happen much quicker and allows you to easily get the previous value.
Doing it this way avoids the issue of preventing the done key by not testing which key is pressed. It's also easily expandable by simply changing the regexp to match a different kind of zip code.

How to apply CSS styling to elements created by jquery's append()?

I am trying to create a dynamic form, and have run into a problem with styling that makes itself quite apparent when you add elements to a form. There is styling added to inputs on load that aren't applied to any created when I add them with jQuery's append() function. The margins are nonexistant on the new input elements, whereas if I add them manually in the beginning on page load the styling is there. Seems to be some browser default styling which I cannot override. How do I fix this? Example code below.
CSS:
#GraphTools
{
border-top: 1px solid #BBBBBB;
height: 24px;
margin: 0 5px 3px;
padding-top: 2px;
}
#GraphSearch
{
float: left;
}
#GraphTools input
{
background-color: rgba(255, 255, 255, 0.4);
border-radius: 3px 3px 3px 3px;
box-shadow: 0 0 2px #444444 inset;
font-size: 14px;
padding: 2px;
}
#GraphTools input[type=button]:active, #GraphTools input[type=submit]:active
{
background-color: rgba(192, 192, 192, 0.4);
}
#GraphSearchFields
{
float: left;
margin-right: 5px;
}
#GraphSearchFields input
{
margin: 0 5px 0 5px;
}
#GraphZoom
{
float: right;
}
HTML:
<div id="GraphTools">
<div id="GraphSearch">
<form id="GraphSearchForm">
<div id="GraphSearchFields">
<input type="text" data-default-value="Sender" id="SenderBox0" class="GraphSearchBox" />
<input type="text" data-default-value="Reciever" id="RecieverBox0" class="GraphSearchBox" />
<input type="text" data-default-value="Sender" id="SenderBox1" class="GraphSearchBox" />
<input type="text" data-default-value="Reciever" id="RecieverBox1" class="GraphSearchBox" />
</div>
<input type="button" id="AddNewHumanSet" value="+" />
<input type="submit" value="Go" />
<input type="button" value="Reset" class="GraphResetButton" />
</form>
</div>
<div id="GraphZoom">
<input type="button" value="-" />
<input type="button" value="+" />
</div>
</div>
Javascript:
$(document).ready(function ()
{
function LoadDefaultSearchBoxValues()
{
$(".GraphSearchBox").each(function (i, e)
{
if ($(this).val() == "")
{
$(this).val($(this).data("default-value"));
}
});
}
LoadDefaultSearchBoxValues();
$(".GraphSearchBox").live("focus", function ()
{
if ($(this).val() == $(this).data("default-value"))
{
$(this).val("");
}
});
$(".GraphSearchBox").live("blur", function ()
{
if ($(this).val() == "")
{
$(this).val($(this).data("default-value"));
}
});
$("#GraphSearchForm").live("submit", function (event)
{
event.preventDefault();
var SenderBoxHasValue = !($("#SenderBox").val() == $("#SenderBox").data("default-value") && $("#SenderBox").val() == "");
var RecieverBoxHasValue = !($("#RecieverBox").val() == $("#RecieverBox").data("default-value") && $("#RecieverBox").val() == "");
if (SenderBoxHasValue && RecieverBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.source.data.label.toLowerCase().indexOf($("#SenderBox").val().toLowerCase()) != -1 &&
edge.target.data.label.toLowerCase().indexOf($("#RecieverBox").val().toLowerCase()) != -1;
});
}
else if (SenderBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.source.data.label.toLowerCase().indexOf($("#SenderBox").val().toLowerCase()) != -1;
});
}
else if (RecieverBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.target.data.label.toLowerCase().indexOf($("#RecieverBox").val().toLowerCase()) != -1;
});
}
});
$(".GraphResetButton").live("click", function ()
{
graph.resetGraph();
});
$("#AddNewHumanSet").live("click", function ()
{
var inputcount = $("#GraphSearchFields").children("input").length / 2;
var mod4 = $("#GraphSearchFields").children("input").length % 4;
if (mod4 == 0)
{
$("#GraphSearchFields").append("<br />");
}
$("#GraphSearchFields").append('<input type="text" data-default-value="Sender" id="SenderBox' + inputcount + '" class="GraphSearchBox" /><input type="text" data-default-value="Reciever" id="RecieverBox' + inputcount + '" class="GraphSearchBox" />');
LoadDefaultSearchBoxValues();
});
});
You need to put a space in between 2 input boxes when you append them.
Take a look at this working demo it is fine now
http://jsfiddle.net/2xfED/1/

Does anyone know why my multi-phase form won't work?

I am making a multi-phase form but it is not acting normal
I have written a lot of diffrent code for it but don't know why it is not working the way I want it
It has been two days working with it I am feeling stupid now
here is the code
HTML:
<div id="form-container">
<div id="phase-1">
<h3>Phase 01</h3>
<form>
<input id="fname" type="text" placeholder="First name">
<input id="lname" type="text" placeholder="Last name">
<input id="email" type="text" placeholder="Email">
<button id="phase-1-btn">Next</button>
</form>
</div>
<div id="phase-2">
<h3>Phase 02</h3>
<form>
<input id="pass" type="text" placeholder="Password">
<input id="cpass" type="text" placeholder="Confirm Password">
<button id="phase-2-btn">Next</button>
</form>
</div>
<div id="phase-3">
<h2>Thank You for Testing my pen</h2>
</div>
</div>
CSS :
#form-container{
height: 350px;
width: 300px;
margin-top: 80px;
margin-left: auto;
margin-right: auto;
background-color: #95a5a6;
font-family: "Slabo 27px";
position: relative;
box-shadow: 1px 1px 2px,
-1px -1px 2px;
}
#phase-1, #phase-2{
height: 100%;
width: 100%;
border-top: 3px solid #f39c12;
display: block;
}
#phase-1 h3, #phase-2 h3{
height: 10%;
width: 60%;
margin-left: auto;
margin-right: auto;
text-align: center;
font-size: 23px;
color: #fff;
}
#phase-1 form, #phase-2 form{
display: block;
height: 75%;
padding: 0;
padding-top: 15px;
margin: 0;
}
input{
display: block;
width: 80%;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
button {
display: block;
width: 60%;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
padding: 10px 5px;
background-color: #f39c12;
color: #fff;
font-weight: 600;
border: none;
border-radius: 6px;
}
#phase-2{
display: none;
}
#phase-3{
display: none;
height: 0;
width: 100%;
color: #000;
position: absolute;
top: 0;
left: 0;
background: #f39c12
}
#phase-3 h2{
width: 200px;
height: 60px;
margin-left: auto;
margin-right: auto;
margin-top: 135px;
text-align: center;
}
JS :
var fname, lname, email, pass, cpass;
function id( id ) {
return document.getElementById(id);
}
function phase1 () {
fname = id("fname").value;
lname = id("lname").value;
email = id("email").value;
if ( fname.length > 2 && lname.length > 2 && email.length > 2 ) {
id("phase-1").style.display = "none";
id("phase-2").style.display = "block";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase1 function
// add the event to the phase-1-btn
id("phase-1-btn").addEventListener("click", phase1());
/* phase 02 */
function phase2 () {
pass = id("pass").value;
cpass = id("cpass").value;
if ( pass.length > 2 && cpass.length > 2 ) {
id("phase-2").style.display = "none";
id("phase-3").style.display = "block";
id("phase-3").style.height = "100%";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase2 function
id("phase-2-btn").addEventListener("click", phase2());
Let's try this one. Then tell me what you see in the console.
<script>
function phase1()
{
window.console.log('phase1 function called');
var fname_val = document.getElementById('fname').value;
var lname_val = document.getElementById('lname').value;
var email_val = document.getElementById('email').value;
// verify values
window.console.log('fname_val='+fname_val + ' lname_val='+lname_val + ' email_val='+email_val);
if( fname_val.length > 2 && lname_val.length > 2 && email_val.length > 2 )
{
window.console.log('validation!! :)');
document.getElementById("phase-1").style.display = "none";
document.getElementById("phase-2").style.display = "block";
}
else
{
alert("Please fill the Form");
}
}
function phase2()
{
window.console.log('phase2 function called');
}
document.addEventListener("DOMContentLoaded", function(event) {
window.console.log("DOM fully loaded and parsed");
document.getElementById("phase-1-btn").addEventListener("click", phase1);
document.getElementById("phase-2-btn").addEventListener("click", phase2);
});
</script>
<div id="phase-1">
<h3>Phase 01</h3>
<input id="fname" type="text" placeholder="First name" />
<input id="lname" type="text" placeholder="Last name" />
<input id="email" type="text" placeholder="Email" />
<input type="button" id="phase-1-btn" value="Next" />
</div>
<div id="phase-2">
<h3>Phase 02</h3>
<input id="pass" type="text" placeholder="Password" />
<input id="cpass" type="text" placeholder="Confirm Password" />
<input type="button" id="phase-2-btn" value="Next" />
</div>
<div id="phase-3">
<h2>Thank You for Testing my pen</h2>
</div>
To submit a form you want to use a submit button (not classic button).
Have all of your inputs within the form tags.
Add the appropriate form tag attributes such as (action & method)
Use one form tag that wraps around everything with the submit button on the inside.
CSS will have no effect so no need to share that part.
Last but not least - Dont call yourself stupid. Stupid people never ask for help. Reaching out for help is how you improve your skillset.
If you insist on using Javascript to submit the form that is fine, but you want to make sure the form works with classic HTML first.
To make this a multi-step process you should try doing 1 form per page. You will need to understand session handling. You can display portions of the form at a time with Javascript which gives an impression of doing steps but still using 1 form.
<form action="" method="POST">
<script>
function toggleSection(x){
document.getElementById('sec'+x).style.display = "block";
}
</script>
<div id="sec1">
section 1 stuff
<input type="button" value="Continue" onclick="toggleSection(2);" />
</div>
<div id="sec2" style="display:none;">
section 2 stuff
<input type="button" value="Continue" onclick="toggleSection(3);" />
</div>
<div id="sec3" style="display:none;">
section 3 stuff
<input type="submit" value="Submit" />
</div>
</form>
here it is with the changes you ordered
var fname, lname, email, pass, cpass;
function el( id ) {
return document.getElementById(id);
}
function phase1 () {
fname = el("fname").value;
lname = el("lname").value;
email = el("email").value;
if ( fname.length > 2 && lname.length > 2 && email.length > 2 ) {
el("phase-1").style.display = "none";
el("phase-2").style.display = "block";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase1 function
// add the event to the phase-1-btn
el("phase-1-btn").addEventListener("click", phase1);
/* phase 02 */
function phase2 () {
pass = el("pass").value;
cpass = el("cpass").value;
if ( pass.length > 2 && cpass.length > 2 ) {
el("phase-2").style.display = "none";
el("phase-3").style.display = "block";
el("phase-3").style.height = "100%";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase2 function
el("phase-2-btn").addEventListener("click", phase2);

Categories

Resources