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.
Related
I have a String having URL like:
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
I am getting quantity on button click from input as well like:
var qty = jQuery(this).siblings('.quantity-field').val(); // 4
How can I change this qty in URL String "/qty/3/" to "/qty/4/" on every time I get new value from input on button click?
I can't simply find and replace because i don't know /qty/3 exact number its dynamic it could be 2,3,4,5 etc
here is function for having this functionality
function changeValue(str,value){
return str.replace(/\/qty\/[0-9]+\//,`\/qty\/${value}\/`)
}
console.log(url,4);
You can use replace method.
capture everything up to /qty in group 1 (g1), all the following digits in group 2 (g2), and remaining in group 3 (g3), in callback change value of group 2 as required.
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
let desired = url.replace(/^(.*\/qty\/)(\d+)(.*)$/g, function(match,g1,g2,g3){
return g1+ (Number(g2)+1) + g3
})
console.log(desired)
I need to change the color of some word for each row Table
I have a table for wordInput that's mean contains the word that I need to color them and the second Table contain Titles that I need to color some words for it.
My script work when the number of row title equal to the number of
the row wordInput and That's wrong! because sometimes I have only 1
row as an input. I need to find solution to how can do the loop for
each row Title I got errors evaluating script when I need to
change the color of the second-row Title
TypeError: Cannot call method "split" of null (#4)
this error because now we ARE in the second Row InputWords and it NULL without Value
var row = {
"Title": ["This reference is to serve as a useful","Title2","Title3"],"wordInput":["serve"] }
//Title contains 3 rows : as string Values
//wordInput contains words that i need to color them in Title :As a string Value
var words = row["wordInput"];// this contain only 1 row ["serve"]
var orgTitle = row["Title"];
words.split(" ").forEach(function (word) {
orgTitle = orgTitle.replace(new RegExp(word, "g"),'<span style="color: red;">'+word+'</span>');
});
orgTitle;
I'm looking for your help thanks
Assuming row.title is the array that contains all the words that should be highlighted, this is what you need.
var row = {
"Abstract": "This reference is to serve as a useful reference for testing whether the styling of reference, works or not. All occurances of 'reference' should be given a color of red.",
"Title":["reference" ,"testing"]
};
var wordsToHighlight = row['Title'];
var result = row["Abstract"];
wordsToHighlight.forEach(function (word) {
result = result.replace(new RegExp(word, "g"),'<span style="color: red;">'+word+'</span>');
});
document.querySelector("#result").innerHTML = result;
<div id="result">
</div>
We have a front end form where users enter the below feed. I would need to validate the text, display a popup if there is a word "Y" instead of "X" after the first ":" and clear the row which has Y in it.
20170731_5412_1234:X:Hello:P:James::999999999
20170731_5412_5678:X:Gopal::Varma::999999999
20170731_5412_1234:X:Steve:H:Benton::999999999
20170731_5412_2321:Y:Varme::Dost::999999999
For example:
In the above feed the 4th line has "Y" after the first column. I need to display a popup stating the user Varme has Y and it will be cleared. The validation should be performed on multiple rows.
Try something like this, where you split your text result first on the newline character ("\n") and then by colons:
var input,
cwidRows,
results,
i;
// divide input string into an array of strings representing each line
input = stringFromTextArea;
cwidRows = input.split("\n");
// put acceptable results into results array for later use
results = [];
for (i = 0; i < cwidRows; i++) {
if (cwidRows[i].split(":")[1] !== "Y") results.push(cwidRows[i]);
}
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.
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.