Reference Textarea W/ Input - javascript

I am looking to build a simple webpage that can check to see if a string contains certain information. I'm taking a summer course in Java and wanted to give Javascript a try. Maybe a bad idea?
I want the user to enter information - name, phone number, and a couple other options in a form. Then I want the user to enter more information in the text area. The text area will reference the input data and if there is a match it will alert the user.
I have limited javascript experience, but I've been able to manipulate user input with javascript in the past.
Not sure what my problem here is. Any tips (especially regarding style and logic) are greatly appreciated! PS - I'm using Bootstrap if that matters...
Thanks in advance :)
HTML
<div class="container">
<div class="col-md-6">
<form>
<input type="text" id="Name" placeholder="Name" style="width:100%"><br /><br />
<input type="text" id="Number" placeholder="Number" style="width:100%"><br /><br />
<input type="text" id="Next" placeholder="Something Else" style="width:100%"><br /><br />
<input type="text" id="WhatEver" placeholder="Something Else" style="width:100%"><br /><br />
</form>
</div>
<div class="col-md-6">
<textarea id="LongText" placeholder="Enter Info" style="width:100%; height:250px">
</textarea> <br />
<input type="submit" class="btn btn-danger" id="tSubmit" value="Submit" onclick="GetInput();Check();">
</div>
<div class="col-md-12">
<h1>Output</h1>
<div id="tOutPut" style="color:red;"></div>
</div>
</div>
JS
GetInput()
{
var tNameValue = document.getElementById("Name").value;
var tValue = document.getElementById("Number").value;
var tArray = document.getElementById('LongText').value.split('\n');
}
Check( tArray, tNameValue, tValue )
{
for(var i = 0; i < tArray.length; i++ )
{
if( i === tNameVaue )
{
document.getElementById( 'tOutPut' ).innerText = "Name Match" <br />;
}
if( i === tValue )
{
document.getElementById( 'tOutPut' ).innerText = "Match" <br />;
}
}
}
*

Your javascript has many things wrong. Here is the HTML and the Javascript. The logic must be improved but the code is working.
<div class="container">
<div class="col-md-6">
<form>
<input type="text" id="Name" placeholder="Name" style="width:100%"><br /><br />
<input type="text" id="Number" placeholder="Number" style="width:100%"><br /><br />
<input type="text" id="Next" placeholder="Something Else" style="width:100%"><br /><br />
<input type="text" id="WhatEver" placeholder="Something Else" style="width:100%"><br /><br />
</form>
</div>
<div class="col-md-6">
<textarea id="LongText" placeholder="Enter Info" style="width:100%; height:250px">
</textarea> <br />
<input type="submit" class="btn btn-danger" id="tSubmit" value="Submit" onclick="ExecuteAll();">
</div>
<div class="col-md-12">
<h1>Output</h1>
<div id="tOutPut" style="color:red;"></div>
</div>
</div>
And here is the Javascript:
var tNameValue;
var tValue;
var tArray;
function ExecuteAll()
{
GetInput();
Check();
}
function GetInput()
{
tNameValue = document.getElementById("Name").value;
tValue = document.getElementById("Number").value;
tArray = document.getElementById('LongText').value.split('\n');
}
function Check()
{
if (tArray != null) {
for(var i = 0; i < tArray.length; i++ )
{
if( i == tNameValue )
{
document.getElementById( 'tOutPut' ).innerText = "Name Match <br />";
}
if( i == tValue )
{
document.getElementById( 'tOutPut' ).innerText = "Match <br />";
}
}
}
}
I will tell you what I did to fix the bugs:
Added function keyword to the javascript functions.
Put the variables as global so they can be used for the whole code.
Verified whether tArray is not null.
Fixed variable names.
Here is the Fiddle code: http://jsfiddle.net/3U6mE/6/
I hope it helps you get started.

Related

How do I grab a value from an input in javascript?

how do i grab a value from an input element in javascript? For some reason my code is not executing. This is my HTML code:
<section id ="my-life" style="margin-left:39em;">
<input class="jenny" placeholder="Your First Name"/> <br /><br />
<button id="get">Subscribe</button>
<br /><br />
<div id ="whitelion">Thank You!</div>
This is my javascript code:
function buttonClicked() {
var Niche = document.getElementsByClassName("jenny");
var results = document.getElementById("whitelion");
results.innerHTML = "Hello" + Niche[0].value;
}
function buttonClicked() {
var Niche = document.getElementsByClassName("jenny");
var results = document.getElementById("whitelion");
results.innerHTML = "Hello " + Niche[0].value;
}
<input class="jenny" placeholder="Your First Name"/>
<br /><br />
<button onclick='buttonClicked();'>Subscribe</button>
<br /><br />
<div id ="whitelion">Thank You!</div>
<section id ="my-life" style="margin-left:39em;">
<input class="jenny" placeholder="Your First Name"/> <br /><br />
<button id="get">Subscribe</button>
<br /><br />
<div id ="whitelion">Thank You!</div>
<script>
function buttonClicked() {
var Niche = document.getElementsByClassName("jenny");
var results = document.getElementById("whitelion");
results.innerHTML = "Hello" + Niche[0].value;
}
document.getElementById('get').onclick = buttonClicked;
</script>
I tried your code on the editor. It works fine. But you must include your JS code inside a <script> element. And put it in the bottom of the document.
function buttonClicked() {
var Niche = document.getElementsByClassName("jenny");
var results = document.getElementById("whitelion");
results.innerHTML = "Hello " + Niche[0].value;
}
<section id ="my-life">
<input class="jenny" placeholder="Your First Name"/> <br /><br />
<button id="get" onclick="buttonClicked()">Subscribe</button>
<br /><br />
<div id ="whitelion">Thank You!</div>
<br/>
</section>

HTML / JS countdown to call on php file

good day! i'm using this code i found in this site to run a countdown timer that when it reaches zero, it will run a php file. what i have noticed is that when the tab on the server is closed is that it does not actually call the php file. do you guys have any solution to this? Any help will be very much appreciated.
switch1.js file and index.html file
var interval;
function start() {
// If a timer is already running, stop it
stop();
// Get and validate user input
var userInput = document.getElementById('userTime').value;
if (userInput.length == 0) {
return alert("Please enter a value");
}
var numericExpression = /^[0-9]+$/
if (!userInput.match(numericExpression)) {
return alert("Please enter a number");
}
// Calculate end date/time
expires = Date.now() + ((userInput * 60000) + 1000); // Assumes userInput is in seconds
localStorage.setItem("expires", expires);
runTimer(); // Start the actual timer
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
expires = 0;
localStorage.setItem("expires", expires);
// Clear the display
display("notifier", " ");
}
var actions = {
10: function() {
display("notifier", "Just 10 seconds to go");
},
5: function() {
display("notifier", "5 seconds left");
},
0: function() {
window.location = 'off1.php'
}
};
function runTimer() {
interval = setInterval(function() {
var remain = Math.floor((expires - Date.now()) / 1000);
// If expired time come and gone
if (remain < 0) {
clearInterval(interval);
interval = null;
return;
}
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
}, 1000);
}
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond(x) {
return Math.floor(x / 60) + ":" + x % 60;
}
// If a timer is already setup (page has been refreshed) continue it
var expires = localStorage.getItem("expires");
if (expires > 0) runTimer();
<div>
<br>
<br>
</br>
<div id="countdown"></div>
<div id="notifier"></div>
Please Enter A Number: <input type="text" id="userTime" />
<input type="button" value="Go" onclick="start()" />
<input type="button" onclick="stop()" value="Stop it" />
</br>
</div>
<div>
<br>
<br>
</br>
<div id="countdown1"></div>
<div id="notifier1"></div>
Please Enter A Number: <input type="text" id="userTime1" />
<input type="button" value="Go" onclick="start1()" />
<input type="button" onclick="stop1()" value="Stop it" />
</br>
</div>
<div>
<br>
<br>
</br>
<div id="countdown2"></div>
<div id="notifier2"></div>
Please Enter A Number: <input type="text" id="userTime2" />
<input type="button" value="Go" onclick="start2()" />
<input type="button" onclick="stop2()" value="Stop it" />
</br>
</div>
<div>
<br>
<br>
</br>
<div id="countdown3"></div>
<div id="notifier3"></div>
Please Enter A Number: <input type="text" id="userTime3" />
<input type="button" value="Go" onclick="start3()" />
<input type="button" onclick="stop3()" value="Stop it" />
</br>
</div>
<div>
<br>
<br>
</br>
<div id="countdown4"></div>
<div id="notifier4"></div>
Please Enter A Number: <input type="text" id="userTime4" />
<input type="button" value="Go" onclick="start4()" />
<input type="button" onclick="stop4()" value="Stop it" />
</br>
</div>
<div>
<br>
<br>
</br>
<div id="countdown5"></div>
<div id="notifier5"></div>
Please Enter A Number: <input type="text" id="userTime5" />
<input type="button" value="Go" onclick="start5()" />
<input type="button" onclick="stop5()" value="Stop it" />
</br>
</div>
<div>
<br>
</br>
<br>
<div id="countdown6"></div>
<div id="notifier6"></div>
Please Enter A Number: <input type="text" id="userTime6" />
<input type="button" value="Go" onclick="start6()" />
<input type="button" onclick="stop6()" value="Stop it" />
</br>
</div>
<div>
<br>
<br>
</br>
<div id="countdown7"></div>
<div id="notifier7"></div>
Please Enter A Number: <input type="text" id="userTime7" />
<input type="button" value="Go" onclick="start7()" />
<input type="button" onclick="stop7()" value="Stop it" />
</br>
</div>
You are running a javascript script on the client-side. The browser the user's computer are basically doing everything. When the counter running on the browser reaches zero it tells the browser to navigate to a certain link. The browser sends a GET request to that link.
On the server-side, a php script is initiated when the server receives a GET request to it.
Since when you are closing the tab, you are stopping the script, the event in which the GET request is being sent never occurs. Thus the server never gets this request and never starts the script.

Adding a node to html page with javascript

This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>

Text Input To Sentence Case

I have a form whose is saved to the database and generates a PDF.
I want to have the input text transformed to sentence case. Tried style="text-transform:capitalize" but it still save the input as it was typed into the database. How can I do this, perhaps with JavaScript?
<form class="form-style-9" name="litterregistration" id="LitterReg" method="post">
<li>
<input type="text" name="AKennel" required class="field-style field-split align-left" placeholder="Kennel Name" style="text-transform:capitalize" />
<input type="text" name="BDamMother" required class="field-style field-split align-right" placeholder="Dame (Mother)" style="text-transform:capitalize"/>
</li>
<input type="submit" value="Save as PDF" onClick="Onsubmit1();" />
<input type="button" onclick="ClearFormFields()" value="Clear All Fields">
</form
<script>
function Onsubmit1()
{
document.litterregistration.action = "tcpdf/examples/form-litter-regis.php"
return true;
}
</script>
Please, note this is a NOT scalabe solution, and will only work with this specif code
Hi, a few notes first:
- you call a ClearFormFields() function but it isn't build anywhere;
- the name onSubmit1() for the function is not really good.
- You've missed a /> in the form tag.
With this is mind, this should do the (THIS) trick:
Javascript:
<script type="text/javascript">
function mySubmitAction(myAction) {
with (document.getElementById("LitterReg")) {
AKennel.value = AKennel.value.toUpperCase();
BDamMother.value = BDamMother.value.toUpperCase();
}
document.litterregistration.action = myAction;
return true;
}
</script>
HTML
<form class="form-style-9" name="litterregistration" id="LitterReg" method="post">
<li>
<input type="text" name="AKennel" required class="field-style field-split align-left" placeholder="Kennel Name" style="text-transform:capitalize" />
<input type="text" name="BDamMother" required class="field-style field-split align-right" placeholder="Dame (Mother)" style="text-transform:capitalize"/>
</li>
<input type="submit" value="Save as PDF" onclick="mySubmitAction('tcpdf/examples/form-litter-regis.php');" />
<input type="button" onclick="ClearFormFields()" value="Clear all fields" />
</form>
var $input1 = $( '#input-1' );
$.toSentenceCase = function ( value ) {
var val = value.split( ' ' );
for ( var i = 0, l = val.length; i < l; i++ ) {
val[i] = val[i].charAt(0).toUpperCase() + val[i].substr(1);
}
return val.join( ' ' );
}
$input1.on( 'blur', function ( e ) {
var $this = $( this );
$this.val( $.toSentenceCase( $this.val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input-1">
</form>

Mutilple javascript variable iterations with jquery

i have a form and would like to give users the ability to duplicate a group of fields as many times as necessary. With one group it iterates correctly but when I add a second group the "current" variable iterates collectively instead of being unique to each group... i tried changing all of the "current" to "newFieldset.current" but that returns NAN... any ideas?
<script type="text/javascript">
$(document).ready(function() {
var current = 0;
//Add New Fieldset with Button
var newFieldset = {
init: function(groupIndex) {
current++;
$newPerson= $("#Template"+groupIndex).clone(true);
$newPerson.children("p").children("label").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("for",$currentElem.attr("for")+current);
});
$newPerson.children("p").children("input").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("name",$currentElem.attr("name")+current);
$currentElem.attr("value",$currentElem.attr("value")+groupIndex+current);
$currentElem.attr("id",$currentElem.attr("id")+current);
});
$newPerson.appendTo("#mainField"+groupIndex);
$newPerson.removeClass("hideElement");
},
currentID: null,
obj: null
};
$(".addButton").each(function() {
$(this).click(function() {
var groupIndex = $(this).attr("title");
//newFieldset.obj = this;
//var fieldIndex = $(this).attr("class");
newFieldset.init(groupIndex);
});
});
console.log('r');
});
</script>
<style>
.hideElement {display:none;}
</style>
<form name="demoForm" id="demoForm" method="post" action="#">
<div id="groupCtr1">
<fieldset id="mainField1">
<div id="Template1" class="hideElement">
<p>
<label for="firstname">Name</label> <em>*</em>
<input id="firstname" name="firstname" size="25" /> <input id="lastname" name="lastname" size="25" />
</p>
<p>
<label for="email">Email</label> <em>*</em><input id="email" name="email" size="25" />
</p>
</div>
<div>
<p>
<label for="firstname1">Name</label>
<em>*</em> <input id="firstname1" name="firstname1" size="25" /> <input id="lastname1" name="lastname1" size="25" />
</p>
<p>
<label for="email1">Email</label>
<em>*</em><input id="email1" name="email1" size="25" />
</p>
</div>
</fieldset>
<p>
<input type="button" class="addButton" title="1" value="Add Another Person">
</p>
</div>
<div id="groupCtr2">
<fieldset id="mainField2">
<div id="Template2" class="hideElement">
<p>
<label for="coname">Company Name</label> <em>*</em>
<input id="coname" name="coname" size="25" />
</p>
<p>
<label for="codesc">Description</label> <em>*</em><input id="codesc" name="codesc" size="25" />
</p>
</div>
<div>
<p>
<label for="coname1">Company Name</label>
<em>*</em> <input id="coname1" name="coname1" size="25" />
</p>
<p>
<label for="codesc1">Description</label>
<em>*</em><input id="codesc1" name="codesc1" size="25" />
</p>
</div>
</fieldset>
<p>
<input type="button" class="addButton" title="2" value="Add Another Company">
</p>
</div>
<input type="submit" value="Save">
</form>
Attach the value to the element with the jQuery data method. Increment it on click, and then pass it to the newFieldset.init method as the second param. Voila!
$(document).ready(function() {
//Add New Fieldset with Button
var newFieldset = {
init: function(groupIndex,current) {
$newPerson= $("#Template"+groupIndex).clone(true);
$newPerson.children("p").children("label").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("for",$currentElem.attr("for")+current);
});
$newPerson.children("p").children("input").each(function(i) {
var $currentElem= $(this);
$currentElem.attr("name",$currentElem.attr("name")+current);
$currentElem.attr("value",$currentElem.attr("value")+groupIndex+current);
$currentElem.attr("id",$currentElem.attr("id")+current);
});
$newPerson.appendTo("#mainField"+groupIndex);
$newPerson.removeClass("hideElement");
},
currentID: null,
obj: null
};
$(".addButton").click(function() {
var groupIndex = $(this).attr("title");
var current = $(this).data('current');
$(this).data('current',++current);
//newFieldset.obj = this;
//var fieldIndex = $(this).attr("class");
newFieldset.init(groupIndex,current);
}).data('current',0);
console.log('r');
});
Happy jquery-ing to you sir.
if you dont make the current variable global it will should work. try this:
var newFieldset = {
current: 0,
init: function() {
this.current++;
//rest of init code
},
//all your other fieldset code here
};
/* all other code */
EDIT: After re-reading the question, I would take a completely different approach to what you're trying to achieve. The above code will still exhibit the same behavior for you. If the question hasn't been successfully answered I'll do a bigger writeup when i get home.
I would do something like that:
...
var currents = {};
var newFieldset = {
init: function(groupIndex) {
var current = 0;
if (currents[groupIndex]) {
current = currents[groupIndex];
}
++current;
currents[groupIndex] = current;
...

Categories