I have two radio buttons. When I click into one of them to change the form fields, the captcha version 1 does not show anymore.
So, I have to click the refresh button to generate a new captcha image.
<input type="radio" name="data[Form][sv]" id="FormV1" value="1" /> V1
<input type="radio" name="data[Form][sv]" id="FormV2" value="2" checked="checked" /> V2
The jquery code is:
$(document).ready(function () {
$("#FormV1").bind("change", function (event) {
$.ajax({async:true,
beforeSend:function (XMLHttpRequest) {
$('#loading').show();
},
complete:function (XMLHttpRequest, textStatus) {$('#loading').hide()},
data:$("#FormularioSituacaoVeiculo1").closest("form").serialize(),
dataType:"html",
evalScripts:true,
success:function (data, textStatus) {
$("#search").html(data);},
type:"post",
url:"\/mysite\/theurl\/"});
return false;
});
$("#FormV2").bind("change", function (event) {
$.ajax({async:true,
beforeSend:function (XMLHttpRequest) {
$('#loading').show();
},
complete:function (XMLHttpRequest, textStatus) {
$('#loading').hide()
},
data:$("#FormV2").closest("form").serialize(),
dataType:"html", evalScripts:true, success:function (data, textStatus) {
$("#search").html(data);
},
type:"post",
url:"\/mysite\/url\/"});
return false;
});
function showRecaptcha(element) {
Recaptcha.create('hjfsdjklsdjklfsdjklfsdjklfjksdl', element, {
lang : 'en-gb',
theme : 'custom',
custom_theme_widget: 'recaptcha_widget',
callback: Recaptcha.focus_response_field
}
);
}
showRecaptcha('recaptcha_div');
How can I switch the form fields (V1 to V2) and generate the captcha automatically without having to click on the refresh button?
Today the captcha is not generated when I do click on the radio button. So I have to click on the refresh button to regenerate a captcha image.
Please check this working example (I have tried my best to make this example as close as possible to your situation):
$('input[name="data[Form][sv]"]').change(function(e) {
$.ajax({
async: true,
beforeSend: function(XMLHttpRequest) {
$('#loading').show();
},
complete: function(XMLHttpRequest, textStatus) {
$('#loading').hide()
},
data: $(this).closest("form").serialize(),
evalScripts: true,
success: function(data, textStatus) {
$("#search").html(data);
Recaptcha.reload();
},
dataType: "html",
type: "POST",
url: "https://httpbin.org/post"
});
return false;
});
function showRecaptcha(element) {
Recaptcha.create('6Ld3TPkSAAAAAPckREYZuVQ6GtjMQsD-Q5CkzNxj', element, {
lang: 'pt-BR',
theme: 'white',
custom_theme_widget: 'recaptcha_widget',
//callback: Recaptcha.focus_response_field
});
}
$(function() {
showRecaptcha('recaptcha');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha"></div>
<h4>Radio Inputs: </h4>
<form>
<input type="radio" name="data[Form][sv]" id="FormV1" value="1" />V1
<input type="radio" name="data[Form][sv]" id="FormV2" value="2" checked="checked" />V2
</form>
<h4>Ajax Post Result <span style="display:none" id="loading">Loading...</span>: </h4>
<div id="search">
</div>
Refresh codes are what you are looking for?
for v1:
Recaptcha.reload();
for v2:
grecaptcha.reset();
Related
I am trying to build my first website and I encountered a problem that I couldn't resolve by now. So, when an user wants to add an item to the cart, or to increment the quantity, I want to prevent the page from refreshing when hitting the submit button. I've looked for many answers, I tried to apply Ajax/JQuery, but unsuccessful.
Here is my code:
html
<form action="{% url 'cart-add' %}" method="GET" id="myform">
{% csrf_token %}
<label>
<input type="hidden" name="{{ product.pk }}">
<input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1">
<button type="submit" value="">Add to chart</button>
</label>
</form>
Ajax/JQuery script
<script type="text/javascript">
$(document).ready(function () {
$('myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("myForm").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
When I hit add-to-cart submit button, it throw me to the "cart.html". I do not want to do that, instead I want to prevent that and throw a message to the user saying that his/her item has been successfully added.
Can somebody help me? Thank you very much for your time. I much appreciate it!
You need to return false, otherwise, the function with carry on with the default behaviour after the function is complete:
<script type="text/javascript">
$(document).ready(function () {
$('#myform').on('submit', function(e) { // fix typo
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("myForm").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
// Prevent function from saving
return false;
});
});
</script>
Update: looking at the jQuery documentation, I don't know if return false is necessary if e.preventDefault() is present.
Is $('myform') a typo? Should it be $('#myform')?
To reference a HTML's ID, use a #idName.
To reference a HTML class, use a .className
To reference a HTML element, just enter name
$('myform') is looking for a <myform></myform> element.
$('#myform') is looking for a <... id="myform"></...>
$('.myform') is looking for a <... class="myform anotherRandomClass"></...>
Your form is submitting normally because your jquery selector is wrong. You have to change $('myform') to $('#myform')
<script type="text/javascript">
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#myform").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
I have the below jquery. It all works correctly except.... if I input a value in "name=bidz" and then click anywhere on the page, this triggers the animation but nothing else. How do I get clicks outside of my submit button to stop triggering the animation?
Does this have something to do with first clicking in the input box, then adding the value, and then the follow click is a second change?
<form action="" method="post">
<div id="<?php echo $this->item['id']; ?>">
<div class="ab">
<label for="ab_input"><?php echo $this->translate('To get the auction started, you must enter a starting bid.'); ?></label>
<span class="auction_bid_container">
<input id="ab_input" type="text" maxlength="12"
class="middle nmr event-clear-focus"
name="bidz" value="Enter something" />
<input id="updateBidButton" type="submit"
class="button grey-button num-items-button"
name="bidz"
value="<?php echo $this->translate('submit'); ?>"/>
</span>
</div>
</div>
</form>
<div class="clear mb20"></div>
$('input[name="bidz"]').live('change', function () {
var bidz = this.value;
$.ajax({
type: 'post',
url: "?module=is&controller=index&action=syy",
dataType: "text",
data: 'bid=' + bidz + '&id=' + id,
beforeSend: function () {
$('.ab').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
console.log(bidz);
$('.ab').animate({
'backgroundColor': '#A3D1A3'
}, 300);
} else {
$('.ab').animate({
'backgroundColor': '#FFBFBF'
}, 300);
}
}
});
});
If you just want clicks outside of your submit button to stop triggering the animation, then you should attach the event handler to your submit button instead of text input. Something like this should work fine:
$('#updateBidButton').live('click', function (e) {
e.preventDefault();
var bidz = this.value;
$.ajax({
type: 'post',
url: "?module=is&controller=index&action=syy",
dataType: "text",
data: 'bid=' + bidz + '&id=' + id,
beforeSend: function () {
$('.ab').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
console.log(bidz);
$('.ab').animate({
'backgroundColor': '#A3D1A3'
}, 300);
} else {
$('.ab').animate({
'backgroundColor': '#FFBFBF'
}, 300);
}
}
});
});
Edit:
Also please remember that live() method was removed in jQuery 1.9, so consider replacing it with:
$(document).on('event', 'yourSelector', function() {
// your code hear
});
So in your case it would be:
$(document).on('click', '#updateBidButton', function() {
// ...rest of your code...
});
This will attach an event to the document object and then when you click an element it will check if the target is #updateBidButton, so it will work even if the html is generated dynamically.
I have the following input HTML tag
<input type="submit" id="submitForm" value="Submit" class="btn btn-primary start" autocomplete="off" onclick="submitForm();" />
When I click on the submit button, it goes to the related JavaScript file and executes the function submitForm();
I would like to change the text of the submit form to "Please wait..." until the function is completed.
Is there a way this can be done?
This is how the submitForm() function looks like:
function submitForm() {
$("#submitForm").val("Please wait...");
if (formValidation() === true) {
submitFormInfo().done(function () {
$("#submitForm").val("Submit");
});
}
}
function submitFormInfo() {
return $.ajax({
cache: false,
url: "URLHERE"
error: function (xhr) {
},
success: function (result) {
},
async: false,
processData: false
});
}
Are you having asynchronus operation in submitform() ?
if yes then you can use following line
$("#submitForm").val("Please Wait");
You can use jquery please see:-
https://jsfiddle.net/swawrm1g/3/
I have removed:-
onclick="submitForm();"
and added:-
$('#submitForm').click(function(){
$(this).val('Please Wait...');
submitForm()
});
function submitForm() {
alert('Form submitted');
};
Simple javascript is enough to do this..
<script>
function submitForm(){
document.getElementById('submitForm').value="Please wait..";
}
</script>
<input type="submit" id="submitForm" onclick="submitForm()" value="Submit">
Use the beforeSend option on your ajax call, so in your submitForm() function, you can do something like this:
function submitForm() {
var submitForm = $("#submitForm");
if (formValidation() === true) {
$.ajax({
cache: false,
url: "URLHERE",
async: false,
type: 'post',
data: { somedata: 'here' },
beforeSend: function (){
submitForm.val("Please wait...").attr("disabled", "disabled");
},
success: function (data){
// do something
},
error: function (){
// do something
},
complete: function () {
// regardless of the response status (success/error)
// the codes below will be executed.
submitForm.val("Submit").removeAttr("disabled");
}
});
}
}
I have a page with a dropdown list and a input with type="text".
I'm trying to filter the results of my table via AJAX when I select an option in my dropdown list.
It should clean the value of the input when the option is selected (after the success).
It's working fine.
The problem is that I need it to for my input. It should send the value of the input to AJAX and then filter the results when I submit the form.
I can't put it to work after the suceess. It sets the dropdown list to "selected". I don't know why.
HTML code:
<form action="#Url.Action("a","b")" id="filter-date" onsubmit="javascript:return false">
<label for="from" class="label-datepicker">from:</label>
<input type="text" id="from" name="from" class="dateinput">
<label for="to" class="label-datepicker">to:</label>
<input type="text" id="to" name="to" class="dateinput">
<button type="submit" name="submit" id="submit-date">
OK
</button>
</form>
<select name="Assunto" id="select-a">
<option value="" selected="selected">--Select--</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
JavaScript code:
$("#select-a").change(function () {
var selected = $("#select-a").val();
var Keyword = { data: $("#select-a").val() };
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("bo", "b"))',
data: { Keyword: selected },
dataType: 'html',
success: function (data) {
$(".dateinput").val('');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
$("#filter-date").submit(function () {
var from = $("#from").val();
var to = $("#to").val();
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("update", "b"))',
data: { From: from, To: to },
dataType: 'html',
success: function (data) {
$("#bodylist").html(data);
$("#select-a").val(selected);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
Try this
As #Anto rightly said
var selected = $("#select-a").val();
scope of this above statement should be in form-submit also
$("#select-a option[selected]").removeAttr("selected");
$("#select-a option[value=" + selected+ "]").attr('selected', 'selected');
Try:
$("#filter-date").submit(function () {
var from = $("#from").val();
var to = $("#to").val();
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("update", "b"))',
data: { From: from, To: to },
dataType: 'html',
success: function (data) {
$("#bodylist").html(data);
// $("#select-a").val(selected); //should remove this line because we use ajax, the page is not refreshed, not need to restore the state.
//or $("#select-a").val(""); if you need to reset
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
return false; //return false at the end to prevent form submitting
});
And remove onsubmit="javascript:return false". And should not use - in id attribute.
i have found a solution.. and its solved now.
its more easier if i thought.
the ajax call on .submit doesn´t allow me to do something after success like what i need..
this i don´t know it.
what i have done is to set the value of the option from my dropdownlist to selected before the ajax section.
and the magic is done..
its working now.
this is my new code:
$("#filter-date").submit(function () {
var from = $("#from").val();
var to = $("#to").val();
$('#select-a').val('selected');
$.ajax({
cache: false,
type: 'GET',
async: false,
url: '#(Url.Action("update", "b"))',
data: { From: from, To: to },
dataType: 'html',
success: function (data) {
$("#bodylist").html(data);
$("#select-a").val(selected);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
Try use jQuery function .data(name, value) to store selected value like this:
$('#select-a').data('selectedValue', $('#select-a').val());
Then in submit handler get it:
var selected = $('#select-a').data('selectedValue');
And use #Nitin's code to set selected option:
$("#select-a option[selected]").removeAttr("selected");
$("#select-a option[value=" + selected+ "]").attr('selected', 'selected');
Just make selected global:
(function(){
var selected;
$("#select-a").change(function () {
selected = $("#select-a").val();
// rest of your script
})(); // close the wrapper
EDIT: Wrapping it up in a self-executing anonymous function will keep the global namespace clean (thanks to #jameslafferty).
I am trying to pull text from another page (ajaxuseradd.psp) which is in JSON format. I am then trying to insert this text into several text boxes and/or select lists. For right now, I am merely trying to do the text boxes.
Here's my code, a good deal of which was given to me, because I am not all that familiar with jQuery:
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$.each(data, function(key, value) {
$('#' + key).val(value);
});
},
dataType: 'json'
})
});
</script>
<form action="adduser.psp" method="get">
<fieldset>
<label for="uname">Username:</label>
<select name="uname" id="useruname" onchange="updateAdduser();">
<%
Random Python Code That Isn't Important But Generates Option Values
%>
<%= options %>
</select>
</fieldset>
<fieldset>
<label for="fname">First Name:</label>
<input type="text" name="fname" />
</fieldset>
<fieldset>
<label for="lname">Last Name:</label>
<input type="text" name="lname" />
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="text" name="email">
</fieldset>
Output from ajaxuser.psp should be as follows, or some variation thereof. This will be displayed on the page ajaxuser.psp when the argument ?uname=neverland is used, for example:
{"fname" : Neverland, "lname" : Conference Room, "email" : nobody#mediaG.com, "deptid" : deptid, "active" : active, "sentient" : sentient}
So my code should look like this?
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$("#fname").val(data.fname);
});
},
dataType: 'json'
})
});
});
</script>
EDIT: This is still not working - I select a drop down value, and NO CHANGE for any of the fields.
The first thing I see is that you need to wrap the onchange handler in this:
$(document).ready(function () {
});
So it looks like this:
$(document).ready(function () {
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$.each(data, function(key, value) {
$('#' + key).val(value);
});
},
dataType: 'json'
})
});
});
Also, this:
$.each(data, function(key, value) {
$('#' + key).val(value);
});
Is not going to work like you think. You get back ONE object with the properties, so more like this:
success: function(data, status, xhr) {
$("#fname").val(data.fname);
....
},