Click form on click of text - javascript

In this when I click on "Upload Photo" I want that the form's "Choose File" be clicked.I want to hide the form and trigger the form through click of "Upload Photo".How can I achieve this (without using label)?
HTML:
<div id="image_container" name="image_container">
<img src="../image/ab.jpg" alt="Cover" width="900px" height="500px">
<div class="btn-group" id="cov" name="cov" >
<button class="btn dropdown-toggle" data-toggle="dropdown" id="mybtn" onclick="dropdown()">Action</button>
<ul class="dropdown-menu" id="dropdown-menu" style="display:none">
<!-- dropdown menu links -->
<li>Upload Photo</li>
<li>Something else here</li>
<li class="divider"></li>
<li>Another link</li>
</ul>
</div>
</div>
<form action="upload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<input name="ImageFile" id="imageInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
<img src="img/loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="output"></div>
JS:
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
});
function uploadfile(){
$("imageInput").click();
}

Something like this would work (assuming the "Upload Photo"-text is a link):
$('#upload-photo-link').click(function(e) {
e.preventDefault();
$('#imageInput').trigger('click');
});
Here's a fiddle: http://jsfiddle.net/Niffler/EvNLQ/

Related

Javascript click function only work once

I have a dropdown menu with a submit function that executes, if any children from the dropdown is clicked.
Now I want to prevent the submit function to a special li element, because there should be insert a tracking id in a popup iFrame.
With the following code it works so far on the first dropdown menu and prevent the submit function, but it wont work on all following dropdown's.
Maybe someone has a short solution for me?
<script type="text/javascript">
$(document).ready(function() {
$('.track').click(function(){
stopPropagation();
});
$('.dropdown li').click(function() {
document.getElementById('opt').value = $(this).data('value');
$('#options').submit();
});
$("#options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
});
</script>
<form name="" action="" method="post" id="options">
<input type="hidden" name="update" id="opt" value="">
<div id="item-select-option">
<div class="dropdown">
Options <span class="caret"></span>
<ul id="selector" class="dropdown-menu pull-right" role="menu">
<li data-value="paid">paid</li>
<li data-value="shipped">shipped</li>
<li class="track">track</li>
</ul>
</div>
</div>
</form>
Problem: You've several elements with the id track/options when the id attribute should be unique in same document, so when you attach event to the id just the first element with this id that will be attached.
Suggested solution :
Use class instead of id's, like :
<form name="" action="" method="post" class="options">
.....
<li class="track">
track
</li>
</form>
Then you js should be like :
$('.track').click(function(event){
event.stopPropagation();
});
$(".options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
NOTE : The event should be present in anonymous function function(event).
Hope this helps.

hide div after form has been submitted

I'm trying to hide a div if a span element contains a specific word.
The issue I'm having is that the span only appears after a form has been submitted. I've tried to run my hide function on click of the submit button but this doesn't work as the span is only shown after the button has been clicked and the form submitted. I've also tried running it on submit() of the form but no luck either (posted the code that I've tried below).
HTML
<div class=“deliveryUpsellText”>
<p>blabla</p>
</div>
<ul>
<li class=“error-msg”>
<ul>
<li>
<span> Coupon Code “blabla” is not valid
</span>
</li>
</ul>
</li>
</ul>
<form id="discount-coupon-form" action="http://dev.blabla.co.uk/cart/couponPost/" method="post">
.....
<button type="button" id="cartCoupon" title="Apply Coupon" class="button applycouponhide" onclick="discountForm.submit(false) ; " value="Apply Coupon"><span style="background:none;"><span style="background:none;">Apply</span></span></button>
</form>
jQuery
$j('#cartCoupon').click(function(){
if ($j(".error-msg span:contains('blabla')").length) {
$j('.deliveryUpsellText').css({
"display":"none"
});
}
});
I've also tried
$j('#discount-coupon-form').submit(function(){
if ($j(".error-msg span:contains('blabla')").length) {
$j('.deliveryUpsellText').css({
"display":"none"
});
}
});
Any ideas how I could do this?
You are using this character as quotation: ”
You should use one of these: ' or "
Also, you have this:
onclick="discountForm.submit(false) ; "
which if the object discountForm is not defined, you get error before parsing the javascript part.
$(document).ready(function(){
$('#cartCoupon').on('click',function(){
if($('.error-msg').find("span:contains('blabla')").length > 0) {
$('.deliveryUpsellText').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class='deliveryUpsellText'>
<p>blabla</p>
</div>
<ul>
<li class="error-msg">
<ul>
<li>
<span> Coupon Code “blabla” is not valid
</span>
</li>
</ul>
</li>
</ul>
<form id="discount-coupon-form" action="http://dev.blabla.co.uk/cart/couponPost/" method="post">
.....
<button type="button" id='cartCoupon' title="Apply Coupon" class="button applycouponhide" value="Apply Coupon"><span style="background:none;"><span style="background:none;">Apply</span></span></button>
</form>

Combine/bind many on change, on click event of many tags with different id or class

In my view I have many tags with differents classed and ids like this:
<!-- html view -->
<div class="panel panel-default">
<ul class="" id="tablist" role="tablist">
<li class="getState active" id="proposed">
<b>Proposed</b>
</li>
<li class="getState" id="current">
<b>Current</b>
</li>
<li class="getState" id="incoming">
<b>Incoming</b>
</li>
<li class="getState" id="finished">
<b>Finished</b>
</li>
</ul>
</div>
<select class="form-control" id="isProduction">
<option value="" disabled selected>Type</option>
<option value="production">Production</option>
<option value="nonProduction">nonProduction</option>
</select>
<div>
<!-- some content here like <p></p> -->
<a href="#validity">
<button class="btn btn-default">Validity</button>
</a>
</div>
<div>
<!-- some content here like <p></p> -->
<a href="#rate">
<button class="btn btn-default">Rate</button>
</a>
</div>
<!-- content appear here -->
<div id="info">
<!-- put some content here following click and selected option change -->
</div>
Using jQuery, I would like to catch all clicks, changes of these tags, more precisely if user click on a <li></li> tag with class .getState, or if user have selected an option of the <select></select> tag which has the id #isProduction or if user have click on the other <button></button> tag wich have <a href="#validity"> or <a href="#rate">.
Like this example:
<script type="text/javascript" charset="utf-8" defer>
$('.getState').bind('click', function sortByState(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
});
</script>
Here I could make a request (php server side) by recovering the state, then I could make a request with this argument.
How can I combine all these event in only one function in order to recover all the argument I need for my php server side using jQuery ?
I see on the doc here, that we could create a bind on multiple event like this:
$( "#foo" ).bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});
If I understand correctly you want to attach same event to multiple elements, if yes that could be done using comma separator ,:
$('body').on('click','#isProduction, .getState, button.my-btn',function(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
})
NOTE : For the two buttons better if you could add a class to them so you will attach event just to them button.my-btn instead of attaching it to button so that will not infect other buttons click event.
<button class="btn btn-default my-btn">Validity</button>
<button class="btn btn-default my-btn">Rate</button>
Or also you could use separated function and attach events separately but trigger the same action :
$('body').on('click','.getState, button.my-btn',myAction);
$('body').on('change','#isProduction',myAction);
function myAction(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
}
Hope this helps.
$('body').on('click','.getState, button.my-btn',myAction);
$('body').on('change','#isProduction',myAction);
function myAction(){
alert('myAction');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="panel panel-default">
<ul class="" id="tablist" role="tablist">
<li class="getState active" id="proposed">
<b>Proposed</b>
</li>
<li class="getState" id="current">
<b>Current</b>
</li>
<li class="getState" id="incoming">
<b>Incoming</b>
</li>
<li class="getState" id="finished">
<b>Finished</b>
</li>
</ul>
</div>
<select class="form-control" id="isProduction">
<option value="" disabled selected>Type</option>
<option value="production">Production</option>
<option value="nonProduction">nonProduction</option>
</select>
<div>
<!-- some content here like <p></p> -->
<a href="#validity">
<button class="btn btn-default my-btn">Validity</button>
</a>
</div>
<div>
<!-- some content here like <p></p> -->
<a href="#rate">
<button class="btn btn-default my-btn">Rate</button>
</a>
</div>
<!-- content appear here -->
<div id="info">
<!-- put some content here following click and selected option change -->
</div>
You can use below code to capture trigger click event on whole page and then you can write desired code to be executed:
$('body').bind('click',function(){
//your code here
});

How to update a textfield based on other form elements

I'm writing a little database query app.
What i'm trying to do: Each time a checkbox is clicked, i'd like for a query that includes the selected fields to be generated and inserted into the textarea.
The problem: For some reason, with every click, its showing the query from the previous click event, not the current one.
Here's the markup:
<div class="application container" ng-controller="OQB_Controller">
<!-- top headr -->
<nav class="navbar navbar-default navbar-fixed-top navbar-inverse shadow" role="navigation">
<a class="navbar-brand">
Algebraix Database Client
</a>
<ul class="nav navbar-nav navbar-right">
<!--<li>Clear Queries</li>-->
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-import"></span> Load Data <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>Default Data</li>
<li>Custom Import</li>
<!-- <li class="divider"></li> -->
</ul>
</li>
<li>
<a href="" class="queries-clear">
<span class="glyphicon glyphicon-remove"></span> Clear Queries
</a>
</li>
</ul>
</nav>
<!-- left column -->
<div class="col-md-4">
<div class="well form-group">
<ul>
<li ng-repeat="option in options">
<input type="checkbox" class="included-{{option.included}}" value="{{option.value}}" ng-click="buildQuery()" ng-model="option.included"> {{option.text}}
</li>
</ul>
</div>
</div>
<!-- right column -->
<div class="col-md-8">
<form role="form" id="sparqlForm" method="POST" action="" class="form howblock">
<div class="form-group">
<!--<label>Query</label>-->
<textarea type="text" name="query" class="form-control" rows="10" placeholder="Write your SPARQL query here">{{query}}</textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit Query" data-loading-text="Running Query..." />
</div>
</form>
</div>
</div>
And in my controller, i am doing the following:
var OQB_Controller = function($scope) {
console.log('OQB_CONTROLLER');
$scope.query = 0;
$scope.options = [
{ text: "checkbox1", value: "xyz123", included: false }
,{ text: "checkbox2", value: "abcRRR", included: false }
,{ text: "checkbox2", value: "abcRRR", included: false }
];
$scope.buildQuery = function() {
console.log('click');
var lines = [];
lines.push("SELECT *");
lines.push("WHERE {");
lines.push(" ?s ?p ?o .");
for(var i = 0; i<$scope.options.length; i++) {
var line = $scope.options[i];
console.log( line.value, line.included, i );
if( line.included ) {
lines.push(" OPTIONAL { ?s "+line.value+" ?o } .");
}
}
lines.push("}");
lines.push("LIMIT 10");
var _query = lines.join("\n");
$scope.query = _query;
};
};
To reiterate, every time the build query method is called, the state of the included booleans is from one click event prior. this has the symptoms of the classic javascript problem of the keyup vs keydown and the state of the event... however, i'm not sure if that is what is happening here.
is there a better way to do build the query (than what i'm currently doing) and populate the textarea based on the checked boxes?
use ng-change instead of ng-click because it is more appropriate for this particular desired behavior. See the ng-change documentation below:
The ngChange expression is only evaluated when a change in the input
value causes a new value to be committed to the model.
It will not be evaluated:
if the value returned from the $parsers transformation pipeline has
not changed if the input has continued to be invalid since the model
will stay null if the model is changed programmatically and not by a
change to the input value

Why can't I process the returned HTTP status codes from $.ajax?

I have next JSP page that works on Google App Engine:
<%# page contentType="text/html; charset=windows-1251" language="java" %>
<%# page import="com.wedding.Register" %>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
function submitMyForm(button) {
var myForm = $(button).closest('form');
$.ajax({
url: $(myForm).attr('action'),
type: "post",
contentType:attr("enctype", "multipart/form-data"),
data: $(myForm).serialize(),
statusCode: {
400: function () {
$('.form-inline').after("<h1>400!</h1>");
},
200: function () {
$('.form-inline').after("<h1>200!</h1>");
}
}
});
}
</script>
</head>
<body>
<div class="container">
<%
String companyName = Register.getLoggedInCompanyName(request);
if (companyName == null) {
%>
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Menu</a>
<ul class="nav">
<li>Home</li>
<li class="active">Register</li>
</ul>
</div>
</div>
<div class="hero-unit">
<h1>Login</h1>
<p>Enter login credentials</p>
<p>
<form action="/reg?action=login" class="form-inline" method="post" enctype="multipart/form-data">
<input type="text" name="email" class="input-xlarge" placeholder="">
<input type="password" name="password" class="input-xlarge" placeholder="">
<button type="submit" class="btn" onClick="submitMyForm(this)">Login</button>
</form>
</p>
</div>
<%
} else {
%>
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">Menu</a>
<ul class="nav">
<li>Home</li>
<li class="active">Logout</li>
</ul>
</div>
</div>
<div class="hero-unit">
<h1>Error</h1>
<p>Error.</p>
</div>
<%
}
%>
</div>
<div id="footer">
<div class="container">
<p class="muted credit"></p>
</div>
</div>
</body>
The problem is that when a click button the form is sent to the server but if the server return 400 HTTP status code
$('.form-inline').after("<h1>400!</h1>");
is not invoked.
I've also tried success/error function and other HTTP codes but without success. The interesting thing is that it worked once and then always fails. Instead of adding new element to HTML the browser is redirected to the generated error page.
The status code is returned using
HttpServletResponse.sendError(400);
I've checked that a correct request and response are sent. I've also checked that the latest jquery is linked.
A <button/> enclosed in a <form/>, by default, submits it. So, you need to stop the form submission.
In the following example I will stick with jQuery instead of your mix of JavaScript and jQuery.
/* Bind the submit event */
$("form").submit(function() {
/* Request an HTTP 400 */
$.ajax({
url: "http://httpstat.us/400",
statusCode: {
400: function() {
console.log("HTTP 400 received");
}
}
});
/* stop the form submission */
return false;
});​
<form action="/reg?action=login" class="form-inline" method="post" enctype="multipart/form-data">
...
<button type="submit" class="btn">Login</button>
...
</form>
Since $.ajax is executed asynchronously, if you don't stop the form submission the browser will still submit it hence redirecting the page.
Feel free to test it out.
Have you tried surrounding the function submitMyForm(button) around jquery document ready?
$(document).ready(function(){
function submitMyForm(button) {
var myForm = $(button).closest('form');
$.ajax({
url: $(myForm).attr('action'),
type: "post",
contentType:attr("enctype", "multipart/form-data"),
data: $(myForm).serialize(),
statusCode: {
400: function () {
$('.form-inline').after("<h1>400!</h1>");
},
200: function () {
$('.form-inline').after("<h1>200!</h1>");
}
}
});
}
});

Categories

Resources