Mapping multiple language data in JavaScript - javascript

guys! I'm still beginner so I have a problem with mapping in JS if I have multiple langauges to map. With react I could to solve it with the useState and useEffect but in this case I don't know what do do...
function report() {
const reportWindow = document.getElementById("reportWindow");
const pageName = window.location.pathname;
const language = document.getElementsByTagName("html");
let codeBlock = "";
for (let i = 0; i < language.length; i++) {
if (language[i].lang === "en") {
codeBlock = `
<div class="report__base" id="myReport">
<span id="close" onclick="showOld()">×</span>
<div class="report__content" id="report01">
<h3>Report page</h3>
<form method="post" action="https://saro.website/report.php" class="report__form">
<input name="language" id="language" value="${language[i].lang}" style="display: none;">
<input name="page" id="page" value="${pageName}" style="display: none;">
<input name="lang" id="lang" value="English" style="display: none;">
<select name="category" id="category" required>
<option value="Bug">Bug</option>
<option value="Page does not work">Page does not work</option>
<option value="Problem with displying">Page displays incorrectly</option>
<option value="other">Other</option></select>
<input type="text" name="other" id="other" class="issue" placeholder="if other, what is it?">
<textarea name="describe" id="describe" cols="30" rows="10" placeholder="Describe your issue or feedback here" required></textarea>
<i>*Additional informations name, email are not requested</i>
<div class="form__label__left">
<input type="text" name="name" id="name" class="issue" placeholder="Name">
<input type="email" name="email" id="email" class="issue" placeholder="Email">
<input type="submit" class="button__black" value="Send">
</form>
</div>
</div>
</div>`;
} else if (language[i].lang === "ja") {
codeBlock = `
<div class="report__base" id="myReport">
<span id="close" onclick="showOld()">×</span>
<div class="report__content" id="report01">
<h3>レポート</h3>
<form method="post" action="https://saro.website/report.php" class="report__form">
<input name="language" id="language" value="${language[i].lang}" style="display: none;">
<input name="page" id="page" value="${pageName}" style="display: none;">
<input name="lang" id="lang" value="Japanese" style="display: none;">
<select name="category" id="category" required>
<option value="Bug">バグ</option>
<option value="Page does not work">ページがうまく動かない</option>
<option value="Problem with displying">指定したページが一致しな</option>
<option value="other">その他</option></select>
<input type="text" name="other" id="other" class="issue" placeholder="「その他」を選んだ方は、内容をご記入下さい?">
<textarea name="describe" id="describe" cols="30" rows="10" required placeholder="発生している状況やフィードバックをご記入下さい"></textarea>
<i>以下の内容をご記入下さい。(任意)</i>
<input type="text" name="name" id="name" class="issue" placeholder="お名前">
<input type="email" name="email" id="email" class="issue" placeholder="メールアドレス">
<input type="submit" class="button__black" value="送信">
</form>
</div>
</div>`;
} else if (language[i].lang === "zh") {
codeBlock = `
<div class="report__base" id="myReport">
<span id="close" onclick="showOld()">×</span>
<div class="report__content" id="report01">
<h3>问题反馈</h3>
<form method="post" action="https://saro.website/report.php" class="report__form">
<input name="language" id="language" value="${language[i].lang}" style="display: none;">
<input name="page" id="page" value="${pageName}" style="display: none;">
<input name="lang" id="lang" value="Chinese" style="display: none;">
<select name="category" id="category" required>
<option value="Bug">问题</option>
<option value="Page does not work">页面 没 有 反应</option>
<option value="Problem with displying">页面 显示 错误</option>
<option value="other">其他</option></select>
<input type="text" name="other" id="other" class="issue" placeholder="如果 是其他问题, 是 什 么?">
<textarea name="describe" id="describe" cols="30" rows="10" required placeholder="在这里描述下 你的 问题 或 反馈 "></textarea>
<i>附加 信息, 不 需要</i>
<input type="text" name="name" id="name" class="issue" placeholder="名字">
<input type="email" name="email" id="email" class="issue" placeholder="邮件">
<input type="submit" class="button__black" value="发送">
</form>
</div>
</div>`;
}
reportWindow.innerHTML = codeBlock;
}
}
There is a code, but I would to love to make it more clear and readable I would like to leave only one codeBlock as a varible and don't multiple it. Somebody could to help me and solve it in JS? ^^" thanks in advance - I would love to expand my knowladge about JS so it would be helpful in my studying this language.

You're in the right way, that code needs to be simplified!
And you're purpose to expand your knowledge is mirable. 😉
JavaScript is perfect for HTML page manipulation. Sometimes you use frameworks or libraries like React or Vue.js, JQuery, Angular to make things cleaner and easier.
There are also libraries which simplify language translation inside our code, like for example I18N.
If you write in plain JavaScript (called Vanilla JS), sometimes you have to write, debug, maintain a lot of code. You should consider to use a framework or at least a library.
In this case I really suggest you to:
avoid to put HTML strings inside JavaScript code, it's not very readable
avoid to duplicate code. You could simplify it for example using a language map like in the example below and then modifying the HTML using classes and ids.
const languageMaps = {
'en': {
'bug': 'Bug',
},
'ja': {
'bug': 'バグ',
},
// ...
};
const language = 'en';
document
.getElementById("bug-option")
.firstChild
.nodeValue = languageMaps[language].bug;
I know it's not that much, but I hope it could help.
Good luck with your study! 😉

Related

How do we concatenate text along with a PayPal field variable?

We are using a standard PayPal Form to collect payments online and have a field for customers to input a pickup date/time, for this we are using the passthrough variable "invoice" per instructions at PayPal Docs everything worked fine this way until we decided for clarification we would also like to pass along the text "PickUpDate" so its makes sense in the email notifications from PayPal. Instead of just Invoice ID 2021-08-30T12:30 We would like it to read Invoice ID PickUpDate:2021-08-30T12:30 We added some JavaScript to get this to work but no success - Any suggestions anyone, hoping for a simple solution somewhere? - Thanks in advance!
Here is an example of the form as we have it now:
<script type="text/javascript">
jQuery(document).ready(function($){
$('input[type="datetime-local"]').change( function() {
$val = 'PickUpDate:' + $(this).val();
$('#invoice').val($val);
});
});
</script>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="margin:0;padding:0;" target="PayPal">
<input type="hidden" name="business" value="paypal#toolcart.com">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="notify_url" value="https://develop.toolcart.com/?notify=1" />
<input type="hidden" name="item_number" value="Toolcart Sale of: Grey Steel 48x72x24 Cabinet">
<input type="hidden" name="item_name" value="Purchase of a Grey Steel 48x72x24 Cabinet">
<div class="text-secondary px-3 form-group">
<label class="col-md-3 control-label" for="date">
<small>Pickup times 9:00a-6:00p (Mon-Sat)</small>
</label>
<div class="col-md-3">
<input id="date" type="datetime-local" name="invoice" min="2021-08-26T09:00" class="form-control-sm" id="invoice" required="">
</div>
</div>
<input type="hidden" name="custom" value="Websale|GrSteel48x72x24Cab|587688|1200.00|Tax|06|72|Total|1272.00">
<div class="text-secondary px-3 form-group">
<label class="col-md-3 control-label" for="selectbasic">
<small>Please select a payment option:</small>
</label>
<div class="col-md-3">
<select id="selectbasic" name="amount" class="form-control-sm">
<option selected="true" value="360">Reservation amount: $360.00</option>
<option value="1272">Full Price: $1,200.00 + 72.00 Tax</option>
</select>
</div>
</div>
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="receiver_email" value="paypal#toolcart.com">
<input type="hidden" name="return" value="https://develop.toolcart.com/pickup">
<input type="hidden" name="no_note" value="1">
<input type="image" src="/wp-content/themes/develop-toolcart-theme/images/paypal.png" class="img-fluid" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
I would just like to prepend the text of PickUpDate: before the type="datetime-local" values and submit it along with the form if at all possible?
I've never used jQuery, try using template literal like this:
I don't know if this will work, just try.
<script type="text/javascript">
jQuery(document).ready(function($){
$('input[type="datetime-local"]').change( function() {
$val = `PickUpDate: ${$(this).val()}`;
$('#invoice').val($val);
});
});
</script>

How to fix "Uncaught ReferenceError: nameCheck is not defined" error?

I am having difficulty getting this to work, everything works except the dependent dropdown, am I doing something wrong?
I am trying to add this to a google sheet script working with a sheet, it all seems to work except the dependent dropdown.
This is the error I'm getting:
Uncaught ReferenceError: nameCheck is not defined
if I test this code on an HTML tester it seems to work correctly, however, it does not seem to work in google sheets.
<html lang="en">
<body>
<h4>Add a Customer</h4>
Select a Date: <input type="date" id="date" name="start" class="mb-3">
<div>
Sales Rep:
<select id="rep">
<option>select option</option>
<option>Neil</option>
<option>Dave</option>
<option>Bob</option>
<option>Trick</option>
</select>
</div>
<div class="add-customer-form">
<div class="form-group">
<label for="first-name">Company name : </label>
<input type="text" class="form-control" id="first-name">
</div>
<div>
Product type:
<select id="input" onchange="nameCheck()">
<option>select option</option>
<option>CASH</option>
<option>Training</option>
<option>Optional Modules</option>
<option>Annual Additional Modules</option>
<option>Hosting Existing user moving Licence</option>
<option>Rentals</option>
<option>Existing Customer - Rentals</option>
<option>Existing Customer - CASH</option>
<option>other</option>
google.script.run.nameCheck();
console.log(input);
</select>
<div>
Product:
<select id="output" onchange="nameCheck()">
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="first-name">Quantity : </label>
<input type="number" class="form-control" id="last-name">
</div>
<div class="form-group mt-3">
<label for="phone-number">Previous CAD : </label>
<input type="text" class="form-control" id="phone-number">
<div class="form-group">
<label for="sales-price">Sales Price : </label>
<input type="number" class="form-control" id="salesP">
</div>
<div class="form-group">
<label for="deposit">Deposit : </label>
<input type="number" class="form-control" id="deposit">
</div>
<div class="form-group">
<label for="install">No. Intallments : </label>
<input type="number" class="form-control" id="install">
</div>
<div class="form-group">
<label for="invoice">Invoice Nr : </label>
<input type="text" class="form-control" id="invoice">
</div>
<div class="form-group">
<label for="Notes">Notes : </label>
<input type="text" class="form-control" id="notes">
</div>
<button class="btn btn-primary" id="add-customer-button">Add Customer</button>
</div>
<div class="alert alert-success invisible mt-3" id="save-success-message" role="alert">
Successfully Added!!
</div>
<script>
function nameCheck(){
var a=document.getElementById("input").value;
console.log(a);
if(a==="CASH")
{
var arr=["Cash 1","cash2"];
}
else if(a==="Existing Customer - CASH")
{
var arr=["existing 1", "existing 2"];
}
else if(a==="Training")
{
var arr=["Level 1 Training (in-house)","Level 2 Training (in-house)","Level 3 Training (in-house)","Onsite Training (up to 4 people)","Training Online per hour","Principles of Design (Renee Mascari)","Graham Hayden Sales/Care","KBBConnect training (per hours)","Training Solus (in-house) - 8 people"];
}
var string="";
for(i=0;i<arr.length;i++)
{
string=string+"<option value="+arr[i]+">"+arr[i]+"</option>";
}
document.getElementById("output").innerHTML=string;
}
</script>
</body>
</html>
Screenshot off dialog:
The code in the question have several issues, i.e.:
Bad HTML
Remove google.script.run.nameCheck(); and console.log(input); from
<select id="input" onchange="nameCheck()">
<option>select option</option>
<option>CASH</option>
<option>Training</option>
<option>Optional Modules</option>
<option>Annual Additional Modules</option>
<option>Hosting Existing user moving Licence</option>
<option>Rentals</option>
<option>Existing Customer - Rentals</option>
<option>Existing Customer - CASH</option>
<option>other</option>
google.script.run.nameCheck();
console.log(input);
</select>
The above because JavaScript can't be included that way between HTML tags.
Use of HTML attributes for handling events.
Instead of
<select id="input" onchange="nameCheck()">
Use
<select id="input">
then between <script></script> use something like
document.getElementById('input').onchange = nameCheck;
or use addEventListener
Related
HTML form submits twice if the onsubmit function runs longer than 10 seconds

Javascript default shipping address equal to billing address on page load, works in jsfiddle, but not in browser?

I recognize that similar questions have been asked before, but none of them seem to fix my problem. I'm trying to get the default setting be where the shipping address is equal to the billing address with a check box pre-checked. Upon clicking the checkbox a section of the form appears and the previously hidden form values/input text is cleared so that the user can enter in separate billing information. I've got it all working in jsfiddle, but can't for the life of me get it working in the browser. Any help would be appreciated.
ps. sorry for the wonky formatting, I can't figure out how to elegantly paste code while following the formatting guidelines.
<form name="checkout" method="post" id="payment-form" action="/templates/dropindemo.php">
<section id="shipping">
<h2>Shipping</h2>
<label for="first">First name</label>
<input type="text" autocomplete="given-name" placeholder="Hermionie" name="fname" id="first">
<label for="last">Last name</label>
<input type="text" autocomplete="family-name" placeholder="Granger" name="lname" id="last">
<br>
<label for="address">Address</label>
<input type="text" autocomplete="street-address" placeholder="12 Grimmauld Place" name="address" id="address">
<label for="city">City</label>
<input type="text" autocomplete="address-level2" placeholder="London" name="city" id="city">
<br>
<label for="state">State</label>
<input type="text" autocomplete="address-level1" placeholder="Greater London" name="state" id="state">
<label for="zip">Postal Code</label>
<input type="number" pattern="\d*" autocomplete="postal-code" placeholder="WC1N1 9LX" name="zip" id="zip">
<label for="country">Country</label>
<select name="country" id="country">
<option selected hidden disabled value="">United Kingdom</option>
<option value="USA">United States</option>
</select>
<br>
<label for="last">E-mail</label>
<input type="email" autocomplete="email" placeholder="hermionie#spew.org" name="email" id="email">
<br>
<input type="checkbox" onclick="onPageLoad()" id="shiptobill" />
<label for="shiptobill">My shipping and billing info are the same</label>
</section>
<section id="billing">
<h2>Billing</h2>
<label for="first">First name</label>
<input type="text" autocomplete="given-name" placeholder="Harry" name="bfname" id="bfirst">
<label for="last">Last name</label>
<input type="text" autocomplete="family-name" placeholder="Potter" name="blname" id="last">
<br>
<label for="address">Address</label>
<input type="text" autocomplete="street-address" placeholder="4 Private Drive" name="baddress" id="address">
<label for="city">City</label>
<input type="text" autocomplete="address-level2" placeholder="Little Winging" name="bcity" id="city">
<br>
<label for="state">State</label>
<input type="text" autocomplete="address-level1" placeholder="Surrey" name="bstate" id="state">
<label for="zip">Postal Code</label>
<input type="number" pattern="\d*" autocomplete="postal-code" placeholder="RG12 9FG" name="bzip" id="zip">
<label for="country">Country</label>
<select name="bcountry" id="country">
<option selected hidden disabled value="">United Kingdom</option>
<option name="USA" value="USA">United States</option>
</select>
<br>
</section>
</form>
And the javascript...
window.onload = toggle(), onPageLoad();
function toggle() {
if (document.getElementById("shiptobill").checked == true) {
document.getElementById("shiptobill").checked = false;
} else {
document.getElementById("shiptobill").checked = true;
}
};
function onPageLoad() {
var inputs =
document.getElementById("shipping").getElementsByTagName("input");
var mirror =
document.getElementById("billing").getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (document.getElementById("shiptobill").checked === true) {
var att = inputs[i].getAttribute("name");
inputs[i].setAttribute('onkeyup', 'document.checkout.b' + att + '.value=this.value');
document.getElementById('billing').style.display = ""; //would normally be set to "none" in production
} else {
document.getElementById('billing').style.display = "block";
inputs[i].setAttribute('onkeyup', "");
mirror[i].value = "";
}
}
};
window.onload = toggle(), onPageLoad();
means…
Immediately execute toggle
Assign the return value of toggle to onload
toggle has no return statement so it returns undefined
onload expects to be assigned a function, not undefined
Immediately execte onPageLoad
You are almost certainly running into getElementById failing because the element doesn't exist yet. If you looked at the Console of the Developer Tools in your browser, this would probably be obvious. It is really important to look at the error messages your browser gives you.
If you want to call toggle and onPageLoad when the load event fires by assigning something to onload, then you need to assign a function.
function run_on_load() {
toggle();
onPageLoad();
}
window.onload = run_on_load; // No ()! They would *call* the function.
Modern JS uses addEventListener, so you could instead:
addEventListener("load", toggle);
addEventListener("load", onPageLoad);

Conditionally change form action in JSP based on combo box selection

I am have three servers in three different domains. For example,
google.com
oracle.com
sap.com
I have a combo box with the same values as above. How can I change the form action to change to respective site once it is selected in the combo box?
Here is the code i have tried.
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#serverName").on("change",function(){
alert($(this).val());
if($(this).val().toString===("google"))
$("#dataform").attr('action',"http://google.com");
if($(this).val().toString===("oracle"))
$("#dataform").attr("action","http://oracle.com");
if($(this).val().toString===("sap"))
$("#dataform").attr("action","http://sap.com");
});
});
</script>
My form is like :
<form action="anyaction" name="dataform" method="post" >
<img src="logo.png"><br/>
<label for="email" class="boldtext">Triggered By</label><br>
<input type="text" id="email" name="email" placeholder="Enter your mail id"
required><br/>
<label for="serverName" class="`boldtext`">Server Name</label>
<select id="serverName" name="serverName" >
<option value="selectServer">Select the Server</option>
<option value="google">Google</option>
<option value="oracle" >Oracle</option>
<option value="sap">SAP</option>
</select><br/>
<label for="Clients" name= "Clients"
class="boldtext">Clients</label><br>
<input type="text" id="count" name="count"
placeholder="Enter No Of clients" required>
<br/>
<label for="items" name="items" id="items"
class="boldtext">Items</label>
<textarea id="items" name="items" required rows="3"> </textarea><br/>
<button type="submit">Submit</button>
</form>
Looks like there is some value represented by the name for the form i used "dataform".
Once i change it to dataform123 it worked. also the comparison i have changed from tostring.equals to == / === both of them worked.
Thanks for being there to keep me trying !!

html/javascript - Trying to validate the form

I did a website and made a form ,and I have done the most of the validation but I am stuck at one. what I am trying to achieve here is when the the submit button of the form is clicked, a alert message show appear on screen saying thanks'customer name' for feed back and you chose 'radiobutton' and your comment was 'textincommentfield'.for one or another reason validation is not working. Any help would be great and thanks in advance , btw I am new to this.
Code: http://jsfiddle.net/92tSw/
HTML:
<title> Contact</title>
<body>
<div class="container">
<div id="wrap">
<div id="logo">
<img class="p" src="images/logo.png" align="left">
</div>
<img class="d" src="images/title.gif" align="middle">
<div id="menu">
<div id="menu2">
<ul>
<li><a href="homepage.html" ><span>Home</span></a></li>
<li><a href="about.html" ><span>About Us</span></a></li>
<li><a href="clubs.html" ><span>Clubs</span></a></li>
<li><a href="shop.html" ><span>Shop</span></a></li>
<li><a href="contact.html" ><span>Contact Us</span></a></li>
</ul>
</div>
</div>
<form>
<fieldset>
<legend style="font-size:20px; padding-top:20px;">Fill in the form Below to contact Us:</legend>
<p><label for="full name">Full Name:</label>
<input id="full name" type="text" size="40" name="customername" placeholder="Type first and last name" autofocus/></p>
<p><label for="Address">Address:</label>
<input type="text" name="address1" placeholder="Address Line 1" size="42%">
<input type="text" name="address2" placeholder="Address Line 2" size="42%">
<p><label for="Address"> </label>
<input type="text" name="city" placeholder="City/Town" size="20%">
<input type="text" name="postcode" placeholder="Post Code" size="20%"></p>
<p><label for="Telephone No.">Telephone Number:</label>
<input type="text" name="Telephone No." maxlenght="12"placeholder=" Enter Telephone No." size="42%"></p>
<p><label for="email">Email:</label>
<input name="email" type="email" size="25" placeholder="youremail#you.com" /></p>
<legend style="font-size:20px;" >Comments</legend>
<p><label for="quantity"> How great is the website?Choose one<em>*</em> :</label>
<input type="radio" name="myRadio" value="VG" >Very Great
<input type="radio" name="myRadio" value="G" >Great
<input type="radio" name="myRadio" value="NVG">Not Very Great
<input type="radio" name="myRadio" value="U" >Useless
<BR>
<BR>
<BR>
<BR>
<p><label for="comment">Your Message:</label>
<textarea cols="35" rows="5" name="comments" Placeholder="eg. please knock on the dooor, ring the bell etc." >
</textarea></p>
</fieldset>
<fieldset>
<input type="checkbox" name="Terms and Condition"value="Terms and Condition" required> Accept Terms and Condition<br>
<input id="bor" type="reset" value="Reset">
<input id="chor" type="submit" name="button" value="Submit" onclick="getMyForm(this.form)" >
</fieldset>
</div>
</div>
CSS:
form{ padding-top:100px; color:White;}
fieldset { background-color:#980000 ; margin: 1%;}
label { float:left; width:20%; text-align:right;}
legend{font-weight:bold;}
.foot {
padding-top:.75pt;
padding-bottom:.75pt;
padding-right:auto;
padding-left:auto;
width:100%;
}
JS:
function getMyForm(frm)
{
var myinfo = getRadioValue(frm.myRadio);
var customername = document.getElementById("customer").value;
var comment = document.getElementById("comment").value;
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
}
function getRadioValue(radioArray){
var i;
for (i = 0; i < radioArray.length; i++){
if (radioArray[i].checked) return radioArray[i].value;}
return "";
}
It may be better to have the event on the form
<form id="form1" onsubmit="return getMyForm(this)">
To prevent the form from actually submitting, you have to return false; from the javascript method.
To submit the form programmatically in JS
frm.submit();
Or
document.getElementById("form1").submit();
Then return true; from the function under the right conditions to allow the submit to complete.
(I noticed you didn't include the action and method attributes on the form. I assumed this was just for the example.)
http://jsfiddle.net/92tSw/2/
Use JQuery if you are new to javascript.. its much more comfortable:
$(document).ready(function() {
$("#yourmockform").submit(function(e) {
var customername = $(this).find('#fullname').val();
var comment = $(this).find('#comment').val();
var myinfo = $(this).find('[name="myRadio"]:checked').attr('value');
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
return false;
});
});

Categories