Javascript capture HTML form value for Mixpanel - javascript

I have a mailchimp form to sign up for my email list, and mixpanel tracking to detect when the form is submitted.
<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup"><form id="mc-embedded-subscribe-form" class="validate" action="http://fileoptic.us7.list-manage.com/subscribe/post?u=a1a176055d942403ee4c74a11&id=028333dc80" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank"><label for="mce-EMAIL">Subscribe to our mailing list for blog updates:</label>
<input id="mce-EMAIL" class="email" name="EMAIL" required="" type="email" value="" placeholder="email address" />
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input name="b_a1a176055d942403ee4c74a11_028333dc80" type="text" value="" /></div>
<div class="clear"><input id="mc-embedded-subscribe" class="button" name="subscribe" type="submit" value="Subscribe" /></div>
</form></div>
<!--End mc_embed_signup-->
<script type="text/javascript">
mixpanel.track_forms("#mc-embedded-subscribe-form", "Subscribed to Email List");
</script>
I want to extract the submitted email address from the form and use mixpanel.alias to identify users by their email addresses as they navigate around my site.
What code do I use to extract the email address and call mixpanel.alias with it?

I don't know anything about mixpanel, but here are two ways to get the value of an input and store it in a variable for later use.
With jQuery (I prefer this method):
$('#mc-embedded-subscribe-form').on('submit', function(){
var val = $('input.email').val();
console.log(val); // Use this to test the function
});
Or with plain Javascript. First add this to the form tag in your HTML:
onsubmit="getEmail()"
Then the JS function:
function getEmail() {
var elem = document.getElementById('mce-EMAIL');
var val = elem.value;
console.log(val); // For testing
}
Hope that helps :)

Related

Validate Form With JavaScript Using Multiple id

I use JavaScript to validate my form but the JavaScript can only validate a field at a time which means I have to duplicate the JavaScript for every field that I want to validate.
For Example,
My form has the Phone and Email fields that I want to validate, To achieve that, I had to write the javascript with the phone ID separately and write the javascript with the email ID separately.
Is it possible to validate the phone and email fields independently but with one javascript file and different ids?
My Sample code is below;
<!--THIS SCRIPT ONLY VALIDATES THE PHONE FIELD -->
<!--TO VALIDATE THE EMAIL FIELD, I HAVE TO DUPLICATE THIS SCRIPT AND CHANGE THE IDS TO email -->
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isphoneInUse(value)) {
alert ("Phone In Use!\nPlease provide another one");
$(".validate").hide();
} else {
$(".validate").show();
}
});
$('#submitForm()').on('submit', function(e) {
var value = $("#phone").val();
if (isphoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return 0;
}
})
function isphoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm" runat="server" >
<div class="validate" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Phone Available ✓</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/>
<br/><br/>
<div class="validate2" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Email Available ✓</b></span></div>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com"/>
</div>
<br/><br>
<button class="button" id="submitForm" type="submit" value=""><span>Check </span></button>
</form>

How to access to a button or an input content that was loaded (html file) with jquery?

I have a html file that have an input and a button, I load this file in another html file with jquery. And now, I want to access the input and button to do something and I don't know how to do that.
The bottom (div) is what I load in another file.
The last code is a script to load the html file.
Can You Help ME??
<div class="newsletter">
<h6 class="headerDIV">SUBSCRIBE TO OUR NEWSLETTER</h6>
<input id="newsletterInputEmail" class="input-email"type="email" placeholder="Enter your email here">
<button id="newsletterButtonSubmit" width="100px"class="w3-button w3-round-xlarge w3-grey">Submit</button>
<p><label id="newsletterEmailMSG" class="textFillField">This field is mandatory</label></p>
<p><input id="newsletterCheckbox" class="w3-check" type="checkbox"><label class="textRights">I have read and accepted the general terms and conditions*</label></p>
<p><label id="newsletterCheckboxMSG" class="textFillField">This field is mandatory</label></p>
<label class="textRights2">See our Privacy Notice for more information.</label>
</div>
$(document).ready(function(){
$("#newsletter").load("standardSite/newsletter.html");
});
Thanks in advance!!!
To bind events to dynamically generated elements, you need to do event delegation jquery offers.
$('#newsletter').on('click', '#newsletterButtonSubmit', function(){
var inputVal = $(this).parent('div').find('#newsletterInputEmail').val();
});
Above assumes that there will be unique id per element. If you're loading it multiple times, there will be multiple elements with the same id. In that case, you should use unique id or a class as done below:
$('#newsletter').on('click', '.newsletterButtonSubmit', function(){
var inputVal = $(this).parent('div').find('.newsletterInputEmail').val();
});
Check this snippet:
$('#newsletter').on('click', '#newsletterButtonSubmit', function() {
var inputVal = $(this).parent('div').find('#newsletterInputEmail').val();
console.log(inputVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="newsletter">
<div class="newsletter">
<h6 class="headerDIV">SUBSCRIBE TO OUR NEWSLETTER</h6>
<input id="newsletterInputEmail" class="input-email" type="email" placeholder="Enter your email here">
<button id="newsletterButtonSubmit" width="100px" class="w3-button w3-round-xlarge w3-grey">Submit</button>
<p><label id="newsletterEmailMSG" class="textFillField">This field is mandatory</label></p>
<p><input id="newsletterCheckbox" class="w3-check" type="checkbox"><label class="textRights">I have read and accepted the general terms and conditions*</label></p>
<p><label id="newsletterCheckboxMSG" class="textFillField">This field is mandatory</label></p>
<label class="textRights2">See our Privacy Notice for more information.</label>
</div>
</div>
Create a variable to store the input by user and then you can use the variable wherever you want:
document.getElementById("buttonid").onclick =function(){
var input = document.getElementById("boxid").value();
}

JavaScript set a form fields initial value, to the same value of another field?

I am trying to handle some JavaScript work, which I don't have much experience with. I have a 2 part form where a user enters their personal info, and then company info. I am trying to set some of the company fields to what they already entered in their personal info.
I don't want the user to have to retype address, email, etc.
for example, I have...
<div class="form-group">
<label for="email">Email<span>*</span></label>
<input name="email" type="text" class="form-control required" id="email"placeholder="Email" value=".
{{email}}">
<span id="span_email" class="error-msg"></span>
And...
<div class="form-group">
<label for="comp_email">Company Email<span>*</span></label>
<input name="comp_email" type="text" class="form-control required" id="comp_email"placeholder="Email"
value="{{comp_email}}">
<span id="span_email" class="error-msg"></span>
How would I be able to set that second comp_email field to initially have the email info, so the user doesn't have to retype, unless they actually wanted to change the comp_email to another email address?
EDIT
It is all in one form, just separated by divs. Initially, when the page is loaded, the account section div is displayed, when the user hits next, it triggers the display of the business info.
<input type="button" onclick="nextFormPage(); window.scrollTo(0, 100)"
class="btn btn-danger btn-block" value="Next">
The nextFormPage() function just hides the first div and displays the second div.
You have tagged both javascript and jQuery so I'm not sure which you are using. But you can do this with a single line either way:
Javascript::
document.getElementById("comp_email").value = document.getElementById("email").value;
document.getElementById("email").value gets the value from the email input and we set the value of the document.getElementById("comp_email") by setting its value attribute:
jQuery:
$("#comp_email").val( $("#email").val() );
$("#email").val() get the value from the email input and $("#comp_email").val( ... ); sets the text passed in as the input value.
Javascript Working Example
function nextFormPage(){
document.getElementById("comp_email").value = document.getElementById("email").value;
}
<div class="form-group">
<label for="email">Email<span>*</span></label>
<input name="email" type="text" class="form-control required" id="email" placeholder="Email" value="">
<span id="span_email" class="error-msg"></span>
<div class="form-group">
<label for="comp_email">Company Email<span>*</span></label>
<input name="comp_email" type="text" class="form-control required" id="comp_email" placeholder="Email"
value="">
<span id="span_email" class="error-msg"></span>
<input type="button" onclick="nextFormPage(); window.scrollTo(0, 100)"
class="btn btn-danger btn-block" value="Next">
If your user is logged in, you should pass all of their information to the form, including their email. For example:
const logIn = () => {
... some code to get the user ...
... pass the user to the form, probably through an event listener...
let button = document.createElement("button")
button.textContent = "Edit"
button.addEventListener('click', () => {editYourStuff(user)}
}
const editYourStuff = user => {
... grab whatever your form is called ...
editForm.email.value = user.email
}
This should pre populate your form with the email

How to give custom validation error messages for HTML validations?

When I use default HTML validation it shows the default error messages which is not I want to show to my clients. I need to customize the message and give different massages for each validations such as min, max, type and require. For Example:
The field is required, The value does not match
Refer the tradition HTML Code:
<input type="text" required>
I want something like this:
<input type="text" validation="required|my_message,min:5|my_message">
It's totally possible with custom libraries in jQuery which I would suggest - https://github.com/aslamanver/abvalidate
Custom Message - jQuery Form Validation - abValidate.js
ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name"
Use this library by adding these CDNs
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- abValidate Library -->
<script type="text/javascript" src="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.min.js">
<link rel="stylesheet" href="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.css">
Initialize the library
$(document).ready(function () {
//.ab-form is your form class
$(".ab-form").abValidate();
});
There you go, now you can use your custom validation using jQuery abValidate library
<form class="ab-form" action="your_action_url">
<!-- Input and error message should be in a div class -->
<div class="my-form-group">
<input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name" class="ab-validation-i" />
<div class="error"></div>
</div><br>
<div class="my-form-group">
<input type="submit" name="submit" value="Submit">
</div>
</form>
Try this one, its better and tested:
HTML:
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
JAVASCRIPT:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
Demo:
http://jsfiddle.net/patelriki13/Sqq8e/

how to use autocomplete in angularjs

I have an application with add friend feature, in that feature, user must fill their friend's username in the textbox. this is the html code:
<div content-for="title">
<span>Add Friend</span>
</div>
<form class="form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID">
</div>
<button type="submit" class="btn btn-default" data-ng-click="addfriends()">Add</button>
the interface will be like this
and this is the js code:
// addfriend
$scope.add = {};
$scope.addfriends = function(){
$scope.messages = {
email : $scope.add.email,
userid : $scope.datauser['data']['_id']
};
//event add friend
socket.emit('addfriend',$scope.messages,function(callback){
if(!callback['error']){
$scope.datauser['data']['penddingrequest'].push(callback['data']);
//push pendding request to localstorage user
localStorageService.remove('user');
localStorageService.add('user', $scope.datauser);
$scope.add['email'] = '';
alert('Successfully added friend');
}else{
var msg = callback['error'];
navigator.notification.alert(msg,'','Error Report','Ok');
}
});
};
I want to change this feature little bit, I want to make this textbox showing some suggestion based on the input, like if user input 'a', the textbox will show all user id that start with 'a'. something like twitter's searchbox or instagram searchbox. these user ids is from database.
example searchbox of web instagram
my question is how to change this textbox to be autocomplete but still work like before? thanks very much
There are many ways to do this.
First is this one: You basically create Angular directive for your input.
http://jsfiddle.net/sebmade/swfjT/
Another way to do is to attach onKeyUp event to your input:
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID" ng-keyup="searchFriends()">
<div ng-model="searchFriendsResult" />
</div>
And then, in your controller, you create a searchFriends function that will:
Search your database
Display the result in the view.
Something like this (not a complete code):
$scope.searchFriends = function(value){
// Make Ajax call
var userRes = $resource('/user/:username', {username: '#username'});
userRes.get({username:value})
.$promise.then(function(users) {
$scope.searchFriendsResult = users;
});
};
Use Bootstrap Typeahead
<input type="text" ng-model="asyncSelected"
placeholder="Locations loaded via $http"
uib-typeahead="address for address in getLocation($viewValue)"
typeahead-loading="loadingLocations"
typeahead-no-results="noResults"
class="form-control"/>

Categories

Resources