Javascript replacement of the characters . with , - javascript

I am trying to make a simple replacement in a javascript form.
The form is submitting invoicenumber and amount to external payment gateway. The problem is the payment gateway doesn't accept , (comma) as seperator between the integer and fraction parts (ie. dollar,cent) but only (dollar.cent).
I want to make sure it accepts both characters . (dot) AND , (comma) so customer can use both and the form will just send . to external server.
UPDATE:
This is current javascript code:
`
function startPayment() {
var objForm = document.getElementById("ePay");
if (objForm.merchantnumber.value.length < 7) {
alert("Please enter your merchant!");
return false;
}
paymentwindow = new PaymentWindow({
'windowstate': 1,
'paymentcollection': 1,
'language': 1,
'merchantnumber': objForm.merchantnumber.value,
'amount': objForm.amount.value * "100",
'currency': "208",
'orderid': objForm.orderid.value,
});
paymentwindow.open();
}
function init() {
var sURL = String(window.location);
var arrURL = sURL.split("/");
var sAcceptURL = "";
var objForm = document.getElementById("ePay");
var n;
for (n = 0; n < arrURL.length - 1; n++)
sAcceptURL += arrURL[n] + "/";
objForm.cancelurl.value = sURL;
objForm.accepturl.value = sAcceptURL + "accept.html";
}
</script>`
This is the HTML code:
<tr>
<td>Amount:</td>
<td>
<input type="text" name="amount" value="" style="width: 200px;" />
</td>
<td>
Amount to pay
</td>

The solution to this would be either to replace the ',' with a '.' if that's what you're looking to do:
amount.replace(/,/g, '.');
What this line will do is use RegExp to find the occurrence of ',' and replace it with '.'. However, because you are creating a secure form to the back end, some recommended practices are to parse it at the back end first and confirm that there is no trace of things like SQL injection and make sure all input is valid. For example, if you are only looking to accept numbers and '.' in your input, I would use:
var rxCheck = /[0-9\.]*/g;
if (!rxCheck.test(amount)) {
// TODO: .. code if the input is invalid ..
}
Good luck in your search!

You can try this:
objForm.amount.value.split(",").join(".");
Or this:
objForm.amount.value.replace( /,/g, "." )
Beware: if your code is going to run in more cultures, you should handle this another way.

Related

Why request to server parameter 'occupation=01%02' is work normally but 'occupation=01%2C02' or 'occupation=01&occupation=02' is get error?

When using the API, the parameter requested to the server does not work properly.
'occupation=01%02' works fine (change url directly in internet browser), but it throws an error when 'occupation=01%2C02'(,) or 'occupation=01&occupation=02'.
This error occurs when requesting to the server with multiple values ​​from the checkbox.
What is the problem?
Is it an encoding problem?
If I'm wrong, where would I go wrong?
I used html5 client and receive 10 from the server and paging them
in java:
uri = new URIBuilder()
.setScheme("http")
.setHost("openapi.work.go.kr")
.setPath("/opi/opi/opia/wantedApi.do")
.setParameter("returnType", "xml")
.setParameter("startPage", requestVo.getStartPage())
.setParameter("callTp", "L")
.setParameter("region", "30200")
.setParameter("occupation", requestVo.getOccupation())
.setParameter("keyword", requestVo.getKeyword())
.setParameter("authKey", requestVo.getKey())
.build();
in jsp
:checkbox id is occupation_chbox and I put the value in
<input type="hidden" name="startPage" value="1">
using js
function jobsubmit(){
var form = document.getElementById("requestForm")
var occ = checkOcc();
$("#occupation").val(occ);
console.log($("#occupation").val());
form.submit();
}
function checkOcc(){
var chk_arr = [];
$("input[id='occupation_chbox']:checked").each(function(){
var chkBox = $(this).val();
chk_arr.push(chkBox);
})
console.log(chk_arr);
var occ="";
for(i = 0; i<chk_arr.length; i++){
occ += (i < chk_arr.length - 1) ? chk_arr[i] + "," : chk_arr[i]
}
console.log(occ);
return occ;
}
I solved this problem by changing the delimiter from ',' to '|'.
occ += (i < chk_arr.length - 1) ? chk_arr[i] + "|" : chk_arr[i]

Dynamic Filter of Iframe with Two Input Fields

I'm attempting to make a dynamic filter on one iframe with two input boxes. Let's call the input boxes "Box 1" and "Box 2". When both boxes are not populated, I would like the iframe to display all of the information. When Box A is populated, I want it to display information on Box A. When Box B is populated as well, I would like both the filters to apply. When only Box B is populated, I would like the iframe to only display Box B's input.
One limitation I have is the changing nature of having one of the input boxes blank. I am limited to assigning a number to the input on the URL (e.g. - col1, op1, val1). If the "salModBox" is blank for instance, it needs to be dynamic enough to assign "serNumPrefBox" with col1, op1, val1). If both are populated, it would need to be col1, op1, val1 for "salModBox" and col2, op2, val2 for "serNumPrefBox". If neither are populated, well, it doesn't need to have col1 or 2 for that matter.
Expected output of the URL would ultimately look like this if both are populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod+"&col2=Variable%20Number%20Two&op2=EQ&val2="+serNoPre+"#/moreinfo/anotherID
Expected output of the URL with one variable populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod (or serNoPre) +"#/moreinfo/anotherID
With both of them blank, it would simply be the original URL source link. This would be a wide open search. A user isn't technically limited to values they can put in either input box.
function salModSnpFilter() {
var salModInput = document.getElementById('salModBox').value;
var serNumPrefInput = document.getElementById('serNumPrefBox').value;
var smSnp = '';
if (salModInput = ' ' and serNumPrefInput = ' ') {"https://en.wikipedia.org/wiki/IFrame"
} else if (salModInput = ' ' and serNumPrefInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput
} else if (serNumPrefInput = ' ' and salModInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + salModInput
} else if (salModInput != ' ' and serNumPrefInput != ' ' {"chttps://en.wikipedia.org/wiki/IFrame"+salModInput+serNumPrefInput
} else {"https://en.wikipedia.org/wiki/IFrame"
}
var salModString = "https://en.wikipedia.org/wiki/IFrame" + salModInput";
var serNumPrefString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput";
var bothString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput + salModInput";
document.getElementById('SM_SNPiFrame').src = salModString;
document.getElementById('SM_SNPiFrame').src = serNumPrefString;
document.getElementById('SM_SNPiFrame').src = bothString;
}
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name = "Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame"
width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
I ultimately used this code and it worked:
function filterSelection() {
var smBoxValue = document.getElementById("salModBox").value;
var snpBoxValue = document.getElementById("serNumPrefBox").value;
if (smBoxValue != "" && snpBoxValue != "") {var combinedModString =
"https://example.com/col1=Serial%20Number%20Prefix&op1=EQ&val1=" +
snpBoxValue +"&col2=Sales%20Model%20BOM%20EDS&op2=EQ&val2=" +
smBoxValue";
document.getElementById('SM_SNPiFrame').src = combinedModString;
}
else if (smBoxValue == "" && snpBoxValue != "") {var snpModString =
"https://example.com/#/col1=Serial%20Number%20Prefix&op1=EQ&val1="
+ snpBoxValue;
document.getElementById('SM_SNPiFrame').src = snpModString;
}
else if (smBoxValue != "" && snpBoxValue == "") {var salModString =
"https://example/col1=Sales%20Model%20BOM%20EDS&op1=EQ&val1=" +
smBoxValue;
document.getElementById('SM_SNPiFrame').src = salModString;
}
else {document.getElementById('SM_SNPiFrame').src =
"https://example.com/";
}
}
Your code seems a bit complex than what your issue is, I'll explain to you how to correct this and use some good practices in JavaScript.
Since you need to handle the values inside the input tags and use them into the iFrame tag, we will do the following:
Global elements first.
Since we will probably need to define only once which DOM element is the iFrame tag and which ones are the input tags, lets have them at the very beginning:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
Also, we define a strings variable that will help us store the input values in the same index as elements array.
Set event listeners for every element.
After defining which elements we want to use, now we should handle the change of its value. The most fast-looking effect is to use keyup event, this will pass the value everytime that the user types:
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
In this event listener, you need to setup what will happen every time this event is fired. I just did a simple function to store the new value into the same index but in different array (strings array).
And after that done, call the function that will update the iFrame tag.
Keep your code simple and functional.
The function salModSnpFilter() doesn't need a lot of if statements and the same string appearing multiple times to handle the new source of the iFrame. Lets keep code simple:
const salModSnpFilter = () => {
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/"; //You can set it to empty: "" if you dont want slashes.
strings.forEach(string => {
if (string !== "") {
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
We define the base URL in a variable at the top and a variable that will hold the string that we will append to the base source.
We iterate over the strings array and add this string to finalString array in the same order of the inputs.
After this, the only thing left to do is to set the source of the iFrame tag.
Final code:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
const salModSnpFilter = () =>{
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/";//You can set it to empty: "" if you dont want slashes.
strings.forEach(string=>{
if(string !== ""){
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name="Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame" width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
Note: The order of the strings and how they are used on the iFrame are the same as the order you added the inputs to the elements array. This means, inputA value will always go before inputB value. Unless you change the order in the elements array.

How to Properly Add Double Quotes to a Textarea

I need a textarea to include a set of double quotes at the start and end of the textarea value. The below code works in that double quotes are added to the start and end of the field, but if the user enters text and then goes back to the field, multiple double quote sets can be added. How can I prevent this? A jQuery solution is also acceptable.
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea>
function quotes(){
var quoteValueBefore = document.getElementById("quoteName").value;
var ensureQuotes = "\"" + quoteValueBefore + "\"";
document.getElementById("quoteName").value = ensureQuotes;
}
Check to see if the text already begins with a quote, and if it already ends with one. If either is missing, add it.
Also check that the length >= 2, otherwise " would pass the test (ends with a quote? check. begins with a quote? check.)
function quotes() {
var quoteValue = document.getElementById("quoteName").value;
if (!quoteValue.match(/^"/))
quoteValue = '"' + quoteValue;
if (!quoteValue.match(/"$/))
quoteValue += '"';
if (quoteValue.length < 2)
quoteValue += '"';
document.getElementById("quoteName").value = quoteValue;
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea>
function checkQuotes(id) {
str = document.getElementById(id).value;
if (str[0] != '"') {
str = '"'.concat(str);
}
if (str[str.length - 1] != '"') {
str = str.concat('"')
}
return str
}
function quotes() {
withQuotes = checkQuotes("quoteName");
document.getElementById("quoteName").value = withQuotes
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onchange="quotes()">testing the quotes feature</textarea>
This snippet will check if the first character is a quote, if it isn't it will prepend it. It also checks if the last character is a quote, if it isn't it will append it. This probably isn't the most friendly UI solution, and I recommend either adding this through CSS if you're using it for display purposes, or using PHP or whatever you're doing for the backend form submission.

Add line break to HTML from Js loop

I have a simple Js function that generates a list of random numbers based on how many the user wants. The function works fine, and logs fine, but it isn't displaying like I'd like it to. I'm new to Javascript, so I tried using the \n escape character, but it didn't do anything. Any help would be appreciated.
function generateIDs()
{
var num = document.getElementById('numberToGenerate').value;
var par = document.getElementById('numbers');
var button = document.getElementById('genButton');
button.disabled = true;
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id;
}
<form>
Auto-Generate <input type="text" name="number" id="numberToGenerate"/> IDs.
<button type="button" onclick="generateIDs()" id="genButton">Go!</button>
</form>
<p id="numbers">
</p>
\n doesn't mean much to a browser; use <br/> instead.
Example:
// snip
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id.toString() + '<br/>';
}
//snip
Note that this is going to overwrite the previous value on each iteration. You probably want this:
par.innerHTML += id.toString() + '<br/>';

Get array of values from multiple inputs using jQuery

Can someone please let me know how to get values from several input fields?
I have a list with several inputs like this:
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
I have a solution in Javascript (on form submit):
...
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
}
How do I do the same thing in JQuery?
It's not valid to have two inputs of the same name. If you want to do this, you can use <input name="titles[]">
You can try this:
<input name="titles[]">
<input name="titles[]">
​<button>submit</button>​​​​​​​​​​​​​​​​​​​​​​​
With this jQuery
// click handler
function onClick(event) {
var titles = $('input[name^=titles]').map(function(idx, elem) {
return $(elem).val();
}).get();
console.log(titles);
event.preventDefault();
}
// attach button click listener on dom ready
$(function() {
$('button').click(onClick);
});
See it working here on jsFiddle
EDIT
This answer gives you the titles in an array instead of a string using a | separator. Personally, I think this is a lot more usable.
If you're just submitting the form and you want to support multiple values, use the .serialize method as described in the other answer
Use jQuery's native serialize function:
var data = $('input[name="additionaltitlename"]').serialize();
docs
The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements.
It is very easy in jquery. you can do this as:
types = [];
$("input[name='additionaltitlename']").each(function() {
types.push($(this).val());
});
console.log(types);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="additionaltitlename1" name="additionaltitlename" class="form-control" value="abc">
<input type="text" id="additionaltitlename2" name="additionaltitlename" class="form-control" value="xyz">
In addition to #gdoron's or #macek's answer which are probably the way to go, I'd like to add that all that is wrong with the code you have posted is that you have one } too much. This works (although it still has room for improvement):
$('#getpreviewbutton').click(function(){
var extratitles = document.getElementsByName('additionaltitlename');
var str = '';
for (var i = 0; i < extratitles.length; i++) {
str = str + '|' + extratitles.item(i).value;
}
});​
See: http://jsfiddle.net/8XJcc/
I don't know which browser you are using but using sth like Firebug or the Chrome Dev Tools can be pretty handy to spot simple mistakes like this. See this reference for Chrome or this one for Firefox. Even IE has one - just press F12.
Means:
str = '';
$("input[type='text']").each(function() {
str = str + '|' + $(this).val();
});
or
str = '';
$("input[name='additionaltitlename']").each(function() {
str = str + '|' + $(this).val();
});
?

Categories

Resources