intl-tel-input is not adding country code with phone Number - javascript

I am using intl-tel-input plugin in my contact form. Plugin is running fine and dropdown is appearing well with all country codes and flags. but when i submit form, i can see only phone number i have added without any country code in start. here is what i am doing.
<input class="cfos_field" autocomplete="off" type="tel" name="number" id="cfos-number" placeholder="Your Number">
and here is my Jquery code
jQuery(document).ready(function () {
var rhInput = document.querySelector("#cfos-number");
window.intlTelInput(rhInput, {
initialCountry: "auto",
geoIpLookup: function (callback) {
jQuery.get('https://ipinfo.io', function () {
}, "jsonp").always(function (resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
});
});
I dont know what i am doing wrong.

Related

Dynamically initialise multiple input fields in plugin

I've many forms on one page. Each of the forms should have a phone number field. Those fields are driven by JS plug-in.
So I'm getting a big number of fields which should be properly initialized.
If I will do it manually I will get:
forms * phone input fields = number of initializations.
At this moment I only have the very first field working. Other doesn't initialize.
My markup looks like:
<input type="tel" class="phone_flag" name="phone_tab1[main]" required="">
<input type="tel" class="phone_flag" name="phone_tab2[main]" required="">
<input type="tel" class="phone_flag" name="phone_tab3[main]" required="">
xxx
...
I got a piece of advice: in order to make in properly work, I should have querySelectorAll with forEach loop. Then I should call PhoneDisplay function, don't pass the class name, instead pass in the element itself. Afterward, initialize the plugin on that element directly.
I only came to this solution, but it only inits the first element.
JS init code:
document.querySelectorAll('.phone_flag').forEach(el => {
PhoneDisplay(el.className);
});
function PhoneDisplay(ClassName){
var input = document.querySelector('.' + `${ClassName}`);
var iti = window.intlTelInput(input, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('proxy.php', function() {}).always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
hiddenInput: "full_phone",
utilsScript: "intlTelInput/js/utils.js"
});
var reset = function() {
input.classList.remove("error");
errorMsg.innerHTML = "";
errorMsg.classList.add("hide");
validMsg.classList.add("hide");
};
input.addEventListener('blur', function() {
reset();
if (input.value.trim()) {
if (iti.isValidNumber()) {
validMsg.classList.remove("hide");
} else {
input.classList.add("error");
var errorCode = iti.getValidationError();
errorMsg.innerHTML = errorMap[errorCode];
errorMsg.classList.remove("hide");
}
}
});
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);
}
document.querySelector returns the first query, so var input is always the first input. You should just pass in the element itself in the forEach loop: PhoneDisplay(el); and then function PhoneDisplay(input) and remove the 'var input=' line.
jQuery(document).ready(function($) {
var input = $("input[name=phone]");
input.each(function() {
intlTelInput($(this)[0], {
initialCountry: "auto",
nationalMode: false,
separateDialCode: true,
preferredCountries: ["ua", "pl", "us"],
geoIpLookup: function(success, failure) {
$.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "us";
success(countryCode);
});
},
});
});
});

target input field and submit button by type and name

I'm using a Jquery code to check if an e-mail input field is empty before sending the form.
here is my e-mail input html :
<input class="sml_emailinput" type="email" value="" placeholder="votre adresse e-mail" name="sml_email"></input>
and here is my submit button :
<input class="btn sml_submitbtn" type="submit" value="OK" name="submit"></input>
it works fine with this code :
function submit_newsletter(){
var $submit = $("input[type=submit]"),
$inputs = $("input[type=email]");
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
}
the problem is that I'm using other input fields on my website and so I need to target those two specific field only using input type and input name.
I tried many ways of doin it and I really don't understand why it's not working.
here the code I tried :
function submit_newsletter(){
var $submit = $("input[type='submit', name='submit']"),
$inputs = $("input[type='email', name='sml_email']");
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
}
can anybody help me with this ?
I can't change the html of the two inputs because it's generated by a plugin.
thanks a lot
The syntax you need is
$('input[type="x"][name="y"]')
Try it using
$('input[type="x"][name="y"]')

Clear jquery.validate error messages on change/hide of disabled attributes

Trying to clear the error messages when the disabled fields are toggled on and off on my form using jquery.validate. Right now I have it working where on change or on click fields are showing and changing the prop from disabled. So it works for what I need which is hiding the fields that are not necessary and not validating them when they are in a disabled state. However, when I toggle these fields back to their disabled state ad hide them, the error messages are still showing until I click submit again. I tried adding the .valid() call to the toggleDisabled function and it does not make the messages disappear when they go back to a hidden/disabled state. Anyone see what can be added to make the messages disappear when the fields do?
Here is the working fiddle with what I have so far:
JS Fiddle
And I am using jquery.validate from :
jQuery.Validate
HTML:
<form id="myform">
<input type="text" name="field1" />
<br/>
<br />
<input type="text" id="toggleInput" name="toggleInputName" disabled style="display:none" />
<input type="button" id="toggleButton" value="Toggle Disabled" />
<div id="tickets">
<label for="group1">Number of Tickets: <span class="req">*</span></label>
<select class="group1_dropdown" id="group1" name="group1">
<option value="0">-- Please select --</option>
<option value="1">Member</option>
<option value="2">Member + 1 Guest</option>
<option value="3">Member + 2 Guests</option>
<option value="4">Member + 3 Guests</option>
</select>
</div>
<input type="text" id="payMethod" name="payMethodName" disabled style="display:none" />
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('#myform').validate({
onblur: true,
onkeyup: false,
ignore: ":disabled",
rules: {
field1: {
required: true,
minlength: 5
},
payMethodName: {
required: true,
minlength: 5
},
toggleInputName: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
});
//used for toggling/showing disabled fields - will display and make not disabled on same click event
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.prop('disabled')) {
$this.prop('disabled', false).show();
} else {
$this.prop('disabled', true).hide();
}
});
};
})(jQuery);
$(function () {
$('#toggleButton').click(function () {
$('#toggleInput').toggleDisabled();
});
});
$(function () {
$("#group1").change(function () {
var str = "";
str = parseInt($(this).val());
if(str == 2)
$("#payMethod").toggleDisabled();
else
$("#payMethod").toggleDisabled();
});
});
I have changed your plugin a little to do what you want.
Fiddle Demo
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this),
id = $this.attr('id'), //get the id of input
label = $this.next('label[for="' + id + '"]'); //find the next label which is added by jQuery Validator
if ($this.prop('disabled')) {
label.show(); //show the label
$this.prop('disabled', false).show();
} else {
label.hide();//hide the label
$this.prop('disabled', true).hide();
}
});
};
})(jQuery);
Update
Another way without changing your plugin
Fiddle Demo
$(document).ready(function () { //place your all DOM ready code in one DOM ready handler
var validator = $('#myform').validate({ //assign validate to a variable
//validator code here
});
$('#toggleButton').click(function () {
validator.resetForm();//reset Form validation
$('#toggleInput').toggleDisabled();
});
});

jQuery Validate: Validate that one field, or both fields of a pair are required

I have a form that I am trying to validate that has two fields:
<div class="entryForm">
<div class="formField">
<label for="fieldEmailAddress">Email address:</label>
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress"/>
</div>
<div class="formField">
<label for="fieldMobileNumber">Mobile number:</label>
<input type="text" name="fieldMobileNumber" id="fieldMobileNumber"/>
</div>
</div>
Here's my jQuery Validation wireup:
<script type="text/javascript">
$(document).ready(function () {
$('#form1').validate({ rules: { fieldMobileNumber: { phoneUS: true } } });
});
</script>
What I'd like to do is add an additional validation rule that says: the form is not valid if both fieldEmailAddress and fieldMobileNumber are blank. In other words, I'd like to make it such that at least one of either fieldEmailAddress or fieldMobileNumber is required. It seems like most of the jQuery Validation custom methods are designed to only work for one field at a time - I need to validate both.
Any ideas?
You can bypass the Validate plugin and do a check like the following:
$("#form1").submit(function() {
var email = $('#fieldEmailAddress');
var phone = $('#fieldMobileNumber');
if(email.val() == '' && phone.val() == '') {
alert('Fill out both fields');
}
else if(email.val() == '') {
alert('Email, please...');
}
else if(phone.val() == '') {
alert('Phone, please...');
}
else {
alert('Yay!');
}
});
You simply need to include the additional-methods.js file and use the require_from_group method.
require_from_group: [x, '.class']
// x = number of items required from a group of items.
// .class = class assigned to every form element included in the group.
jQuery:
$(document).ready(function () {
$('#form1').validate({
rules: {
fieldMobileNumber: {
phoneUS: true,
require_from_group: [1, '.mygroup']
},
fieldEmailAddress: {
require_from_group: [1, '.mygroup']
}
},
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
});
});
Add class="mygroup" to each input you need to group together...
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress" class="mygroup" />
And finally, optionally use the groups option to lump the messages into one...
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
Working DEMO: http://jsfiddle.net/CYZZy/
If you don't like where the validation message is placed, that's where you'd tweak it using the errorPlacement callback function.

Using watermark effect in forms

I want to implement watermark effect in my html form.
I have my code like this http://jsfiddle.net/aMjT4/1/
I want to set particular value to all my textboxes. Like in my textbox field
<input type="text" id="firstName" name="firstName" value="Enter First Name" class="inputTextboxId"/>
I want to set watermark text from value.(value="Enter First Name").
My javascript look like this but it will set watermark text into all my form fields.
$(document).ready(function () {
var watermark = 'Enter something...';
$('.inputTextboxId').blur(function () {
if ($(this).val().length == 0)
$(this).val(watermark).addClass('watermark');
}).focus(function () {
if ($(this).val() == watermark)
$(this).val('').removeClass('watermark');
}).val(watermark).addClass('watermark');
});
How can i set value text to all my textboxes?
I have this code but in this code i have to write this for all textboxes.
is there any way to generlize this?
<input type="text" id="city" name="city" value="Enter Your City" class="inputTextboxId" onblur="if (this.value == '') { this.value = 'Enter Country City';this.style.color = 'Gray'; }" maxlength="255" onfocus="if(this.value == this.defaultValue){this.value='';this.style.color='Black'}"/>
This is the hard way. You want to just either write a plugin or grab one that is readily available.
http://plugins.jquery.com/project/TinyWatermark
http://plugins.jquery.com/plugin-tags/watermark
Here's one I wrote
this is the js file code;
(function ($) {
$.fn.extend({
watermark: function () {
return this.each(function () {
var $obj = $(this);
$obj.val($obj.attr("watermarkText"));
$obj.focus(function (e) {
if ($obj.val() == $obj.attr("watermarkText"))
$obj.val("");
});
$obj.blur(function (e) {
if ($obj.val() == "")
$obj.val($obj.attr("watermarkText"));
});
});
}
});
})(jQuery);
and then in your html;
<script>
$(function () {
$(".watermark").watermark();
</script>
<input id="author" value="" type="text" name="author" watermarkText="Your name..." class="watermark required">

Categories

Resources