I have text file. there around 1000 lines in it, each line contains a 8 letter alpha numeric word for example my text file looks like this
TEST1234
T1E2A334
12RR8912
and so on. this file is located on the server in a folder called TestCodes
Now I have an html file called test.html where in this file I have input textbox where the user enters the testcode he/she has with them
I have button called Verify. when this input button is clicked I want to check the user inputed value against the contents in the text file.
If the testcode exists in the text file then display a button called Procced if not display an error message called invalid.
I know how to write the if condition but I have no idea how to check it against the text file
HTML
<div class="user-input">
<input type="text" name="test-code" id="test-code" value="" />
<input type="submit" value="Verify Code" name="verify-code" id="verify-code" />
</div>
<div id="TestRegister">
<form id="club" action="/Proceed.html" method="post" autocomplete="off">
<input type="submit" value="Proceed Registration" name="proceed-register" />
</form>
</div>
<div id="TestError">
<span>Please check the code again, its not valid</span>
</div>
JavaScript
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#TestRegister").hide();
$("#TestError").hide();
$.get("testcodes.txt", function (data) {
var lines = data.split("\n");
// this is where I am stuck. how to pass the above to ARRAY
$("#verify-code").click(function (e) {
e.preventDefault();
if ( /* here I need to check against the user input value, if they are equal */ ) {
$("#TestRegister").show();
$("TestError").hide();
} else {
$("#TestRegister").hide();
$("TestError").show();
}
}
});
</script>
How can I pass text from testcodes to an Array and then check the user input value against this array? If the user input value is present in the array then I want to show #TestRegister, and if not, or if the input value is blank or null, show #TestError.
Thanks and appreciate any tips.
var lines;
$(document).ready(function () {
$("#TestRegister").hide();
$("#TestError").hide();
$.get("testcodes.txt", function (data) {
lines = data.split("\n");
});
$("#verify-code").click(function (e) {
e.preventDefault();
if (lines.indexOf($("#test-code").val()) !== -1 && $("#test-code").val().length == 8) {
$("#TestRegister").show();
$("TestError").hide();
} else {
$("#TestRegister").hide();
$("TestError").show();
}
});
});
You can avoid an array loop altogether by creating a regular expression that ensures the test code is found between word boundaries:
var codeRegEx = new RegExp('\\b'+$('#test-code').val()+'\\b');
if(codeRegEx.test(lines)) {
// the testcode is found on a single line, avoiding partial matches
}
Here's a demo:
jsFiddle DEMO
Related
I have a page that loads a random MP3 file on each refresh. The user has to guess a name based on the sound via text form input. I want to check their input against the stored string and refresh the page if it's correct. Otherwise, I wan't to give them an incorrect alert and stay on the same page so they can guess again:
<div class="ui-widget" align="center">
<form method="post" action="" class="answer_box" onsubmit="return submit();">
<p>Which hero is it? <input id="tags" name="guess" /></p>
<script>
var key = <?php echo json_encode($rand_key) ?>;
var info = document.getElementById("guess").value;
function submit() {
if (key==info){
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
</form>
</div>
Right now, it submits the information to a new page regardless of the input. The javascript alerts are also not showing (I suspect they do show, but the page then refreshes and they disappear). The key variable is the key from the randomly taken value of a PHP array, and info should be the text the user inputs.
Problems found:
you cant use submit as a function name a this is an HtmlForm object
document.getElementById("guess").value; is looking for an element with ID of "guess" and that does not exist.
I would rewrite your script like this:
<script>
var key = <?php echo json_encode($rand_key) ?>;
function my_submit(curr) {
var info = curr.guess.value;
if (key == info) {
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
<form onsubmit="return my_submit(this);">
<p>Which hero is it? <input id="tags" name="guess"/></p>
</form>
You have a problem here:
<input id="tags" name="guess" />
Your id is tags, not guess.
You should use document.getElementById("tags").value.
You are trying to retrieve the value of an element with id of "guess." Change this to "tags."
var info = document.getElementById("tags").value;
Also, as #CodeGodie mentioned, you need to change your function name to something other than submit.
Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});
**Below is the input text fileds**
<form:form commandName="DRCNdetails" id="frm1" method="POST" action="addNewDelayReason.do" >
<form:input id="text1" path="delayCategory" cssClass="padR10 boxSizing" maxlength="75"></form:input>
<form:input path="preFix" id="text2" cssClass="padR10 boxSizing" maxlength="6"> </form:input>
<form:input path="reasonValue" maxlength="150" id="reasonValue" cssClass="textbox width100" cssStyle="visibility:hidden"></form:input>
</form:form> <button class="btnStyle blueBtn" onclick="formvalidation(),validateSpecialCharacters()"> <span class="left">
Submit
on submit need to vaidate the id's "text1","text2" fileds , on successful validation should display the below pop up screen that is showLtBox('mask', 'addMisdReasonCode1'), the conditions are below:
should not allow the null values for both the fileds, and special characters,and integers and alert me accordingly , on satisying this criteria only it should display the pop up screen showLtBox('mask', 'addMisdReasonCode1')
As far as I understand the question, you need to create a validation function that would be triggered upon pressing the submit button.
I already see that you have created to function that would be triggered on "OnClick" operation, However the syntax is incorrect.
You need to separate between the two function using ";" and not ","
You need to use only one function for validation - this would be more readable than the code you have written.
The result should be returned to the onclick command.
Example:
change the attribute onclick as follows:
onclick="return FullValidation();"
Create new JavaScript function that includes the two validations and return validation result;
function FullValidation() {
var validationResultOK = formvalidation();
if (validationResultOK) {
validationResultOK = validateSpecialCharacters();
}
if (validationResultOK) {
// Popup alert should be here, I put alert as example.
alert("Out your message here");
}
return validationResultOK;
}
Use Javascript Regular expression..
var pattern = new RegExp(/^[a-zA-Z]{n}$/);
where n is number of charecters you want to accept.
the above regular expression matches only charecters(both cases).
Now retrieve the value from your text fields
var text1 = document.getElementById("#your_id").value;
var text2 = document.getElementById("#your_id").value;
if(pattern.test(text1) && pattern.test(text2))
{
// your popup code
}
<!DOCTYPE html>
<html>
<head>
<title>input number</title>
</head>
<body>
enter no:1<input id="t1" type="text"><br>
<button type="button" onClick="myFunction()">submit</button>
<button type="button" onClick="myFunction()">next</button>
<div id="div1" style="color:#0000FF">
</div>
<script>
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no))
{
alert("Not Numeric");
}
else{
if(no!=1){
if(no%2==0){
no=no/2;
}
if (no%2!=0) {
no=(no*3)+1;
}
}
}
document.getElementById("div1").innerHTML = no;
}
</script>
</body>
</html>
After entering number in the text box when I press submit button it shows the following output
enter no:1
submit next
16
but when i press next button it is not showing any output.My expected output is when I press next button it shoult show the next no. by executing the logic in the myFunction() function.Helpme...
You haven't set any case for when no = 1. You have a case for when no != 1 and when no%2 != 0 both of which are false when no = 1. There isn't any increment logic in here to find the next number and return it. I think you are missing a } at the end of the no%2==0 clause.
Also I fail to see why you have two identical buttons here, next and submit do the same thing. Moreover I would advice more descriptive IDs. div1 isn't a good name for a div.
The javascript part should look like this, if the intention is to implement Collatz conjecture. http://en.wikipedia.org/wiki/Collatz_conjecture
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no)) {
alert("Not Numeric");
} else {
if(no!=1) {
if(no%2==0) {
no=no/2; // Note the division operator instead of mod
} else {
no=(no*3)+1;
}
}
}
document.getElementById("t1").value = no; // Note that we are writing to the textbox
}
There are some basic HTML issues too, in your post you are using the input tag as
<input id="t1" type="text"> use it as: <input id="t1" type="text" />
Secondly, when you submit the data to the function, you are having some value there! Maybe 1 is the value or 16, whatever. But when you are trying to resubmit, either its not allowed or your input is now an empty field. So the function is not executing further than this step:
if(no==""||isNaN(no))
Try to save the value in the form.
Try using this:
document.getElementById("t1").value = no;
Make sure that the value is captured as it was, because your code is changing the value into some other form, use a new variable for this. That would save the value from the input and again write it back to that input.
This will set the value for that text input as it was before the function. It might make the input again ready for the submit!
This is my first message here so I hope that newbies also get help :)
My problem is following:
let's start with code first....
javascript:
$(document).ready(function(){
if ($("input#datum2").val() == "")
{
$().click(function(){
$("input#datum2").val($("input#datum1").val());
});
}
});
html:
<form >
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
What I want this script to do is that first checks if input field datum2 is empty. If yes, than copy value from input#datum1. This action is suppose to happen each time user clicks (anywhere on page?)...
When user types something in datum1 and clicks somewhere than this value is copied to datum2. The problem is when user edits datum1 or datum2, than this value is again copied to datum2. Obviously this condition
if ($("input#datum2").val() == "")
works only once.
I'm new to javascript and jquery so I would appreciate for any help.
Thanks in advance!
Cheers,
Ile
Sounds like you'll need to bind to a different event. Blur occurs when an input loses focus, which sounds like what you're after.
$(function() {
var $datum2 = $('#datum2');
$('#datum1').blur(function() {
if(!$datum2.val())
$datum2.val($(this).val());
});
});
Couple of things:
1) $(function() { ... is a nice shortcut to $(document).ready
2) In JavaScript, an empty string evals to false, so its a nice shortcut.
I see the way round are the order of the click event and "if ($("#datum2",..."
HTML:
<form id="myform">
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
Javascript:
$(document).ready(function(){
$().click(function(){
if ($("#datum2", $("#myform")).val() == "") {
$("#datum2", $("#myform").val($("#datum1", $("#myform")).val());
}
});
});
$(document).ready(function(){
var $datum2 = $('#datum2');
$('#datum2').hover(function() {
if(!$datum2.val())
$datum2.val($('#datum1').val());
});
});