How to avoid HTML javascript string spacing come with (+) sign? - javascript

I have create a html form with javascript that must run at IE to trigger outlook by using mailto action, but for the string I pass to outlook, all the spacing auto replace by (+) sign. Below is my code:
<script>
var i= 'Product name:';
var idproduct=i.split('+').join(' ')
function beforeSubmit() {
var Product = document.getElementById("Product_Name");
var Email = document.getElementById("Email_Address");
var body = document.getElementById("body");
body.value = idproduct+ Product.value +"\n";
}
</script>
<input name="Subject" size="78" id="Subject" type="hidden" value=" Car Notification" /><br/>
But the output I get is :
Subject the email:
Car+Notification
Body of the email:
Product+name:Honda
My expected output is without all the plus sign for the spacing.Anyone have ideas in this issue?

We could write the mailto link like this to avoid the "+" symbol: mailto:somebody?subject=etc&body=etc. We send the subject and body as query parameters. You could check the example below, it works in IE:
function beforeSubmit() {
var Product = document.getElementById("Product_Name").value;
var Email = document.getElementById("Email_Address").value;
var eTo = encodeURI(Email);
var eSubj = encodeURI("Car Notification");
var eBody = encodeURI(Product + "\n" + "anotherline");
var email = "mailto:" + eTo + "?subject=" + eSubj + "&body=" + eBody;
document.getElementById("myform").href = email;
}
<form>
<input id="Email_Address" type="text" value="somebody#example.com" />
<input id="Product_Name" type="text" value="enter your message here" />
<input type="button" value="submit" />
</form>

Related

How do I target specific inputs on a form fields to change output to Title Case?

On my form I am trying to have specific output fields and their strings output as Title Case. May be worth noting, this form outputs to results on the same page. Here's a Fiddle demo of my form.
As you can see from it I have 3 input categories Name, City and Words, for this example I am trying to implement the Title Case script to just the 'Name" and City" output strings without it effecting the "Words" category. As I don't want to convert an ongoing sentence to Title Case.
I found a lot of discussion here on how to convert to title case. However I am having difficulty implementing this in to my form as I am still new to JavaScript. All the examples show the script, but not how to implement it in a form.
I was playing around with Greg Dean's top answer to try and target the specific inputs like so...
toTitleCase = function(str)
{
var name = document.getElementById('name');
var city = document.getElementById('city');
return str.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
However this does not seem to be working.
Here's the HTMl:
<form>
<input type="text" class="text" id="name" placeholder="Name">
<br>
<input type="text" class="text" id="city" placeholder="City">
<br>
<textarea type="textarea" id="words" placeholder="Words" cols="70" rows="6">
</textarea>
<br>
<input type="button" value="Combine" onclick="convert()">
<br>
<div class="wrap"><span id="CharCountLabel1" class="counter"></span>
<textarea type="textarea" name="output" id="output" cols="70" rows="10"
maxlength='' placeholder="Output"></textarea>
</div>
<br>
<button type="reset" onclick="ResetForm();" value="Reset
form">Reset form</button>
</form>
And the rest of the script:
function convert() {
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
var words = document.getElementById("words").value;
//input = wordwrap(input, 70, true);
var output = "";
if(!document.getElementById("name").disabled){
output += "Name: " + name + "\n";
}
if(!document.getElementById("city").disabled){
output += "City: " + city + "\n";
}
if(!document.getElementById("words").disabled){
output += "The words are... " + words + "\n";
}
document.getElementById("output").value = output;
}
CharacterCount = function(output,FieldToCount){
var myField = document.getElementById(output);
var myLabel = document.getElementById(FieldToCount);
var Chars = myField.length;
if(!Chars){Chars = "" ; };
var remainingChars = Chars + myField.value.length
myLabel.innerHTML = remainingChars+""+Chars
}
setInterval(function(){CharacterCount('output','CharCountLabel1')},55);
How do I target the script to just the specified input fields? Please no jQuery, just JavaScript solutions.
While you have a fully-function toTitleCase() function, you're never actually calling it. All you need to do is run your name and city variables through your toTitleCase function when you go to output them to the page:
if (!document.getElementById("name").disabled) {
output += "Name: " + toTitleCase(name) + "\n";
}
if (!document.getElementById("city").disabled) {
output += "City: " + toTitleCase(city) + "\n";
}
To prevent the words from also being transformed, simply don't pass that variable to the function:
if (!document.getElementById("words").disabled) {
output += "The words are... " + words + "\n";
}
A working demo of this can be seen here.
Hope this helps! :)

How to get values of HTML tags (getAttribute is returning NULL)

I want to get the values of the value-tag of all the fields.
e.g. I want to get:
/wEPDwUKLTUwMTUxNzcwOGRklQy3YSnUhKEGDrFOOy2aa5Lg4qY=
83BB589F
-/wEWBwKN/dHeCAKl1bKzCQK1qbSRCwKpiJ/dDgKE8/3/CQKM+5aFCQKM54rGBs1XK43QekWbnANIKpGR9+Q85Kji
0151CSE003
#Abhishek
My HTML code which is currently giving NULL and Undefined
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<form name="form1" method="post" action="http://abc/Home/default.aspx" id="form1">
<div><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTUwMTUxNzcwOGRklQy3YSnUhKEGDrFOOy2aa5Lg4qY="></div>
<div><input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="83BB589F"></div>
<div><input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBwKN/dHeCAKl1bKzCQK1qbSRCwKpiJ/dDgKE8/3/CQKM+5aFCQKM54rGBs1XK43QekWbnANIKpGR9+Q85Kji"></div>
User Name<input name="txtUserName" type="text" id="txtUserName" value="0151CSE003">
Password<input name="txtPassword" type="password" id="txtPassword" value="#Abhishek">
<input type="submit" name="Ulogin" value="Login" id="Ulogin" >
</form>
<br><br>
<div id="op"></div>
<script>
{
//var x=document.getElementsByTagName("div")[0].getAttribute('value');
var x=document.getElementsByTagName("div")[1];
alert(x.getAttribute('data-value'));
alert(x.dataset.value);
document.getElementById("op").innerHTML=x;
}
</script>
</body></html>
Please check this code and see how it's working to get the values. Some pieces of your code were a little bit wrong.
var viewState = document.querySelector("#__VIEWSTATE");
var viewStateGenerator = document.querySelector("#__VIEWSTATEGENERATOR");
console.log(viewState.value);
console.log(viewStateGenerator.value);
document.querySelector('#op').innerHTML = viewState.value;
It should be
x.getAttribute('value')
You don't add the "data-" tag retroactively, it would have to be included.
if you need take values of inputs, i can do it directly:
var x=document.getElementsByTagName("input");
var showValues = '<ul>';
for(var i=0, len=x.length; i<len; i++){
if(x[i].id != "Ulogin"){
showValues +='<li>'+x[i].value + '</li>';
}
}
showValues += '</ul>';
document.getElementById("op").innerHTML=showValues;
i have wrapped it in ul-li tags, if you would like to show it to user
OK, your JavaScript is a bit messy. The code below should fit your requirements. Use Value property with getElementById
var VIEWSTATE = document.getElementById("__VIEWSTATE").value;
var VIEWSTATEGENERATOR = document.getElementById("__VIEWSTATEGENERATOR").value;
var EVENTVALIDATION = document.getElementById("__EVENTVALIDATION").value;
var UserName = document.getElementById("txtUserName").value;
var Password = document.getElementById("txtPassword").value;
alert(VIEWSTATE +"\n" + VIEWSTATEGENERATOR +"\n" + EVENTVALIDATION + "\n" + UserName+"\n"+Password);
I personally recommend you use jquery - it is much easier to use, uses fewer lines of code and is powerful.
Here is the code:
var VIEWSTATE = $("#__VIEWSTATE").val();
var VIEWSTATEGENERATOR = $("#__VIEWSTATEGENERATOR").val();
var EVENTVALIDATION = $("#__EVENTVALIDATION").val();
var UserName = $("#txtUserName").val();
var Password = $("#txtPassword").val();
alert(VIEWSTATE +"\n" + VIEWSTATEGENERATOR +"\n" + EVENTVALIDATION + "\n" + UserName+"\n"+Password);

Converting HTML form input into Javascript variables and comparing values

I am trying to compare the birth dates of two people. Person 1 and Person 2 input their names and dates of birth in an HTML form, and I want to use Javascript to compare the two dates and print out which person is older on the HTML page. However, I'm not sure how to submit the form and compare the dates. Here is what I have so far for the HTML:
<form id="form1">
Full name of first person: <input type="text" name="name1"><br>
Birthday: <input type="date" date="date1"><br>
<br>
Full name of second person: <input type="text" name="name2"><br>
Birthday: <input type="date" date="date2"><br>
</form>
And the Javascript:
var name1 = document.getElementsByName("name1");
var name2 = document.getElementsByName("name2");
var date1 = document.getElementsByName("date1");
var date2 = document.getElementsByName("date2");
How do I submit the variables in HTML and then have Javascript compare the two dates?
You forgot two things:
A submit button.
A submit handler.
I guess this solves your question.
window.onload = function () {
document.getElementById("form1").onsubmit = function () {
var name1 = document.getElementById("name1");
var name2 = document.getElementById("name2");
var date1 = document.getElementById("date1");
var date2 = document.getElementById("date2");
if ((new Date(date1.value)).getTime() < (new Date(date2.value)).getTime()){
console.log(name1.value + " is greater than " + name2.value)}
else if ((new Date(date1.value)).getTime() > (new Date(date2.value)).getTime()){
console.log(name2.value + " is greater than " + name1.value)}
else{
console.log(name2.value + " and " + name1.value + " are of same age.")};
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
<input type="submit" value="Check" />
</form>
You need to add an action to the form and a submit button. Then you can add an onsubmit call from your button to invoke a simple string comparison function to see which number is greater
Basic form data access demo
var compare = function () {
var form = document.getElementById("form1");
var output = document.getElementById("demo");
output.innerHTML = "";
for(var i = 0; i< form.length; i++){
output.innerHTML = output.innerHTML +" "+ form.elements[i].value;
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
</form>
<input type="button" name="submit" value="Compare " onclick="compare()" />
<p id="demo"></p>
Well, let's go step by step on this
1. How to submit a form
In HTML you have 2 ways of submitting a form:
Through an <input> tag with the type="submit" attribute (resulting in <input type="submit" />
Trough a <button> tag with the type="submit" attribute (resulting in <button type="submit">...content...</button>
Now when these buttons get clicked, they will trigger the <form>'s submit event.
2. How to subscribe to a form's submit event
As when submitting a form, there're (without any external libraries) 2 ways of subscribing to a form's submit event:
Directly setting a property on the form: formvar.onsubmit = function() { /* ... do stuff ... */ } (not really recommended as other plugins/scripts might overwrite this)
Adding an event listener: formvar.addEventListener("submit", function() { /* ... do stuff ... */ } (better than directly setting a property as this won't be removed when another script subscribes to the same event)
3. Comparing dates
Well, first you'd have to transform the dates from the string value you got from the textbox to a proper Date type:
date1 = Date.parse(date1.value);
date2 = Date.parse(date2.value);
And then with a simple arithmetic operator you can find out which one of them is the oldest:
var difference = date2 - date1;
if(difference > 0)
{
// Second person is the oldest
}
else if (difference < 0)
{
// First person is the oldest
}
else
{
// They are the same age
}
You don't need to submit the form to check the difference. A simple onclick function or click event listener will do.
You need to check if they are older, younger, or the same age. Try it below. You code wasn't working because you didn't have a name property for your dates. I switched them to use ids.
document.getElementById("theButton").addEventListener('click', checkOldest);
function checkOldest() {
var name1Value = document.getElementById("name1").value,
name2Value = document.getElementById("name2").value,
date1Value = document.getElementById("date1").value,
date2Value = document.getElementById("date2").value,
result = document.getElementById("result");
// make sure you have input for both birthdates and names
if (name1Value && name2Value && date1Value && date2Value) {
var dateOneComparedToTwo = new Date(date1Value) - new Date(date2Value);
if (dateOneComparedToTwo < 0) {
result.innerText = name1Value + ' is older than ' + name2Value + '!';
} else if (dateOneComparedToTwo > 0) {
result.innerText = name1Value + ' is younger than ' + name2Value + '!';
} else {
result.innerText = name1Value + ' and ' + name2Value + ' are the same age!';
}
} else {
result.innerText = "You need to fill out the form completely!";
}
}
<form id="form1">
Full name of first person: <input type="text" id="name1" name="name1"><br>
Birthday: <input type="date" id="date1" name="date1"><br>
<br>
Full name of second person: <input type="text" id="name2" name="name2"><br>
Birthday: <input type="date" id="date2" name="date2"><br>
<button id="theButton">Who's oldest?</button>
</form>
<p id="result">
Fill out the form please!
</p>

To validate and connvert entered phone number in a form

I am working on an HTML form which has 4 fields as below
Name
Email
Phone Number
Message
The field for phone number should accept 10 digits. It change/accept of the format (xxx) xxx-xxxx when i click on the Message field.
I have written the function for javascript to do so but the number is not getting changed when i click on the message field. The code is below
It would be a great help if someone could help me out with this. Thanks in advance!
function PhoneValidation(phone) {
if (!(this.isNull)) {
var str = this.rawValue;
var regExp = /^\d{10}$/;
if (regExp.test(str)) {
this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(3, 3) + "-" + str.substr(6, 4);
} else {
regExp = /^[1-9]\d{2}\s\d{3}\s\d{4}$/;
if (regExp.test(str)) {
this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(4, 3) + "-" + str.substr(8, 4);
} else {
regExp = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
if (!(regExp.test(str))) {
xfa.host.messageBox("Please enter the telephone number in the format '(999) 999-9999'.");
this.rawValue = null;
xfa.host.setFocus(this);
}
}
}
}
}
And HTML below:
<form id="contact-form" class="contact-form" method="post" action="">
<div class="result"></div>
<input type="text" name="contact[name]" id="name" placeholder="Name *">
<input type="text" name="contact[email]" id="email" placeholder="E-mail *">
<input type="text" name="phone" id="phone" placeholder="Phone" onChange="PhoneValidation(this)" ;>
<textarea cols="5" rows="5" name="contact[message]" id="message" placeholder="Message *"></textarea>
<input type="submit" class="btn-dark" value="SEND">
</form>
in your validate function this = window, or something else so I have no idea what will !this.isNull actually do.
You may change it to something like
function PhoneValidation(phone) {
if(phone.value) {
// set up the phone.value here
}
}
// bind the change event as you did.
<input type="text" name="phone" id="phone" placeholder="Phone" onChange="PhoneValidation(this)";>
EDIT The code above is just the idea, please note that inside PhoneValidation in your case this = window. You have passed phone so try to use it, you can take the demo here http://jsfiddle.net/7qjz2/. As a summary
window.PhoneValidation = function(phone)
// cause I don't know where you put this js, so let bind it to window.
Next in side function, rawValue is undefined so use phone.value instead
If you can't pass the condition, set the html for your message div. by
document.getElementById("result").innerHTML = "Whatever you want"
That's all. Hope this help!
if (!(this.isNull)) {
Apparently, keep it short and simple like:
if (this) {

Use user info without prompt or confirm?

All I want to do is be able to do is have users submit info and be able to use it - without using prompt.
I would like to have them be able to input and have a different box to be able to give them info based on there info. I.E. 81 is a great number.
var c = prompt("pick a number")
if(c>100){
console.log("110 is to high of a number")
}
This is what I have. I'm used to JavaScript editors and using console.log. I'm looking for a way to do that based on info I receive and be able to give feed back in a different <div> or whatever. Can anyone help?
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="submit" value="submit" />
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert(textbox.value + '\n' + location.value);
}
<input type="button" value="submit" onclick="showConfirmationDialog();" />
If you're using jQuery, you can use a click handler that looks like this:
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Here's a fiddle that shows the above code in action.

Categories