The page will strangely refresh when I click the button - javascript

Here's my code:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>中国工程院无线投票系统</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="container" id="login">
<div class="col-md-6 col-md-offset-3">
<div class="page-header">
<h1>中国工程院无线投票系统</h1>
</div>
<form>
<div class="form-group">
<label>用户名</label>
<div class="input-group">
<div class="input-group-addon"><i class="glyphicon glyphicon-user"></i></div>
<input type="text" v-model="account.username" class="form-control" placeholder="Username" required
autofocus>
</div>
</div>
<div class="form-group">
<label>密码</label>
<div class="input-group">
<div class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></div>
<input type="password" v-model="account.password" class="form-control" placeholder="Password"
required>
</div>
</div>
<button v-on:click="validate" class="btn btn-lg btn-primary btn-block">登录</button>
</form>
</div>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios#0.12.0/dist/axios.min.js"></script>
<script src="js/login.js"></script>
</body>
</html>
In the login.js file:
var login = new Vue({
el:"#login",
data:{account:{}},
methods:{
validate:function () {
},
say: function (){
}
}
});
At the beginning, I thought it had something to do with the code within method "validate". However, after I deleted all the code inside, the page still get refreshed when I click the button which is not supposed to happen.

You should add type="button" to your <button>.
If you don't specify a type of a <button> in a <form>, it will behave like a submit button by default, which refreshes the page.
Docs:
<type="submit"> The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.

Or you can do it the vuejs way using Event modifiers like this:
<button v-on:click.prevent="validate" class="btn btn-lg btn-primary btn-block">登录</button>
The prevent event modifier prevents the default behaviour.
Its just like using event.preventDefault() inside your event handler

Add #submit.prevent to your form.
<form #submit.prevent>
....
</form>

When using a form element, the submit action refreshes the page unless you specify return false; at the end of the onsubmit attribute. I believe you are having the same issue here.
Try putting a semicolon at the end of your onclick attribute (before the quote), then type return false; and it should solve your problem.

Related

off FUNCTION jquery

I am trying to make a validation form in a .php file , so it works in a way that once the field validation is done the form gets submitted . My form although is getting submitted but for that I need to press the submit button twice . Below is the code , the problem is mainly in the script section.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title></title>
<style type="text/css">
.container{
margin-top: 20px;
width: 500px;
}
#content{
resize: none;
}
#success{
display: none;
}
#failure{
display: none;
}
</style>
<body>
<div class="container">
<h1 class="display-3">Get in Touch</h1>
<div class="alert alert-danger" role="alert" id="failure">
</div>
<div class="alert alert-success" role="alert" id="success">
<strong>Well done!</strong> We will get back to you ASAP.
</div>
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control" id="content" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>
<script type="text/javascript">
$( "form" ).submit(function( event ) {
event.preventDefault();
var missing="";
if($("#email").val()=="")
{
missing=missing+"<p>Email is Missing</p><br>"
}
if($("#content").val()=="")
{
missing=missing+"<p>Content is Missing</p><br>"
}
if($("#subject").val()=="")
{
missing=missing+"<p>Subject is Missing</p><br>"
}
if(missing!="")
{
$("#failure").html(" <strong>Oh snap!</strong><br>."+missing);
$("#failure").show();
}
else{
$("#failure").hide();
$("form").off("submit").submit(); <- Problematic line
}
});
</script>
</body>
</html>
The issue is here:
$("form").off("submit").submit()
Instead of this, use preventDefault to hold the form submit to check the validation, and when validation succeed submit the form using:
$("form").submit();
.off only removes events that were added using .on. It doesn't remove native events or anything like that.
You're already using event.preventDefault() to stop the native form submission, which is correct.
Therefore simply $("form").submit(); should be sufficient to submit the form programmatically, once your validation is complete.
P.S. I assume you are validating your form on the server (PHP) side as well? JavaScript validation is nice for enhanced user experience but you cannot rely on it, as a malicious user (or bot) can easily change by manipulating the page source, or just ignore it entirely and post to your URL. If you value the integrity of your server and your data you must always validate forms on the server side as well.
Instead of $("form").off("submit").submit(); you can use this.submit();
Try to switch the order of the 2 functions:
$("form").submit().off("submit");

ng-repeat elements are not showing up

In my application I'm making a get request through Angular's http service and in the view looping over the returned data to show an unordered list. But the problem is even though data is available after the get request , its not getting dispplyed on the page. Seems to be a CSS style problem, but don't know how to fix it. I want to show the unorder list within a bootstrap panel as a body.
Below is the angular piece of code inside the controlller for setting up the data
$http.get('/messages').success(function(data) {
console.log("Messages are "+data);
$scope.records=data;
});
Here is the html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Bootstrap News plugin</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="/libs/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/libs/css/font-awesome.min.css"/>
<link rel="stylesheet" href="/libs/css/custom.css"/>
<script src="/libs/js/jquery-3.0.0.min.js" type="text/javascript"></script>
<script src="/libs/js/newsbox.min.js" type="text/javascript"></script>
<script src="/libs/js/angular.min.js" type="text/javascript"></script>
<script src="/libs/js/main.js" type="text/javascript"></script>
</head>
<body ng-app="mean" ng-controller="MainCtrl">
<br/>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-list-alt"></span><b> What you wanna do before you die ...</b>
</div>
<div ng-cloak class="panel-body">
<div class="row">
<div class="col-xs-12">
<ul class="demo1">
<li class="news-item" ng-repeat="item in records">
<table cellpadding="4">
<tr>
<td >
<img class="img-circle" width="60"
ng-src="/images/{{($index+11) % 10}}.png"/>
</td>
<td ng-cloak>
{{$index+1}}. {{item.username}}
</td>
</tr>
</table>
</li>
</ul>
</div>
</div>
</div>
<div class="panel-footer"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-2 col-md-offset-1 ">
<form name="messageForm" novalidate="novalidate" ng-submit="onSubmit()" id="message-box">
<div class="form-group">
<textarea required ng-model="formModel.message"
style="background-color:#ffffe6;border:double 4px orange;border-radius: 0.5em;" rows="3" cols="50" id="message" placeholder="Write your message and press enter.."> </textarea>
<button class="btn btn-primary" type="submit">Shoot it</button>
</div>
<p ng-cloak class="help-block" ng-show="formModel.nameError">Looks like you forgot to mention your name !!!</p>
<p ng-cloak class="help-block" ng-show="formModel.messageEmpty">Really you don't wanna do anything before you die !!! </p>
<p ng-cloak class="help-block" ng-show="formModel.messageTooLong">You are trying to do too many things buddy, just 150 characters !!! </p>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$(".demo1").bootstrapNews({
newsPerPage: 12,
autoplay: true,
pauseOnHover:true,
direction: 'up',
newsTickerInterval: 4000,
onToDo: function () {
//console.log(this);
}
});
});
</script>
</body>
</html>
When I check through chrome dev tool, data is present in that unordered list, data is present but somehow not getting displayed properly within bootstrap panel.
See this image
I noticed there is one undefined element at the bottom of unordered list while checking through dev tools. Any idea whats going wrong?
The panel body is empty
Why is the [ul] tag style set to "height:0px; overflow-y:hidden"? -- this would hide your content
you could also move the ng-cloak to the div.panel-body to the div.row and remove it from the child td
--
Delay bootstrapNews binding
$(function(){
if ($('.panel-body[ng-cloak]').length > 0)
return window.setTimeout(arguments.callee, 10);
$(".demo1").bootstrapNews({...});
});
I think you should write a directive for getting a callback when ng-repeat is done and that is a better solution instead of any 'delay' tactics.
Might help you to go through how I have done in my code- used a directive to emit a render finished event:
dashboard.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit(attr.onFinishRender);
});
}
}
}
});
In the controller I keep the event listener:
$scope.$on('dataLoaded', function(ngRepeatFinishedEvent) {
// your code to add bootstrapNews binding
});
and in the html side, I call them like this:
<div class="add_tenant_name" ng-repeat="tenant in tenants" on-finish-render="dataLoaded">
// more divs
</div>

AngularJS isn`t working

after watching this presentation (https://www.youtube.com/watch?v=ImR0zo1tA_I) I wanted to try Angular JS. I copied the code, exactly what was on the screen, but i doesn't work. I tried it in my browser, in my page (http://thecodemaker.com.pl), I was doing research about AngularJS but it still doesn`t want to work.
Code :
<!DOCTYPE html>
<html ng-app="basicApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
</head>
<body ng-controller="TodoController">
<form>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h1 class="panel-title"><b>ToDo List</b></h1>
</div>
<ul class="list-group">
<li class="list-group-item" ng-repeat = "todo in todos">
<div class="checkbox">
<label>
<input type="checkbox"> {{todo}}
</label>
<button type="button" class="close">×</button>
</div>
</li>
</ul>
</div>
<div class="form-group has-feedback">
<label class="control-label invisible">Enter Task</label>
<input type="text" class="form-control text-primary"></input>
<button type="button" class="close form-control-feedback text-muted">±</button>
</div>
<div class="alert alert-info">Enter new task to get started</div>
<div class="alert alert-danger">Maximum number of tasks allowed : 5</div>
</div>
</form>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-1.11.2.js"></script>
<script>
angular.module("basicApp", [])
.controller("TodoController", ["$scope", function($scope) {
$scope.todos =['Buil an atomic bomb','Sell it on ebay']
}
</script>
</body>
</html>
Any ideas what is wrong ?
There seems to be a lot wrong with your snippet. For one, your submit/add button is not bound to an event listener or anything so it's not doing anything that you'd want (like adding an item to the property on your controller's $scope).
Check out the Todo example on Angular's official website, it's more up to date.
https://angularjs.org/ (scroll down).
Here's the video for it: https://www.youtube.com/watch?v=WuiHuZq_cg4
There is an error : Bootstrap's JavaScript requires jQuery, which means you need to add jQuery library to your project, required by bootstrap.js
Starting with Angular 1.3.x, you can no longer declare a controller as a generic global function on window. Controllers must now use the more current form of component declaration.
<script>
angular.module("basicApp", [])
.controller("TodoController", ["$scope", function($scope) {
$scope.todos =['Buil an atomic bomb','Sell it on ebay']
}
</script>
In the HTML, change ng-app="" to ng-app="basicApp.

bootstrap modal button click event not fired on first time

i am new to twitter bootstrap .i am using the bootstrap 3
and this is my html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bootstrap Samples</title>
<script src="scripts/jquery1.10.2.min.js"></script>
<script src="bootstrap-3.1.1-dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap-3.1.1-dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="bootstrap-3.1.1-dist/css/bootstrap-theme.min.css" />
<style>
.banner {color:#FF0000;}
</style>
<script>
$(document).ready(function(){
$("#MyModal5").on('hidden.bs.modal',function(){
$("#btnYes").on('click',function(e){
var $myMod = $(this);
var id = $myMod.data('cust-id');
if(id=='y'){
alert("You clicked yes button");
}
});
});
});
</script>
</head>
<body>
<!-- -------------------------------------------------------------------- -->
<div class="modal fade" id="MyModal5">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-title">
<label style="color:#FF6600;">Confirmation</label>
</div>
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<label>This may cause to make an additional hit to server. Are you sure you want to continue ?</label>
</div>
<div class="modal-footer">
<button class="btn btn-success btn-sm" id="btnYes" data-cust-id="y" data-dismiss="modal">Yes</button>
<button class="btn btn-danger btn-sm" id="btnNo" data-cust-id="n" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<!-- -------------------------------------------------------------------- -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<label>If you want to visit google</label>Click here
</div>
</div>
</div>
</body>
</html>
idea is that i have a link, while i click on that link i need to populate the model.its working,now if i click on the 'yes' button on that modal ,i need an alert, but problem is that alert is not showing when i click on yes button for first time ,but if i again click on that button for second time it is showing,another problem is tht if i clicked on third time alert is showing twise,i dont know the exact reason,i suspect this is because of the on event of jquery.
can any one help me to slove this issue
I believe the issue may stem from your click event bindings being nested. Try removing the outer binding and just register the click event in this way:
$(document).ready(function() {
$("#btnYes").on("click",function(e) {
var $myMod = $(this).closest(".modal"); // Select on closest parent modal
// Now run your required code
});
});
});
Hope this works and helps! Good luck.

How can I change multiple attributes of a form element when a button is clicked?

Im currently working on a new project that has a modal window on all the pages which houses the login form.
Currently the form just displays, then when the user click 'Login', the value 'Login' changes to 'Processing' and after 5 seconds the form submits.
I like the way this does this, but I would like to add a loading image that shows when the user clicks submit.
So for this I intend to change the '' to '' but the thing is I am not sure in what way I can implement this.
Currently my page looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="../realcms/v0.2/admin/css/style.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<a data-toggle="modal" href="#myModal" class="btn btn-primary btn-large">Launch demo modal</a>
<div id="myModal" class="modal hide">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p><form action="../realcms/v0.2/admin/login.php" method="POST" id="login-form">
<fieldset>
<p>
<label for="login-username">username</label>
<input type="text" name="login-username" id="login-username" class="round full-width-input" autofocus="">
</p>
<p>
<label for="login-password">password</label>
<input type="password" name="login-password" id="login-password" class="round full-width-input">
</p>
<p>I've forgotten my password.</p>
<input type="button" name="loginButton" id="login" value="<img src='http://www.signaltrader.com/images/loading_circle.gif' height='25px' width='25px'>" class="button round blue image-right ic-right-arrow">
<input type="hidden" src="http://www.signaltrader.com/images/loading_circle.gif" name="image" width="60" height="60">
</fieldset>
<br>
</form></p>
</div>
<div class="modal-footer">
<a data-loading-text="Loading..." data-toggle="modal" href="#myModal2" class="btn">Close</a><button type="button" class="btn" data-loading-text="loading stuff..." >...</button>
</div>
</div>
<script type="text/javascript">
var form = document.getElementById("login-form");
form.onsubmit = function() { return false; } // ensure ENTER won't cause submit
form.loginButton.onclick = function( )
{
this.value = "Process";
setTimeout( function() { form.submit(); }, 5000 );
}
</script>
</body>
</html>
You can string together several actions on the button, or add additional timeouts if needed. This is just an example of adding a few more manipulations into your click function.
form.loginButton.onclick = function( )
{
var button = $(this);
button.attr('value','Process').css('border','green').attr('data-loading','true');
$('#loading-img').show();
setTimeout( function() { alert('this thing is totally loading!'); }, 2500 );
setTimeout( function() { $('#loading-img').hide(); form.submit(); }, 5000 );
}
DEMO: http://jsfiddle.net/jonocairns/8gSan/
Used a img element instead of an imput element.
<img src="http://www.signaltrader.com/images/loading_circle.gif" id="image" width="60" height="60" style="display:none;" />
then added some javascript
form.loginButton.onclick = function( )
{
**document.getElementById('image').style.display = 'block';**
this.value = "Process";
setTimeout( function() { form.submit(); }, 5000 );
}

Categories