I have a bootstrap form that I'd like to validate using Javascript by clicking on a link (NOT submit button). Here's my sample code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<style>
/* ==========================================================================
Demo using Bootstrap 3.3.4 and jQuery 1.11.2
You don't need any of the following styles for the form to work properly,
these are just helpers for the demo/test page.
========================================================================== */
#wrapper {
width:595px;
margin:0 auto;
}
legend {
margin-top: 20px;
}
#attribution {
font-size:12px;
color:#999;
padding:20px;
margin:20px 0;
border-top:1px solid #ccc;
}
#O_o {
text-align: center;
background: #33577b;
color: #b4c9dd;
border-bottom: 1px solid #294663;
}
#O_o a:link, #O_o a:visited {
color: #b4c9dd;
border-bottom: #b4c9dd;
display: block;
padding: 8px;
text-decoration: none;
}
#O_o a:hover, #O_o a:active {
color: #fff;
border-bottom: #fff;
text-decoration: none;
}
#media only screen and (max-width: 620px), only screen and (max-device-width: 620px) {
#wrapper {
width: 90%;
}
legend {
font-size: 24px;
font-weight: 500;
}
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
</script>
<script type="text/javascript" src="<?php echo base_url('scripts/js/validator.min.js'); ?>"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <!-- only added as a smoke test for js conflicts -->
</head>
<body>
<div id="wrapper">
<form data-toggle="validator" role="form" id="form" name="extra" value="me">
<div id="entry1" class="clonedInput">
<h2 id="reference" name="reference" class="heading-reference">Entry #1</h2>
<fieldset>
<!-- Select Basic -->
<label class="label_ttl control-label" for="title">Title:</label>
<!-- Text input-->
<div class="form-group">
<label class="label_fn control-label" for="first_name">First name:</label>
<input id="first_name" name="first_name" type="text" placeholder="" class="form-control" required>
<p class="help-block">This field is required.</p>
</div>
</div><!-- end #entry1 -->
<!-- Button -->
<p>
Submit
</p>
</fieldset>
</form>
</div> <!-- end wrapper -->
<script>
function myFunction(){
$('#form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
}
})
}
</script>
</body>
</html>
Am using this lib for validation
http://1000hz.github.io/bootstrap-validator/#validator-usage
I need 'onclick' to fire up the JS function and run validation which should give me a true(i.e pass) or false(i.e fail).
Note: Am a complete noob in JS and am essentially trying to cobble up this so that it works for me.
You could call a function on click of the link such as:
function myFunction(){
$("#form").submit(function() {
$(this).validator(function(e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
}
});
});
}
Source: https://api.jquery.com/submit/
I'd recommend using query validate (http://jqueryvalidation.org). It has lots options and works very well with bootstrap. You can also check fields before submission using valid() method or perform validation using validate() method.
Here is a quick example https://jsfiddle.net/Lu165LLt/1/
<form id="myform" class="container">
<div class="form-group">
<label class="control-label" for="name">Name</label>
<input type="text" name="name" class="form-control" required />
</div>
<a>Validate!</a>
</form>
$.validator.setDefaults({
debug: true,
success: "valid"
});
var form = $("#myform");
form.validate();
$("a").click(function () {
alert("Valid: " + form.valid());
});
Libraries Used:
jQuery,jQuery Validate,Bootstrap
Related
I have three tooltip buttons on a page. I can close any open tooltip by clicking anywhere outside buttons. And this is what I came across:
In the code below, when I click on any place on the page, the handler of this part of code is activated $(document).on('click', (event) => this.closeOnOutsideClick(event));
I can see in inspector, that function closeOnOutsideClick is fired three times - it makes three checks for each tooltip button present on the page. I cannot figure out what mechanism is responsible for that and why the check if (!$(event.target).closest(this.$elem)) is not performed only once? My code can be found here and also below: https://jsfiddle.net/bakrall/786cz40L/
This is a simplified version of a more complex code just to give example of my issue:
const selectors = {
tooltip: '.tooltip-container',
tooltipButton: '.tooltip-button',
tooltipMessage: '.tooltip-message'
}
class Tooltip {
constructor(tooltip) {
this.$elem = $(tooltip);
this.$tooltipButton = this.$elem.find(selectors.tooltipButton);
this.$tooltipMessage = this.$elem.find(selectors.tooltipMessage);
this.$tooltipMessageText = this.$tooltipButton.attr('data-tooltip-content');
this.bindUiEvents();
}
bindUiEvents() {
$(document).on('click', (event) => this.closeOnOutsideClick(event));
this.$tooltipButton.on('click', () => this.showTooltipMessage());
this.$tooltipButton.on('blur', () => this.hideTooltip());
}
showTooltipMessage() {
this.$tooltipMessage
.text(this.$tooltipMessageText)
.addClass('shown-message');
}
hideTooltip() {
this.$tooltipMessage
.text('')
.removeClass('shown-message');
}
closeOnOutsideClick(event) {
if (!$(event.target).closest(this.$elem)) {
this.hideTooltip();
}
}
}
//class in another file
const tooltip = $('.tooltip-container');
tooltip.each(function(index, item) {
new Tooltip(item);
})
.input-wrapper {
margin-bottom: 2em;
}
.tooltip-container {
position: relative;
display: inline-block;
}
.tooltip-message {
display: none;
position: absolute;
left: 100%;
top: 0;
width: 10em;
padding: 0.5rem;
background: #000;
color: #fff;
}
.tooltip-message.shown-message {
display: inline-block;
}
button {
width: 1.2em;
height: 1.2em;
border-radius: 50%;
border: 0;
background: #000;
font-family: serif;
font-weight: bold;
color: #fff;
}
button:focus {
outline: none;
box-shadow: 0 0 0 0.25rem skyBlue;
}
input {
display: block;
}
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title> </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="tooltip.css">
</head>
<body>
<div class="input-wrapper">
<label for="name">
What's your name?
<span class="tooltip-container">
<button class="tooltip-button" type="button" aria-label="more info"
data-tooltip-content="This clarifies whatever needs clarifying">i</button>
<span class="tooltip-message" role="status"></span>
</span>
</label>
<input id="name" type="text"/>
</div>
<div class="input-wrapper">
<label for="age">
What's your age?
<span class="tooltip-container">
<button class="tooltip-button" type="button" aria-label="more info"
data-tooltip-content="This is to know how old you are">i</button>
<span class="tooltip-message" role="status"></span>
</span>
</label>
<input id="age" type="text"/>
</div>
<div class="input-wrapper">
<label for="nationality">
What's your nationality
<span class="tooltip-container">
<button class="tooltip-button" type="button" aria-label="more info"
data-tooltip-content="What country are you from?">i</button>
<span class="tooltip-message" role="status"></span>
</span>
</label>
<input id="nationality" type="text"/>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script src="tooltip.js" async defer></script>
</body>
</html>
tooltip.each(function(index, item) {
new Tooltip(item);
})
Since you instantiate 3 Tooltips, you bind a separate event listener to the document each time. Each listener is getting triggered with each click. However, each of those listeners has a different this which is what allows each listener to tell if its Tooltip was clicked and if not, hide it.
If you want a single listener you could store a list of all your Tooltips and have the event listener iterate through the list of Tooltips, closing all Tooltips that were not clicked.
Your click event is firing on mutliple elements, because you specified just (document). Maybe you can be more specific:
$(document).on('click', '.input-wrapper', (event) => this.closeOnOutsideClick(event));
Here is the following code which is not working to show error message when submitted.
The problem is that the error message is not displayed properly when clicked once but if you give multiple clicks it works.
Help will be appreciated.
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>JavaScript form validation - checking all letters</title>
<style type="text/css">
li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}
</style>
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Enter your Name and Submit</h2>
<form name="form1" action="#">
<ul>
<li>
Code:
</li>
<li id="myList">
<input type='text' name='text1'/>
<p id="error"></p>
</li>
<li class="rq">
*Enter alphabets only.
</li>
<li> </li>
<li>
<input type="submit" name="submit" value="Submit" onclick="allLetter(document.form1.text1)" />
</li>
<li> </li>
</ul>
</form>
</div>
<script type="text/javascript">
function allLetter(inputtxt) {
var letters = /^[A-Za-z]+$/;
if(inputtxt.value.match(letters)) {
document.getElementById("error").innerHTML="error here";
return false;
} else {
document.getElementById("error").innerHTML="success";
return true;
}
}
</script>
</body>
</html>
Your problem and solution is quite simple.
When you click the form button, the form automatically submits itself and that's why you see nothing.
Add this to your button code so you can prevent the default functionality of the submit input:
<input type="submit" name="submit" value="Submit" onclick="allLetter(document.form1.text1);return false" />
That should solve it:
You should to use event.preventDefault method to prevent the page refresh.
So, your function should look like this:
function allLetter(event) {
event.preventDefault();
var letters = /^[A-Za-z]+$/;
if (document.form1.text1.value.match(letters)) {
document.getElementById("error").innerHTML="error here";
//return false;
} else {
document.getElementById("error").innerHTML="success";
return true;
}
}
It should be called in the following way:
<input type="submit" name="submit" value="Submit" onclick="allLetter(event)" />
Having some trouble with the YouTube API and hoping someone can help.
Here's my code:
HTML
<!doctype html>
<html lang="en">
<head>
<title>Video App</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Viral Videos App" />
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>
<h1 class="w100 text-center">Video </h1>
</header>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="#">
<p><input type="text" id="Search" placeholder="Type here..." autocomplete="off" class="form-control" /></p>
<p><input type="submit" value="Search" class="form-control btn btn-primary w100"></p>
</form>
<div id="results"></div>
</div>
</div>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/app.js"></script>
<script src="https://apis.google.com/js/client.js?onload=init"> </script>
</body>
</html>
And here is my CSS
body { background: #1B2836; }
header { margin-top:30px; }
header a { color: #01FFBE; text-decoration: none; }
header a:hover { text-decoration: none; }
form { margin-top: 20px; }
form, #results {padding: 0 20px; }
.item { margin-bottom: 25px; }
.w100 { width: 100%; }
.btn-primary { background: #01FFBE; border-color: #00C693; }
.btn-primary:hover, .btn-primary:active, .btn-primary:focus { background: #00C693; border color: #00C693; }
And here is my Javascript
$(function() {
$("form").on("submit", function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
publishedAfter: "2015-01-01T00:00:00Z"
});
// execute the request
request.execute(function(response) {
var results = response.result;
$.each(results.items, function(index, item) {
console.log(item);
});
});
});
});
function init() {
gapi.client.setApiKey("AIzaSyDnp3yk0p6yWqpcK2iggS1WkwXMyEFYVvI");
gapi.client.load("youtube", "v3", function() {
//yt api is ready
});
}
It appears fine in my live preview and I can type and search but then I hit an error if I open the console.
I want to use radio button in my form. I am using AngularJS to create my form. But i want image instead of radio button. I am able to hide the radio button by adding css
position: absolute;
left: -9999px;
But the problem with this is it's disabling the checked event. Is there any way to make image clickable.
Here is my code:
var app = angular.module("MyApp", []);
app.controller('MyCtrl', function($scope, $timeout) {
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
console.log(myform);
}
};
$scope.sliderValue = null;
$scope.name = '';
$scope.data = {
singleSelect: null,
multipleSelect: [],
option1: 'option-1',
};
$scope.forceUnknownOption = function() {
$scope.data.singleSelect = 'nonsense';
};
});
<!DOCTYPE html>
<html ng-app="MyApp" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body ng-controller="MyCtrl">
<form name='myform' id="myform" ng-init="step = 1" ng-submit="submitForm(myform.$valid)">
<div ng-show="step==1">
<h3>Which step</h3>
<div ng-form='step1form'>
<input type="radio" name="step" ng-model="data.step" value="11" ng-disabled="!step1form.$valid" ng-click="step = 2">
<img src="http://sstatic.net/stackoverflow/img/favicon.ico" style="width:50px" alt="Save icon"/>
<p class="Text">
Step 2
</p>
</div>
</div>
<div ng-show="step==2">
<div ng-form='step2form'>
<div ng-disabled="!step2form.$valid"><span>Finish</span></div>
</div>
</div>
</form>
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
You need to associate a label with your radio input and style that with your image. You can see in this demo that, when you style the label it acts in place of the input
$(document).ready(function() {
$('input').click(function() {
alert($('input').val());
});
});
label.radioLabel {
background: pink;
cursor: pointer;
display: inline-block;
height: 50px;
width: 50px;
}
input[type=radio] {
position: absolute;
top: 0;
left: -9999px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>No label</h1>
<input type="radio" name="step">
<h1>Label Wrapped Around</h1>
<label class="radioLabel">
<input type="radio" name="step">
</label>
<h1>Label With "For"</h1>
<input type="radio" id="step" name="step">
<label class="radioLabel" for="step"></label>
Obviously use your own styles on the label, but I recommend keeping cursor:pointer; so the interaction is apparent to your users.
try this
<label>
<input type="radio" name="step" ng-model="data.step" value="11" ng-disabled="!step1form.$valid" ng-click="step = 2">
<img src="http://sstatic.net/stackoverflow/img/favicon.ico" style="width:50px" alt="Save icon"/>
</label>
css:
label > input{ /* HIDE RADIO */
display:none;
}
label > input + img{ /* IMAGE STYLES */
cursor:pointer;
border:2px solid transparent;
}
label > input:checked + img{ /* (CHECKED) IMAGE STYLES */
border:2px solid #f00;
}
https://jsbin.com/modotayufe/edit?html,css,js,output
The trick is to wrap the input with label so when you click on it it's like you clicked on the radio button. In the label, put a span tag so you can set his background to your image.
In the below snippet you can see this in action. (I commented the ng-change attribute so you can see the effect)
var app = angular.module("MyApp", []);
app.controller('MyCtrl', function($scope, $timeout) {
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
console.log(myform);
}
};
$scope.sliderValue = null;
$scope.name = '';
$scope.data = {
singleSelect: null,
multipleSelect: [],
option1: 'option-1',
};
$scope.forceUnknownOption = function() {
$scope.data.singleSelect = 'nonsense';
};
});
input[type="radio"] {
display:none;
}
input[type="radio"] + span {
content:"";
background:url(http://i.stack.imgur.com/hlkG5.png);
width:30px;
height:30px;
display:inline-block;
}
input[type="radio"]:checked + span {
background-image:url(http://i.stack.imgur.com/TwN4q.png);
}
<!DOCTYPE html>
<html ng-app="MyApp" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body ng-controller="MyCtrl">
<form name='myform' id="myform" ng-init="step = 1" ng-submit="submitForm(myform.$valid)">
<div ng-show="step==1">
<h3>Which step</h3>
<div ng-form='step1form'>
<label>
<input type="radio" name="step" ng-model="data.step" value="11" ng-disabled="!step1form.$valid"><!--ng-click="step = 2"-->
<span></span>
</label>
<img src="http://sstatic.net/stackoverflow/img/favicon.ico" style="width:50px" alt="Save icon"/>
<p class="Text">
Step 2
</p>
</div>
</div>
<div ng-show="step==2">
<div ng-form='step2form'>
<div ng-disabled="!step2form.$valid"><span>Finish</span></div>
</div>
</div>
</form>
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
I used awesome icons. You can do it like this:
<label class="hideRadio">
<input class="" type="radio" value="" name="">
<i class="fa fa-check-circle "></i>
</label>
and use this css:
.hideRadio input {
visibility: hidden; /* Makes input not-clickable */
position: absolute; /* Remove input from document flow */
}
I have the following ColdFusion page (below). I have jQueryTools validation running. It works perfectly fine from a traditional submit button, but I need it to work from the a href link, formatted as a button ( little further down in the code). I can't seem to figure out how to get the a href link that normally submits the form to fire an action that will cause the page to validateV BEFORE submitting the form.
My Javascript skills appear to be very basic. Any help would be greatly appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><cfoutput>Welcome to#application.settings.meta_title#</cfoutput></title>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
<link rel="stylesheet" href="/common/ext/jQuerytools/form.css" type="text/css" media="all" />
<style>
/* error container */
#errors {
background-color: #163356;
color: #fff;
width: 400px;
padding: 20px;
margin: 5px auto;
display: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
/* title */
#errors h2 {
margin: -5px 0;
color: yellow;
}
</style>
</head>
<body onLoad="self.focus();">
<h1>Pre Incident Plans Editor</h1>
<!--- BEGIN MAIN CONTENT AREA --->
<div id="main">
<div id="leftcol">
<form action="" method="POST" name="form2" id="form2">
<label for="addr_street">Address<br>
<input type="text" name="addr_number" id="Street Number" value="" style="width:50px;display:inline" placeholder="Number" required >
<input type="text" name="addr_street" id="Street Name" value="" size="32" placeholder="Street Name" style="display:inline" required />
<span class="field_instructions">Provide the street address that will match the CAD information</span> </label>
<label for="occ_name">
Occupancy Name<br>
<input type="text" name="occ_name" value="" style="width:100%" placeholder="Occupancy Name"/>
<input type="submit" name="button" id="button" value="Submit" class="button green medium">
</form>
</div>
<div id="rightcol">
<div id="publishingcontrols">
<h2>Publishing Controls</h2>
<div align="center"> Save </div>
<div id="errors">
<h2>Please fix these first</h2>
</div>
</div>
</div>
<script>
// adds an effect called "wall" to the validator
$.tools.validator.addEffect("wall", function(errors, event) {
// get the message wall
var wall = $(this.getConf().container).fadeIn();
// remove all existing messages
wall.find("p").remove();
// add new ones
$.each(errors, function(index, error) {
wall.append(
"<p><strong>" +error.input.attr("id")+ "</strong> " +error.messages[0]+ "</p>"
);
});
// the effect does nothing when all inputs are valid
}, function(inputs) {
});
// initialize validator with the new effect
$("#form2").validator({
effect: 'wall',
container: '#errors',
// do not validate inputs when they are edited
errorInputEvent: null
// custom form submission logic
}).submit(function(e) {
});
</script>
</body>
</html>
Add this to fire validator without a submit button:
var $validator= $("#form2").data("validator");
$validator.checkValidity();