Need to do validation on radio buttons onClick function.
HTML CODE :
<fieldset>
<div class="t box"><h4>T</h4>
<div class="radio-buttons-1">
<label class="radio-inline">
<input type="radio" name="tw" value="tw15"> 15
</label>
<label class="radio-inline">
<input type="radio" name="tw" value="tw16"> 16
</label>
</div>
<br>
<span class="error-messages-tw" style="display:none; color:#F44336; font-size:16px; font-weight:700;">
</span>
<br><br>
<div class="tw15 box2">
<select name="twg" class="form-control is_twg" onChange="showfield(this.options[this.selectedIndex].value)">
<option value="" >Select One</option>
<option value="twy">Yes</option><option value="twn">No</option>
</select>
<br>
<span class="error-messages-twg" style="display:none; color:#F44336; font-size:16px; font-weight:700;">
</span>
<br><br>
<div id="div8" class="showMe"><br>
<h4>Select One Option </h4>
<div class="radio-buttons-1">
<label class="radio-inline"><input type="radio" name="twga" value="a" > a
</label>
<label class="radio-inline"><input type="radio" name="twga" value="b" > b
</label>
<label class="radio-inline"><input type="radio" name="twga" value="c" > c
</label>
<label class="radio-inline"><input type="radio" name="twga" value="d"> d
</label>
</div>
<br>
<span class="error-messages-twga" style="display:none; color:#F44336; font-size:16px; font-weight:700;">
</span>
<br><br>
</div>
<button type="button" class="btn btn-next1">Next
<i class="fa fa-angle-right"></i>
</button>
</fieldset>
JS Code :
$('.msf-form .btn-next1').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
if(parent_fieldset.find("input[type='radio']").length > 0){
if (!$('input[name="twga"]:visible:checked').val()) {
$(".error-messages-twga").text("Please Select option").fadeIn();
next_step = false;
}
else {
$(".error-messages-twga").empty().fadeOut();
}
}
parent_fieldset.find('.is_twg:visible').each(function() {
if( $(this).val() == "" ) {
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-twg").text("Please Select One Option").fadeIn();
next_step = false;
}
else{
$(this).focus().css('border','0px solid #F44336');
$(".error-messages-twg").empty().fadeOut();
}
});
});
Thanks in advance.
first of all your javascript code has missing brackets..
Replace your JS Code with this
$('.msf-form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
parent_fieldset.find('.is_abc').each(function() {
if( $(this).val() == "" ) {
$(".error-messages-abc").text("Please Select option").fadeIn();
next_step = false;
}
else{
$(".error-messages-abc").empty().fadeOut();
}
});
});
Now check again if its working.
Change your js code to,
$('.msf-form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
if (!$('input[name="abc"]:checked').val()) {
$(".error-messages-abc").text("Please Select option").fadeIn();
next_step = false;
} else {
$(".error-messages-abc").empty().fadeOut();
}
});
Hope this will solve your problem.
EDIT :
$('.msf-form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
if(parent_fieldset.find("input[type='radio']").length > 0){
if (!$('input[name="abc"]:checked').val()) {
$(".error-messages-abc").text("Please Select option").fadeIn();
next_step = false;
} else {
$(".error-messages-abc").empty().fadeOut();
}
}
});
Here, I am not sure, but parent_fieldset is your parent element, and inside that you want to check if radio buttons exist or not, so I kept condition considering the same.
Related
I would like to have a little help on an enigma that I have.
I have a button that changes according to the number of input:checked
but I would like to add a condition which is: select of the checkboxes of the same class.
for example can I have 2 or more input.
<input class="banana" type="checkbox" value="Cavendish">
<input class="banana" type="checkbox" value="Goldfinger">
<input class="chocolato" type="checkbox" value="cocoa powder">
<input class="chocolato" type="checkbox" value="milk chocolate">
<input class="apple" type="checkbox" value="honneycrisp">
<input class="apple" type="checkbox" value="granny smith">
I can't use attribute name or value. it is not possible to modify the inputs.
the condition:
$('input[type="checkbox"]').click(function(){
if($('input[type="checkbox"]:checked').length >=2){
////////
if (my classes are the same) {
$('#btn').html("click me").prop('disabled', false);
} else {
$('#btn').html("too bad").prop('disabled', true);
}
//////
}
I try with
var checkClass = [];
$.each($("input[type="checkbox"]:checked"), function() {
checkClass.push($(this).attr('class'));
});
I don't know if I'm going the right way or if I'm complicating the code but a little help would be welcome. For the moment my attempts have been unsuccessful.
The following function will reference the first checkbox that's checked className and enable each checkbox that has said className whilst disabling all other checkboxes. Details are commented in Snippet.
// All checkboxes
const all = $(':checkbox');
// Any change event on any checkbox run function `matchCategory`
all.on('change', matchCategory);
function matchCategory() {
// All checked checkboxes
const checked = $(':checkbox:checked');
let category;
// if there is at least one checkbox checked...
if (checked.length > 0) {
// ...enable (.btn)...
$('.btn').removeClass('off');
// ...get the class of the first checked checkbox...
category = checked[0].className;
// ...disable ALL checkboxes...
all.attr('disabled', true);
// ...go through each checkbox...
all.each(function() {
// if THIS checkbox has the class defined as (category)...
if ($(this).is('.' + category)) {
// ...enable it
$(this).attr('disabled', false);
// Otherwise...
} else {
// ...disable and uncheck it
$(this).attr('disabled', true).prop('checked', false);
}
});
// Otherwise...
} else {
// ...enable ALL checkboxes...
all.attr('disabled', false);
// ...disable (.btn)
$('.btn').addClass('off');
}
return false;
}
.off {
pointer-events: none;
opacity: 0.4;
}
<input class="beverage" type="checkbox" value="Alcohol">
<label>🍸</label><br>
<input class="beverage" type="checkbox" value="Coffee">
<label>☕</label><br>
<input class="dessert" type="checkbox" value="cake">
<label>🍰</label><br>
<input class="dessert" type="checkbox" value="Ice Cream">
<label>🍨</label><br>
<input class="appetizer" type="checkbox" value="Salad">
<label>🥗</label><br>
<input class="appetizer" type="checkbox" value="Bread">
<label>🥖</label><br>
<button class='btn off' type='button '>Order</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
some thing like that ?
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
var checked_class = ''
;
bt_restart.onclick = _ =>
{
checked_class = ''
chkbx_all.forEach(cbx=>
{
cbx.checked=cbx.disabled=false
cbx.closest('label').style = ''
})
}
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
if (checked_class === '') checked_class = cbx.className
else if (checked_class != cbx.className )
{
cbx.checked = false
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input class="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input class="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input class="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input class="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input class="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input class="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>
In fact it's like a Matching Pairs card game
this answer is without global checked_group variable, and respecting epascarello message about data attribute see also usage.
Adding a repentance on uncheck elements
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
function clearGame()
{
chkbx_all.forEach(cbx=>
{
cbx.checked = cbx.disabled = false
cbx.closest('label').style = ''
})
}
bt_restart.onclick = clearGame
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
let checkedList = document.querySelectorAll('input[type=checkbox]:checked')
if (cbx.checked)
{
let checked_group = ''
checkedList.forEach(cEl=>{ if (cEl !== cbx) checked_group = cEl.dataset.group })
if (checked_group === '') checked_group = cbx.dataset.group
else if (checked_group !== cbx.dataset.group )
{
cbx.checked = false // you need to uncheck wrong group checkboxes for preserving checkedList
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
else if (checkedList.length === 0) // case of cheked repentir
clearGame()
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input data-group="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input data-group="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input data-group="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input data-group="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>
i want to get all of this input values to my budget app
but i have problem to get values of the radio button because it says its undefined. i create global function to get by radio button value. but the others is in javascript module.
https://jsfiddle.net/8k3gw7ty/
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
Actually there was no default value for your val variable. Since val will only get value when you click on the checkbox (according to your code).
Also you were returning val which isn't necessary. I've also removed the budgetController.
Hope this'll help.
let val = 'inc'; // default value
function getButtonValue() {
var type = document.getElementsByName("type");
if (type[0].checked) {
val = type[0].value
} else if (type[1].checked) {
val = type[1].value
}
}
const domController = (function() {
return {
getInput: function() {
return {
type: val,
description: document.querySelector(".input_description").value || 0,
value: parseFloat(document.querySelector(".input_value").value) || 0
}
}
}
})();
const controller = (function( UI) {
var ctrlAddItem = function() {
var input = UI.getInput();
console.log(input);
}
document.querySelector(".addbtn").addEventListener("click", ctrlAddItem)
document.addEventListener("keypress", function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
})( domController);
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
<button><i class="fas fa-check addbtn">Save</i></button>
Here is my radio buttons' code:
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>
and I want to get value of button in following script audio src, so by clicking on radio button I can switch between media folder:
function PlayVerse(surat,n) {
var aud=document.getElementById("myaudio");
aud.src= "http://data.quranacademy.com/AUDIOS/Media-/01_"
+TxtFormat(surat,"000")
+"_"
+TxtFormat(n,"000")
+".mp3";
}
var x = document.getElementsByTagName("IMG");
var i;
for (i = 0; i < x.length; i++) {
x[i].style = 'display: inline-block; '
+'border: 1px solid #ddd; '
+'border-radius: 4px; padding: 5px;';
}
Try something like this with plain javascript
function PlayVerse(){
var radio = document.getElementsByName('sp');
var check;
for (var i = 0, length = radio.length; i < length; i++)
{
if (radio[i].checked)
{
console.log(radio[i].value);
check = radio[i].value;
break;
}
}
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
if you want to do something by clicking on radio button it can help you
window.onload=function(){
(function (){
var radios = document.getElementsByName('sp');
radios.forEach(function(radio){
radio.onclick = function(){
alert(this.value);
//do something
}
})
})();
}
Red color
Yelow color
<p id="demo"></p>
<script>
function myFunction() {
//var x = document.getElementById("myRadioRed").value;
//document.getElementById("demo").innerHTML = x;
var radios = document.getElementsByName('colors');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
document.getElementById("demo").innerHTML = radios[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
}
</script>
<input type="radio" name="colors" value="red" id="myRadioRed" onchange="myFunction()" checked="checked" />Red color
<input type="radio" name="colors" value="yellow" id="myRadioYellow" onchange="myFunction()" />Yelow color
<p id="demo"></p>
function PlayVerse() {
var selected_radio_button_value = getRadioButtonValue("sp");
alert(selected_radio_button_value);
}
function getRadioButtonValue(elementName) {
var array1 = document.getElementsByName(elementName), rValue = null;
array1.forEach(function(element) {
if( element.checked ) {
rValue = element.value;
return true;
}
});
return rValue;
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
here you can get value of radio button using javascript i have created an function which will give you value of selected radio button you can store that value in variable and access it anywhere you want you can do it in both way
Here is how you can get value of radio button which one is checked. Get all NodeList by getElementsByName and iterate over each one and check if it is checked.
function getVal(elementName) {
var radios = document.getElementsByName(elementName), rValue = null;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
rValue = radios[i].value;
break;
}
}
console.log(rValue);
}
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>
Im using angular.
I have Three checkboxes in a Group and i want to make sure only one of them can be checked. So if one is checked the other two has to bee unchacked. I can Think of doing this several ways with native JS or jQuery but i want to know if there is a typical Angular way of doing it.
Here is Plunker with a set up of the checkboxes and angular controll.
http://plnkr.co/edit/IZmGwktrCaYNyrWjfSqf?p=preview
<body ng-controller="MainCtrl">
<div>
{{vm.Output}}
<br>
<br>
<br>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.changeGroupA()"> A1 </label>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.changeGroupA()"> A2 </label>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.changeGroupA()"> A3 </label>
<br>
<br>
<br> {{vm.Output}}
</body>
Since you can't use radio buttons, I've made this plnkr when you check one the others are deselected:
http://plnkr.co/edit/apSE3cIXA7DIvulBfNGX?p=preview
<label> <input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.a2 = false; vm.a3 = false; vm.changeGroupA()" > A1 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.a1 = false; vm.a3 = false; vm.changeGroupA()" > A2 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.a2 = false; vm.a1 = false; vm.changeGroupA()" > A3 </label>
Hope it helps =)
Edit: You can probably change the state of the other checkboxes in the controller for best practice, made in the html just to demonstrate more quickly..
Another way to do it would be: http://plnkr.co/edit/kH12pYkXfY6t6enrlSns
<br><br><br>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[0]" ng-change="vm.changeGroupA(0)" > A1 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[1]" ng-change="vm.changeGroupA(1)" > A2 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[2]" ng-change="vm.changeGroupA(2)" > A3 </label>
<br><br><br>
The controller would look like this:
$scope.vm = {
groupA: [false, true, false],
count : 0,
changeGroupA : function (index)
{
for (i = 0, len = this.groupA.length; i < len; ++i) {
this.groupA[i] = ((1 << index) & (1 << i)) > 0;
}
this.Output = '(' + this.count + ')' + this.Output;
this.count ++;
},
Output : 'Here we go'
}
You might want to do it the hard way out. http://plnkr.co/edit/A53w4IJMRXQmvRsxa8JA and it should work
changeGroupA : function (x)
{
if (x === 'A1'){
$scope.vm.a1 = true;
$scope.vm.a2 = false;
$scope.vm.a3 = false;
}
else if (x === 'A2') {
$scope.vm.a2 = true;
$scope.vm.a1 = false;
$scope.vm.a3 = false;
}
else if (x === 'A3') {
$scope.vm.a3 = true;
$scope.vm.a1 = false;
$scope.vm.a2 = false;
}
this.Output = '(' + this.count + ')' + this.Output;
this.count ++;
},
This works perfectly fine for angular 6 or 8
HTML:
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" class="custom-control-input" id="check1id"
[(ngModel)]="check1" (change)="onlyOneValue($event)"/>
<label for="check1id" class="custom-control-label">Checkbox 1</label>
</div>
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" class="custom-control-input" id="check2id"
[(ngModel)]="check2" (change)="onlyOneValue($event)" />
<label for="check2id" class="custom-control-label"> Checkbox 2 </label>
</div>
.ts code:
check1=false;
check2=false;
onlyOneValue(e)
{
if (e.target.id == "Check1id") {
this.Check1= true;
this.Check2 = false;
}
else if (e.target.id == "Check1id") {
this.Check1= true;
this.Check2 = false;
}
}
Why don't you just use a radio button?
<label>
<input type="radio" name="groupA" ng-model="vm.a1" ng-change="vm.changeGroupA()"> A1 </label>
<label>
<input type="radio" name="groupA" ng-model="vm.a2" ng-change="vm.changeGroupA()"> A2 </label>
<label>
<input type="radio" name="groupA" ng-model="vm.a3" ng-change="vm.changeGroupA()"> A3 </label>
I want to replace the after-submission checks in the form with on-the-fly completeness and correctness checks that are performed when a form field loses focus.
How can I do this?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<title>Form</title>
<style>
body {
width: 500px;
}
.part {
width: 100%;
padding: 5px;
border-bottom: 1px solid #000;
}
label {
margin-right: 5px;
}
.label-left {
text-align: right;
}
.label-right {
text-align: left;
}
.error {
color: #cc0000;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$(document).ready(function() {
function myValidateEMailAddress(email_address) {
var email_pattern = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email_pattern.test(email_address);
}
function checkPassword(pwd_str) {
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
return my_pwd_pattern.test(pwd_str);
}
function validatePhoneNumber(phone_number) {
var phone_pattern = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
return phone_pattern.test(phone_number);
}
$(document).ready(function() {
$('#form').submit(function(e) {
var my_errors = false;
$('.part> .error').remove();
$('#my_submission').empty();
$(':text, :password, textarea').each(function() {
$(this).val($.trim($(this).val()));
if ($(this).val() == '') {
$(this).parent().append('<div class="error">Please provide a value</div>');
my_errors = true;
}
});
if ($('#email').val() != '') {
if (!myValidateEMailAddress($('#email').val())) {
$('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
}
if ($('#your_password').val() != '') {
if (!checkPassword($('#your_password').val())) {
$('#your_password').parent().append('<div class="error">Please provide a correct password.</div>');
my_errors = true;
}
}
if ($('#phone').val() != '') {
if (!validatePhoneNumber($('#phone').val())) {
$('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>');
my_errors = true;
}
}
if ($('#addresses option:selected').val() == '') {
$('#addresses').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="sex"]:checked').length == 0) {
$(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="subscription"]:checked').length == 0) {
$(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($('#likes option:selected').val() == '') {
$('#likes').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if (my_errors) {
return false;
}
else {
e.preventDefault();
var my_submission_array = $('#form').serialize().split('&');
if (my_submission_array.length > 0) {
$('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
for (var i = 0; i < my_submission_array.length; i++) {
var my_pair = my_submission_array[i].split('=');
$('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\n');
}
}
}
});
});
// });
</script>
</head>
<body>
<h3>Output:</h3>
<h2>My Questionnaire</h2>
<form name="form" id="form" action="" method="post">
<div class="part">
<label for="addresses" class="label-left">How should you be addressed?</label>
<select name="addresses" id="addresses">
<option value="">Please select one</option>
<option value="first">Mr.</option>
<option value="second">Madam</option>
<option value="third">Miss</option>
<option value="fourth">Dr.</option>
<option value="fifth">Pr.</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Sex:</legend>
<input type="radio" name="sex" id="group1" value="1">
<label for="group1" class="label-right">Male</label>
<input type="radio" name="sex" id="group2" value="2">
<label for="group2" class="label-right">Female</label>
</fieldset>
</div>
<div class="part">
<label for="last_name" class="label-left">Last Name: </label>
<input type="text" name="last_name" id="last_name">
</div>
<div class="part">
<label for="first_name" class="label-left">First Name: </label>
<input type="text" name="first_name" id="first_name">
</div>
<div class="part">
<label for="email" class="label-left">E-Mail: </label>
<input type="text" name="email" id="email">
</div>
<div class="part">
<label for="your_password">Password:</label>
<input type="password" name="your_password" id="your_password" size="10" maxlength="20">
</div>
<div class="part">
<label for="phone" class="label-left">Phone number: </label>
<input type="text" name="phone" id="phone">
</div>
<div class="part">
<label for="likes" class="label-left">What are your likes?</label>
<select name="likes" id="likes">
<option value="">Please select one</option>
<option value="first">Programming</option>
<option value="second"> African literature</option>
<option value="third">Poetry</option>
<option value="four">Dancing</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Do you want to receive our newsletter ?</legend>
<input type="radio" name="subscription" id="group1" value="1">
<label for="group1" class="label-right">Yes</label>
<input type="radio" name="letter" id="group2" value="2">
<label for="group2" class="label-right">No</label>
</fieldset>
</div>
<div class="part">
<label for="comments" class="label-left">Write some comments below:</label>
<textarea name="comments" id="comments" cols="40" rows="3"></textarea>
</div>
<div class="part">
<input type="submit" name="submit" id="submit" value="Submit Form">
</div>
<div id="my_submission"></div>
</form>
</body>
</html>
Before I continue answering, I should note that you're putting jQuery script before <html> tag. This is incorrect. It has to be in <head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...
performed when a form field loses focus
An element loses focus when you click away from it. jQuery happends to have a blur event for this occasion:
$('input').on('blur', function() {
// your code here
});
So you might want to do it this way:
$('#email').on('blur', function() {
var emailVal = $(this).val();
if (!emailVal || !myValidateEMailAddress(emailVal)) {
$(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
});
the rest of the code might look similar.