Struggling to pull YouTube videos using api - javascript

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.

Related

How to add a form/input/text to end of fetch() request?

Im building a random DogAPI image generator, where you put a number from 1-50 into a form text box, and hit send, and it returns the number you input into (linked) images printed to the console. I can manually put the number at the end of fetch, and it prints that amount to the console, but I'm having trouble connecting the number you put in your form to put it on the end of your fetch request.
Ive tried using template literals. If you manually type ${5} at the end of fetch, it prints 5 images to console. Great! But... how do I use Template Literals to connect what I put in the form to the end of the fetch. ${text} obviously doesn't work! Or am I doing it all wrong? Thanks for your help everyone!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>How Many?</title>
<link rel="shortcut icon" href="#">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>How Many Dog Pics Do You Want?</h1>
<form>
<input type="text" placeholder="1-50?">
<input type ="submit" value="Send">
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
CSS:
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
}
JS:
'use strict';
function getDogImage() {
fetch(`https://dog.ceo/api/breeds/image/random/${text}`)
.then(response => response.json())
.then(responseJson => console.log(responseJson));
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
getDogImage();
});
}
$(function() {
console.log('App loaded! Waiting for submit!');
watchForm();
});
You need to get the value from the input (using .val()), and pass it to getDogImage(text) (see comments in code):
function getDogImage(text) { // add the text parameter
fetch(`https://dog.ceo/api/breeds/image/random/${text}`)
.then(response => response.json())
.then(responseJson => console.log(responseJson));
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
var text = $('.number').val() || 3; // get the text from the input or use 3
getDogImage(text); // pass to getDogImage
});
}
$(function() {
console.log('App loaded! Waiting for submit!');
watchForm();
});
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h1>How Many Dog Pics Do You Want?</h1>
<form>
<input class="number" type="text" placeholder="1-50?">
<input type="submit" value="Send">
</form>
</div>

How do I get an alert or error message to display in my app if the api is unable to locate the breed name passed in by the user

function getDogImage(breed) {
fetch(`https://dog.ceo/api/breed/${breed}/images/random`)
.then(response => response.json())
.then(responseJson =>
displayResults(responseJson))
.catch(error => alert('Something went wrong. Try again later.'));
}
function displayResults(responseJson) {
console.log(responseJson);
//replace the existing image with the new one
$('.results-img').replaceWith(
`<img src="${responseJson.message}" class="results-img">`
)
//display the results section
$('.results').removeClass('hidden');
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
getDogImage($('#breed').val());
});
}
$(function() {
console.log('App loaded! Waiting for submit!');
watchForm();
});
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
}
.hidden {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dog API Example</title>
<link rel="shortcut icon" href="">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>Dog API: A Simple Example</h1>
<form>
<label for="breed">Breed</label>
<input type="search" name="phone" id="breed" placeholder="Enter Breed" title="dog breeds" required/>
<input type="submit" value="Get a dog pic!">
</form>
<section class="results hidden">
<h2>Look at this dog!</h2>
<img class="results-img" alt="placeholder">
</section>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
How do I get an alert or error message to display in my app if the api is unable to locate the breed name passed in by the user. At the moment a broken image link is displayed when passing in a non-valid breed name. Also im new to programming just here trying to learn from experienced developers
Heres a link to my code
https://repl.it/#Mike65/get-fetch-dog-api-example-DOM-3
img tag has onerror event, you can call alert function on that event like this
HTML
<img src=`${response.message}` class='result-img' onerror="myAlert()" />
Javascript
function myAlert() { alert("the image could not load"); }
JQuery
$('.results-img').replaceWith(
`<img src="${responseJson.message}" class="results-img">`
).on("error", function() { alert("the image could not load"); }

Common function for validation using jquery

I am using simple code to validate whether input box is empty or not and just showing check icon and warning icon accordingly.
You can see working PLUNKER here.
Problem: This set of code works fine for one set of Label:Input Box.
Imagine if we have number of input control throughout the website.
I am looking for a solution which is quite generalized. No need to repeat same set of HTML, CSS or JS code over and over again.
I know its hard to avoid some duplication but wanna write less repetitive code.
// Code goes here
$(document).ready(
function() {
$("#icon-id").hide();
$("#input-id").keyup(function() {
if ($("#input-id").val().length === 0) {
$("#input-id").addClass("redBorder");
$("#icon-id").addClass("icon-warning-sign");
$("#icon-id").removeClass("icon-check");
$("#icon-id").css("color", "red");
$("#icon-id").show();
} else {
$("#input-id").removeClass("redBorder");
$("#icon-id").removeClass("icon-warning-sign");
$("#icon-id").addClass("icon-check");
$("#icon-id").css("color", "green");
$("#icon-id").show();
}
});
});
body {
margin: 20px;
}
.input-container {
width: 250px;
position: relative;
}
.my-input {
width: 100%;
}
.my-icon {
position: absolute;
right: 0px;
color: red;
top: 8px;
}
.redBorder {
border: 1px solid red !important;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body style="margin-top:55px;">
<!-- validation check -->
<div id="header" style="margin-bottom:20px;">
<div id="validate-click">Enter Below</div>
</div>
<!-- input contianre -->
<div class="form-group input-container">
<input id="input-id" type="text" class="my-input" placeholder="Enter here">
<i id="icon-id" class="icon-warning-sign my-icon"></i>
</div>
</html>
Note: Please don't refer any third party control.
You can use class selector instead id for the input. And use an data attribute to select the good icon.
live demo
You can see an example below :
function() {
$(".icon-class").hide();
$(".input-class").keyup(function() {
var idIcon = $(this).attr('data-id-icon');
if ($(this).val().length === 0) {
$(this).addClass("redBorder");
$("#" + idIcon).addClass("icon-warning-sign");
$("#" + idIcon).removeClass("icon-check");
$("#" + idIcon).css("color", "red");
$("#" + idIcon).show();
} else {
$(this).removeClass("redBorder");
$("#" + idIcon).removeClass("icon-warning-sign");
$("#" + idIcon).addClass("icon-check");
$("#" + idIcon).css("color", "green");
$("#" + idIcon).show();
}
});
}
<input data-id-icon="icon-id-1" type="text" class="my-input input-class" placeholder="Enter here">
<i id="icon-id-1" class="icon-warning-sign my-icon"></i>
<input data-id-icon="icon-id-2" type="text" class="my-input input-class" placeholder="Enter here">
<i id="icon-id-2" class="icon-warning-sign my-icon-2"></i>
Make it a jQuery plugin: https://jsfiddle.net/1nxtt0Lk/
I added the attribute data-validate to your <input />s so I can call the plugin on them using $('[data-validate']).
Code:
;( function( $, window, document, undefined ) {
"use strict";
var pluginName = "customValidator",
defaults = {
propertyName: "value"
};
function Plugin ( element, options ) {
this.element = element;
this.settings = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend( Plugin.prototype, {
init: function() {
var $input = $(this.element);
var $icon = $input.parent().find('.my-icon');
$icon.hide();
$input.keyup(function() {
if ($input.val().length === 0) {
$input.addClass("redBorder");
$icon.addClass("icon-warning-sign");
$icon.removeClass("icon-check");
$icon.css("color", "red");
$icon.show();
console.log("empty");
} else {
$input.removeClass("redBorder");
$icon.removeClass("icon-warning-sign");
$icon.addClass("icon-check");
$icon.css("color", "green");
$icon.show();
console.log("Not empty");
}
});
},
} );
$.fn[ pluginName ] = function( options ) {
return this.each( function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" +
pluginName, new Plugin( this, options ) );
}
} );
};
} )( jQuery, window, document );
$('[data-validate]').customValidator();
body {
margin: 20px;
}
.input-container {
width: 250px;
position: relative;
}
.my-input {
width: 100%;
}
.my-icon {
position: absolute;
right: 0px;
color: red;
top: 8px;
}
.redBorder {
border: 1px solid red !important;
}
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
<link rel="stylesheet" href="style.css" />
</head>
<div class="form-group input-container">
<input id="input-id" type="text" class="my-input" placeholder="Enter here" data-validate>
<i id="icon-id" class="icon-warning-sign my-icon"></i>
</div>
<div class="form-group input-container">
<input id="input-id2" type="text" class="my-input" placeholder="Enter here" data-validate>
<i id="icon-id2" class="icon-warning-sign my-icon"></i>
</div>
PS: I used the plugin boilerplate as a base script: https://github.com/jquery-boilerplate/jquery-boilerplate ;
a commented version can be found here https://raw.githubusercontent.com/jquery-boilerplate/jquery-boilerplate/master/dist/jquery.boilerplate.js
Other answer suggest to use a class selector to iterate over each of them. Although that solution definitely would work, I suggest to get used to write jQuery plugins as in the long term it makes your project much more clean and easy to read.
// Code goes here
$(document).ready(
function() {
$(".icon-id").hide();
$(".input-id").keyup(function() {
if ($(this).val().length === 0) {
$(this).addClass("redBorder");
$(this.parentElement).find("#icon-id").addClass("icon-warning-sign");
$(this.parentElement).find("#icon-id").removeClass("icon-check");
$(this.parentElement).find("#icon-id").css("color", "red");
$(this.parentElement).find("#icon-id").show();
} else {
$(this).removeClass("redBorder");
$(this.parentElement).find("#icon-id").removeClass("icon-warning-sign");
$(this.parentElement).find("#icon-id").addClass("icon-check");
$(this.parentElement).find("#icon-id").css("color", "green");
$(this.parentElement).find("#icon-id").show();
}
});
});
body {
margin: 20px;
}
.input-container {
width: 250px;
position: relative;
}
.my-input {
width: 100%;
}
.my-icon {
position: absolute;
right: 0px;
color:red;
top: 8px;
}
.redBorder{
border: 1px solid red !important;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body style="margin-top:55px;">
<!-- validation check -->
<div id="header" style="margin-bottom:20px;">
<div id="validate-click">Enter Below</div>
</div>
<!-- input contianre -->
<div class="form-group input-container">
<input id="input-id" type="text" class="my-input input-id" placeholder="Enter here">
<i id="icon-id" class="icon-warning-sign my-icon icon-id"></i>
</div>
<div class="form-group input-container">
<input id="input-id" type="text" class="my-input input-id" placeholder="Enter here">
<i id="icon-id" class="icon-warning-sign my-icon icon-id"></i>
</div>
</body>
</html>
You can try like this
You can use the classes my-input and my-icon instead of the ids.
Inside the keyup listener you can use $(this) to refer to my-input and $(this).next() to refer to my-icon as the icon is the adjacent sibling of the input.
Also chain your functions like this for brevity:
$(this).next().removeClass("icon-warning-sign")
.addClass("icon-check")
.css("color", "green")
.show();
See demo below:
// Code goes here
$(document).ready(function() {
$(".my-icon").hide();
$(".my-input").keyup(function() {
if ($(this).val().length === 0) {
$(this).addClass("redBorder");
$(this).next().addClass("icon-warning-sign")
.removeClass("icon-check")
.css("color", "red")
.show();
} else {
$(this).removeClass("redBorder");
$(this).next().removeClass("icon-warning-sign")
.addClass("icon-check")
.css("color", "green")
.show();
}
});
});
body {
margin: 20px;
}
.input-container {
width: 250px;
position: relative;
}
.my-input {
width: 100%;
}
.my-icon {
position: absolute;
right: 0px;
color: red;
top: 8px;
}
.redBorder {
border: 1px solid red !important;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
</head>
<body style="margin-top:55px;">
<!-- validation check -->
<div id="header" style="margin-bottom:20px;">
<div id="validate-click">Enter Below
</div>
</div>
<!-- input contianre -->
<div class="form-group input-container">
<input id="input-id" type="text" class="my-input" placeholder="Enter here">
<i id="icon-id" class="icon-warning-sign my-icon"></i>
</div>
</html>
$(document).ready(
function() {
$(".my-input").keyup(function() {
var $input = $(this).parent().find('input');
var $icon = $(this).parent().find('i');
if ($(this).val().length === 0) {
$input.addClass("redBorder");
$icon.addClass("icon-warning-sign").removeClass("icon-check").css("color", "red").show();
} else {
$input.removeClass("redBorder");
$icon.removeClass("icon-warning-sign").addClass("icon-check").css("color", "green").show();
}
});
});
body {
margin: 20px;
}
.input-container {
width: 250px;
position: relative;
}
.my-input {
width: 100%;
}
.my-icon {
position: absolute;
right: 0px;
color: red;
top: 8px;
display: none;
}
.redBorder {
border: 1px solid red !important;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body style="margin-top:55px;">
<!-- validation check -->
<div id="header" style="margin-bottom:20px;">
<div id="validate-click">Enter Below
</div>
</div>
<!-- input contianre -->
<div class="form-group input-container">
<input type="text" class="my-input" placeholder="Enter here">
<i class="icon-warning-sign my-icon"></i>
</div>
<div class="form-group input-container">
<input type="text" class="my-input" placeholder="Enter here">
<i class="icon-warning-sign my-icon"></i>
</div>
</html>

Image as a Radio button

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 */
}

Bootstrap form validation with Javascript

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

Categories