Javascript Output results with input data - javascript

I am a newbie to javascript, I am making a simple script which will show appended link with the data entered in input field, Basically it should get the data from input field and generate link with data being submitted in input field.
Similar to the example below
Input: tony#mail.com ...> after clicking Send button
processing....
Output link: www.domain.com/route.php?email=tony#mail.com
I found this code similar to mine but it wont works like i am looking for.
<p>Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
<a href="#"
onclick="this.href = ('http://' + document.getElementById('foosite').value + 'www.domain.com/route.php?email=')"
target="_blank">send</a>
Is that possible in javascript to make a script like this which will generate output without reloading the page?

You have the getelement in the wrong place. It should be like this if you want to do it that way.
<input type="text" name="foo" id="foosite1" value="" />
send
<input type="text" name="foo" id="foosite2" value="" />
send
http://jsfiddle.net/bowenac/J2Mc5/3/

Split your JS logic from your HTML
HTML
<p>Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
</p>
send
<div id="url_value"></div>
JS
var a = document.getElementById('link')
a.onclick = function(e){
e.preventDefault();
var value = document.getElementById('foosite').value;
var route = "http://www.domain.com/route.php?email=" + value + ', ';
var data = "http://www.domain.com/data.php?email=" + value + ', ';
var form = "http://www.domain.com/form.php?email=" + value;
document.getElementById('url_value').innerHTML = route + data + form
}
DEMO

You can add form to your html code and send data to server using form submit, in this case you can change the action of the form before submit to custom link.
<form name="form1" action="" onSubmit="onsubmit(this)">
<p>
Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
<input type="submit" value="send" />
</p>
</form>
<script>
function onsubmit(form)
{
//change the action of the form to your link.
form.submit();
}
</script>

Related

HTML Assigning the checkbox to the form action already defined

I have the form with action targeted for the specified task. I want to have this form also sent by email. It can be the :mailto option or other.
Mailto on submit button
So When I click the Submit form, the form is submitted. However I would like to attach another action to this action, namely I would like to send this filled form to the email by checking the ckeckbox.
So far I saw, that sending the form by checkbox is possible:
submitting a form when a checkbox is checked
but the pivot thing here is assigning the other form action to my form...
HTML form with multiple "actions"
I tried something like this:
<form id="c_form" action="default_url_when_press_enter" method="get" onsubmit="return validate(this);" target="_blank" >
....
<input type="checkbox" action="mailto:mk#gmail.com" id="cfemail" name="email">
<input class="btn" action="c_form.html" type="submit" id="cfsubmit" value="Submit form">
but it didn't work unfortunately as well as with the code applied below:
document.getElementById("cfsubmit").addEventListener("click", function(){
document.getElementById("c_form").className="submitted";
});
How can I send email along with the form submission when my box is checked?
The full code is available here:
https://jsfiddle.net/ptgbvfen/
So far if I understand your problem correctly, you want to submit the form normally. But if the checkbox is checked you want to perform a mailto function as well.
HTML:
<form id="c_form" onsubmit="return validate(this);" target="_self" >
....
<input type="checkbox" id="openmail" name="email">
<input class="btn" type="button" id="cfsubmit" value="Submit form">
Javascript
document.getElementById("cfsubmit").addEventListener("click", function() {
var check = document.getElementById("opemail"); // Get checkbox element
var mainForm = document.getElementById("c_form"); // Get form element
if (check.checked == true) { // If checked then fire
let link=document.createElement("a"); // Creates <a> element in DOM
link.href = "mailto:mk#gmail.com"; // Adds mailto link to <a>
link.click(); // Clicks the <a> and open default mail app
link.remove();
}
mainForm.submit(); // Submits the form
});
Updated___
Removed the action attribute from form element, because you do not need it when you want the form to submit on the current page. Also changed the target attribute to _self so that it will not open new tab whenever you submit the form.
Updated V2_
Made mailto autofill the email content when checkbox checked and form is submitted, as requested. If you find it helpful then kindly upvote, and if you are facing more issue then comment down below. Thanks.
Demo: https://jsfiddle.net/rzos1bwt/
HTML
<form id="c_form" onsubmit="return false;">
<div id="Page1">
<h2 class="property">Property information</h2>
<fieldset>
<figure class="property_information">
<figure class="fig">
<label>
<div class="order">A</div>
<p>Proposed Cable Route<span class="asterisk">*</span></p>
</label>
<br>
<select name="proposed_cable_route" id="cf_proposed_cable_route">
<option value="" disabled selected>-Select your answer-</option>
<option value="External">External</option>
<option value="Internal">Internal</option>
<option value="Combination">PIA</option>
</select>
</figure>
<figure class="fig" id="cf_building_post_2000">
<label>
<div class="order">B</div>
<p>Is the building post 2000?
<span class="asterisk">*</span>
</p>
</label>
<br>
<input name="building_post_2000" type="radio" value="Yes" selected>Yes
<input name="building_post_2000" type="radio" value="No">No
<br>
</figure>
<figure class="fig" id="cfasbestos">
<label>
<div class="order">C</div>
<p>Do you have asbestos report?
<span class="asterisk">*</span>
</p>
</label>
<br>
<input name="asbestos_report" type="radio" value="Yes" selected>Yes
<input name="asbestos_report" type="radio" value="No">No
<br>
<h3 class="alert">Please contact your team leader for advice!</h3>
</figure>
</figure>
<figure class="fig">
<label>
<div class="order">9</div>
<p>Surveyor<span class="asterisk">*</span></p>
</label>
<br>
<input type="text" name="surveyor" placeholder="Surveyor's name">
<input type="email" name="surveyor_email" placeholder="Email">
<br>
</figure>
<div class="emailreceipt">
<input type="checkbox" id="opemail" name="email">
<label for="opemail">Send me an email receipt of my responses</label>
</div>
<input class="btn" type="submit" id="cfsubmit" value="Submit form">
</fieldset>
</div>
</form>
Javascript
document.getElementById("cfsubmit").addEventListener("click", function() {
var check = document.getElementById("opemail"); // Get checkbox element
var formEl = document.forms.c_form; // Get the form
var formData = new FormData(formEl); // Creates form object
// Get all form data values
var cableRoute = formData.get('proposed_cable_route');
var buildingPost = formData.get('building_post_2000');
var asbestosReport = formData.get('asbestos_report');
var surveyorName = formData.get('surveyor');
var surveyorEmail = formData.get('surveyor_email');
// This will create the subject of form
var subject = "Submission from " + surveyorName;
// This will create body with filled data
var body = 'My name is ' + surveyorName + '\n' + 'My email is ' + surveyorEmail + '\n' + 'Proposed Cable Route: ' + cableRoute + '\n' + 'Is the building post 2000: ' + buildingPost + '\n' + 'Do you have asbestos report: ' + asbestosReport;
// Making the mailto link with urlencoding
var mailTo = "mailto:mk#gmail.com?subject="+encodeURI(subject)+"&body="+encodeURI(body);
if (check.checked == true) { // If checked then fire
let link=document.createElement("a"); // Creates <a> element in DOM
link.href = mailTo; // Adds mailto link to <a>
link.click(); // Clicks the <a> and open default mail app
link.remove();
}
//console.log("mailTo => ", mailTo)
mainForm.submit(); // Submits the form
});

HTML5 validation executes before custom validation

I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>

Javascript id as parameter in href

Second image ,First image I have a set of links, which will open a pop-up form.
When the link is clicked,I want to send a parameter to the form and then use it on form submission.
I'm able to set the value to be passed as id of <a> tag. Can I send to further?
<div> <span>Chapter $i:</span>
<a href='$viewlink '>View</a><span class='status'>Status:$status </span>
<a href=$reqlink id=$i data-rel='popup' class='ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left'>Request Access</a></div><br/>";
<form method="post" action=" " id="myPopup" data-role="popup" style="padding:10px">
<h3>Enter your details</h3>
<input type="text" name="name" id="name" placeholder="Name" required>
<input type="email" name="email" id="email" placeholder="Email" required>
<input type="date" name="date" id="date" placeholder="Intended completion date" required>
<input type="submit" data-inline="true" value="Submit" name='submit'>
</form>
Is it possible to do in javascript? How to do it?
Option #1:
Set up hidden inputs, and send the values to them when clicking the link. You can then get these on the other end where the form is sent.
(Note: in my code examples I'm explicitly using PHP as that's where you seem to have copied your code snipped from)
echo "<a href='$viewlink' onclick='$(\'#viewlink\').val(1);'>View</a><span class='status'>Status:$status </span>
<!-- Do the following inside the form -->
<input type='hidden' name='viewlink' id='viewlink' value='0' />";
And on the PHP receiving end you can do this:
if ($_POST['viewlink'] == 1) {
// do stuff
}
Option #2:
Alternatively you could send the data to a javascript array, prevent posting on submit of the form, take care of adding the array to the form action as query string, then explicitly send the form.
echo "<a href='$viewlink' onclick='linkClicked('viewlink');'>View</a><span class='status'>Status:$status </span>
This is what you'd do in your javascript file:
var queryString = [];
function linkClicked (type) {
queryString[type] = 1;
}
$("#myPopup").submit(function(event) {
event.preventDefault();
$(this).attr('action', $(location).attr('host') + $.param(queryString));
$(this).submit();
});
And on the PHP receiving end you can do the following (note the $_POST from above has changed to $_GET):
if ($_GET['viewlink'] == 1) {
// do stuff
}
try this..
<a id = 'yourid' class = 'mybtn'>click me..</a>
<form id = 'myform'>
....
</form>
Jquery
$(document).ready(function(){
$('.mybtn').click(function(){
var id = $(this).attr('id');
var SubmitForm = $("#myform").serializeArray();
$.post("somepage.php",
{
SubmitForm:SubmitForm,
ID:id
},
function(res){
alert(res);//your result..
});
});

Dynamic URL from user input to search

What I am trying to accomplish: When a user inputs dates, number of adults ect it would dynamically add the info via javascript to the URL within the url variables. This is what I have so far: ( I am a Noob but trying to make it work )
<script type="text/javascript">
$(function () {
$('#submit').click(function() {
$('#button').click(function(e) {
var checkInDate = document.getElementById('checkInDate').value;
var checkInMonthYear = document.getElementById('checkInMonthYear').value;
var checkOutDate = document.getElementById('checkOutDate').value;
var checkOutMonthYear = document.getElementById('checkOutMonthYear').value;
var numberOfAdults = document.getElementById('numberOfAdults').value;
var rateCode = document.getElementById('rateCode').value
window.location.replace("http://www.Link.com/redirect?path=hd&brandCode=cv&localeCode=en&regionCode=1&hotelCode=DISCV&checkInDate=27&checkInMonthYear=002016&checkOutDate=28&checkOutMonthYear=002016&numberOfAdults=2&rateCode=11223");
window.location = url;
});
});
Ok, so first things first: You probably don't need to do this at all. If you create a form and add a name attribute to each input, then the submission automatically creates the URL for you. Fixed value fields can be set to type="hidden".
For this to work you need to use the "GET" method.
<form action="http://www.Link.com/redirect" method="GET">
<input type="hidden" name="path" value="hd"><br>
<input type="hidden" name="brandCode" value="cv"><br>
<input type="hidden" name="localeCode" value="en"><br>
<input type="hidden" name="regionCode" value="1"><br>
<input type="hidden" name="hotelCode" value="DISCV"><br>
<input type="text" name="checkInDate"><br>
<input type="text" name="checkInMonthYear"><br>
<input type="text" name="checkOutDate"><br>
<input type="text" name="checkOutMonthYear"><br>
<input type="text" name="numberOfAdults"><br>
<input type="text" name="rateCode"><br>
<input type="submit">
</form>
Clicking "Submit" changes the URL to the desired one.
If this does not suit your needs, you can replace parameters in the URL by following the advice in this SO answer: Answer Link
This is much better than trying to re-implement URL manipulation on your own.

How to add hyphen in between strings in url

I have a form in which there is one text field and ine submit button.on click of submit button,it goes to next PHP page.The user can enter text in the text field.The text field can contain n number of text string separated by space.like a user enters text as
MY name is peter
I want text to change as MY-name-is-peter in url.
when user clicks on submit button.the url should become like submit.php?search=MY-name-is-peter
<form action="submit.php" method="get">
<input type="text" name="search" id="search">
<input type="submit" name="submit" value="submit">
</form>
PLease guide on how to add hyphen in the strings in url.
<script>
var handler = function (element) {
element.form.search.value = element.form.search.value.replace(/ /g, '-');
};
</script>
<form action="" method="get">
<input type="text" name="search" id="search" />
<input type="submit" onclick="handler(this);" name="submit" value="submit" />
</form>
str_replace will work or if you want to use regex you can try preg_replace("/[-]/", " ", $yourString)
You should encode URL before submit it:
$('form').submit(function(){
var val = $(this).find('#search').val();
$(this).attr('action','submit.php'+encodeURI(val))
})
Example : http://jsfiddle.net/e3L3a/

Categories