Having difficulty validating textarea input - javascript

I have a form with the target="_blank", and onsubmit="return validateForm()", as well as a textarea named "wordList". Here is my validateForm() function
function validateForm() {
var x = document.forms["form1"]["wordList"].value;
if (x == null || x == "") {
alert("Word list cannot be empty.");
return false;
}
}
This works fine to test for an empty input, however I need to also verify that the wordList has a minimum number of lines of text. I have tried inserting a php block after this if statement, but by calling 'explode()', it ends up opening a new tab regardless of if there is input or not. Here's what I mean:
function validateForm() {
var x = document.forms["form1"]["wordList"].value;
if (x == null || x == "") {
alert("Word list cannot be empty.");
return false;
}
<?php
$wordInput = explode("\n", str_replace("\r", "", $_POST['wordList']));
?>
}
I'm not sure how to reference the wordList in the php block when it's on the same page, but either way, whenever I click a submit button, even with an empty textarea, it opens the current page in another tab.
Is there a better way than using php to count and validate the number of lines in the text area?

It is because php code executes at server side not client side, so you need to write javascript alternative code instead of php code ...
Here regardless of what you write in php code it won't return true or false and you want get wordList ... so it will submit the form from the client side

var text = $("#wordList").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length;
console.log(count); // Outputs 4
Use it in you if condition to check countLines more than 2
var text = $("#wordList").val();
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length;
console.log(count); // Outputs 4
var countLines = document.getElementById("wordList").rows;
Codepen URL for reference - http://codepen.io/nagasai/pen/gMrpre

You have to use JavaScript for this purpose. You need to find out how many linebreaks the textarea have. Here a reference to a similiar question.
enteredText = textareaVariableName.val();
numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
Then you have to prevent the action caused by pressing the submit button with JS if the number of linebreaks doesnt match your criteria.
Here a question for handling this.

Related

How can I modify my <textarea> html value based on user input

I have a html textarea element in my page where user gives comma separate values. for example below.
A-48402,AA,SBAFL,AA+,USD,,
From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below
var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');
Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.
row_values.push('Y');
It is reflecting in debugger.
But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit. How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?
String Data = request.getParameter('mbs_inst_data');
This data is populated with the same blank values.
If you're only checking for the last row then the only case that would happen is when it's ,,
so you can just do a simple check
let data = 'A-48402,AA,SBAFL,AA+,USD,,'
data = data.split(',')
let lastRowIsBlank = data[data.length-2] === ""
// we are doing length - 2 because in your situation we have 2 ""
// since you have two commas. If you have only 1 comma we would
// the same steps but with length - 1
if(lastRowIsBlank) data[data.length-2] = "Y"
return data.toString()
You can use it like this.
<p id="demo">Visit Microsoft! ,,</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/,,$/, ',Y');
document.getElementById("demo").innerHTML = res;
}
</script>
Output
Visit Microsoft! ,Y
I guess this would help you.

Javascript Math.log() help wanted

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

jquery hide/show or condiiton failing

Is there anything wrong with the jQuery/JS below? I have an input field aAmt which on change calls below. ${dAmt} = "10000" from DB. It basically converts the number to $ format(eg.. 23 to $23.00) and focuses the value to the input field. Issue is the if loop (if(aAmt >= a_amount)...) fails.
Even if the condition fails it goes to if loops and shows the div which should not happen. I don't see any error in developers console.
$('#aAmt').change(function() {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
curFormat(aAmt);
if(aAmt >= a_amount)
{
$("#dsDiv").show();
}else{
$("#dsDiv").hide();
}
});
function curFormat(aAmt)
{
var nAmt = Number(aAmt.replace(/[^0-9\.]+/g,""));
var fAmt = '$' + nAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
document.getElementById("aAmt").value = fAmt;
}
Have you tried to convert a_amount to an int, to be sure to compare two integers together:
var a_amount = parseInt("${dAmt}");

Need to get indexes from array and output them to user in JavaScript

We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;

How to validate textbox

i have problem with my program. what i want is to validate the textbox if it is equal to data that i get from my database. if it's equal then set focus if not the textbox should be null and and will not able to enter. this is my sample code.Any help is very much appreciated. Thank you.
function sequence(varid) {
var a = varid.indexOf("/")
var b = varid.slice(0, a);
b = parseInt(b)
c = (b + 1)
var f = varid.slice(a);
if (window.event.keyCode == 13 || window.event.keyCode == 10) {
var lot_number = document.getElementsByName("lot_number")[b].value;
var lot_number_scan = document.getElementsByName("lot_number_scan")[b].value;
var counting = document.getElementsByName("lot_number_scan");
counting = counting.length;
var newid = c + f
if (c == counting) {
document.getElementById("issued_by").focus();
} else {
lot_number_scan = lot_number_scan.replace(/(LO)/g, "-LO");
lot_number_scan = lot_number_scan.replace(/-/, "");
var check = (new RegExp(lot_number_scan, "gi").test(lot_number));
if (check == true) {
document.getElementById(newid).focus();
} else {
document.getElementsByName("lot_number_scan")[b].value = '';
document.getElementsByName("lot_number_scan").focus();
}
document.getElementById(newid).focus();
}
}
}
</script>
sorry for late reply.. what happen when i run that codes is, still enter though the entered data is not equal or not the same with the other data sorry if I'm not good in explanation i will give sample hope this can help.
Data from database Texbox
123456828 123456828
152685689 123456828
Save Button
Data from database is just a display data that i post after filtering the sequence of data.
Textbox I scan barcode to input data.
If the entered data in the textbox is matches to the display data it automatically enter the second textbox and ready to scan again Im ok with that, What i want to happen is when the entered data is not match is should not enter to the second textbox or save button also when it enter wrong data it should automatically erase the wrong entered data and ask for correct one. hope you can understand what i want to happen I'm new in coding and self study so your help is very much needed and thank you s much..
I think you can use jquery and in that case you can check it and set value in it with different jquery selectors.
For Example:
$('input[type=text][id="textfieldId"]').val('myValueToBeSet');
Hope this might help you.

Categories