I have a simple mathematical captcha that seems to work however it now does not allow me to submit my form.
https://jsfiddle.net/qm24Lps8/2/
The js fiddle above contains the full code - bellow is the bottom half of the form. The captcha is amended to the bottom of the message box. There is also the javascript that runs the captcha.
What have I done wrong that stops the form from submitting?
<div class="mxm-form-item " id="mxm-form-2446-field-3">
<div class="mxm-form-field">
<textarea rows="2" name="Default.message" id="mxm-form-2446-field-3-el" class="mxm-form-element mxm-form-textarea" onfocus="clearDefaultandCSS(this)">How can we help?</textarea>
</div>
<div class="mxm-clear"></div>
</div>
<div class="mxm-form-item " id="mxm-form-38124-field-3">
<div class="mxm-form-field">
<input type="hidden" name="Default.brochure request" value="no" />
<input id="mxm-form-38124-field-3-el" type="checkbox" name="Default.brochure request" value="yes" class="mxm-form-element mxm-form-booleancheckbox" />
<label for="mxm-form-38124-field-3-el" class="mxm-form-cb-label">Download our brochure</label>
</div>
<div class="mxm-clear"></div>
</div>
<div class="mxm-form-item " id="mxm-form-38124-field-4">
<div class="mxm-form-field">
<label style="width:120px;" class="mxm-form-item-label"></label>
<input type="submit" value="Submit" class="mxm-form-element mxm-form-button" onclick="return(validate());" />
</div>
<div class="mxm-clear"></div>
</div>
</form>
</div>
</div>
</div>
</div>
$(function(){
var mathenticate = {
bounds: {
lower: 5,
upper: 50
},
first: 0,
second: 0,
generate: function()
{
this.first = Math.floor(Math.random() * this.bounds.lower) + 1;
this.second = Math.floor(Math.random() * this.bounds.upper) + 1;
},
show: function()
{
return this.first + ' + ' + this.second;
},
solve: function()
{
return this.first + this.second;
}
};
mathenticate.generate();
var $auth = $('<input type="text" name="auth" />');
$auth
.attr('placeholder', mathenticate.show())
.insertAfter('textarea[name="Default.message"]');
$('#mxm-form-38124').on('submit', function(e){
e.preventDefault();
if( $auth.val() != mathenticate.solve() )
{
alert('wrong answer!');
}
});
});
Check whether Validate() function defined. It throws error on submit button event.
Related
I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});
I have div which needs to be repeated(create dynamically) on a button click.i have a working code,but it needs to be used many places across pages so i would like to make it a generic one,like i need to pass only particular div id as an input parameter to that method.
function textbox_add(id){
console.log(id)
var counter = 0;
$('#'+id).on('click','.newField', function () {
console.log(counter);
if(counter >= 3){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
counter++;
});
$('#'+id).on('click','.remove', function () {
if (counter == 0)
{
return false
}
$(this).parent().remove();
counter--;
});
}
if i use it outside the method it works perfect.The goal is to create 4 text boxes dynamically and if i remove it should remove one by one.
here is my fiddle
Demo
Issues facing when i place inside method are:
On first click it creates single div on second click it creates two div's then continues for further click's.
On clicking remove it works like create.
when i click new again it creates the total of removed,created(earlier) all the div's.
I am not able to find where am missing.
I am not too sure what you are trying to do with the id (I assume it is your div id) that you are adding but you can try replacing your counter with a count of the elements:
function textbox_add(id){
$('#'+id).on('click','.newField', function () {
if($("#" + id + " > .addNew").length >= 4){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
$('#'+id).append(newthing);
});
$('#'+id).on('click','.remove', function () {
if ($("#" + id + " > .addNew").length == 1)
{
return false
}
$(this).parent().remove();
});
}
textbox_add('test');
working Fiddle
OP basically wants an onclick(html) on the add button, like:
function textbox_add(id) {
if ($("#" + id + " > .addNew").length >= 4) {
alert("Reached Maximum");
return false;
}
var newthing = $('#'+id+' .addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','').end();
$('#' + id).append(newthing);
$("#" + id + " > .addNew").on('click', '.remove', function () {
if ($("#" + id + " > .addNew").length === 1) {
return false;
}
$(this).parent().remove();
});
}
working codePen
It works fine, fiddle
You need to pass a wrapper id since you're cloning the .addNew content.
Example:
<div class="container" id="test">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
JS
textbox_add('test');
Your code was actually working well when you use id as selector, but worked wrong (adding multiple times new inputs for example) when you were using class as selector (because multiple elements share the same class).
I have edited it so you can use with id and class selectors:
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
<div id="other_container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JS
function textbox_add(selector){
console.log(selector);
var max_allowed = 3;
$(selector).on('click','.newField', function () {
console.log($(this).parents(selector).find(".addNew").length);
if($(this).parents(selector).find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing=$('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').end();
console.log($(this).parents(selector));
$(this).parents(selector).append(newthing);
});
$(selector).on('click','.remove', function () {
if (!$(this).parents(selector).find(".addNew").length > 1){
return false
}
$(this).parent().remove();
});
}
textbox_add(".container");
textbox_add("#other_container");
And here is the working JSFiddle.
I think that this is not the correct way to approach the problem, but the OP really wants to do it this way.
HTML
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)" />
<br />
<br />
</div>
</div>
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" onClick="textbox_add(this)"/>
<br />
<br />
</div>
</div>
JS
function textbox_add(element){
var max_allowed = 3;
if($(element).parents(".container").find(".addNew").length > max_allowed){
alert("Reached Maximum");
return false
}
var newthing = $('div.addNew:first').clone().find('.newField').removeClass('newField').addClass('remove').val('Remove Field!').attr('onclick','textbox_remove(this)').unbind('click').end();
$(element).parents(".container").append(newthing);
}
function textbox_remove(element){
if (!$(element).parents(".container").find(".addNew").length > 1){
return false
}
$(element).parent().remove();
}
Working JSFiddle
I think this might be what you are trying to do. The main thing I'm not sure of is what you intend to pass in as the id parameter. But tell me if this fills the bill.
http://jsfiddle.net/abalter/xdsacvdm/12/
html:
<div class="container">
<div class="addNew">
<input type="text" name="input_1[]" class="input_1" value="Here goes your stuff" />
<input type="button" class="newField" value="New Field For Stuff" />
<br />
<br />
</div>
</div>
JavaScript:
$('#createField').on('click', function () {
//alert('new field clicked');
var el = createField('some-id', $('#generator').val());
$('.container').append(el);
});
function createField(id, text) {
var numFields = $('.container').find('.added').length;
if (numFields>3)
{
alert("Maximum reached");
return false;
}
var $outerDiv = $('<div>').addClass('newOne').addClass('added').attr('id', id);
var $textBox = $('<input>').attr({'type': 'text','value': text});
var $button = $('<input>').attr({'type': 'button' , 'value': 'Remove Field!'});
$outerDiv.append($textBox);
$outerDiv.append($button).append('<br/>').append('<br/>');
$button.on('click', function(){
$(this).closest('div').remove();
});
return $outerDiv;
}
here for validation i used onsubmit event.
but any how its not working.
i just want check that textbox filed is empty or not.
<!DOCTYPE html>
<html>
<head>
<title>temple3</title>
<link rel="stylesheet" type="text/css" href="temple3css.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div id="popup-content" class='container'>
<div id="container1">
<form id="form" class="form" onsubmit="return validateForm()">
<h1>Feedbak Form</h1>
<div class="content">
<div class="intro"></div>
<div id="section0" >
<div class="field roption">
<input type="radio" name="view" value="public" checked="checked"> <span>Public</span>
<input type="radio" name="view" value="private" ><span>Private</span>
</div>
<div class="field category">
<label for>Category:</label>
<select class="dropDownCate" autofocus>
<option value="bug">Bug</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="field message">
<label for="Comments">Comments:</label>
<textarea id="comments" name="Comments" placeholder='Your Feedback Here!' autofocus></textarea>
</div>
<div class="field">
<label for="Email">Email</label>
<input type="email" id="email" name="Email" placeholder="example#stevens.edu(optional)" autofocus>
</div>
<div class="field"><input type="submit" id="submit-feedback-button" autofocus></div>
</div>
</div>
</form>
</div>
</div>
<div id="popup-overlay-bg"> </div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function validateForm(){
var texbox=document.getElementById("comments").value;
if(texbox == "") {
document.getElementById("comments").focus();
// document.getElementById("comments").style.border = "1px solid #ff0000";
return false;
}
}
$(document).ready(function(){
$("#feedback-button").click(function(){
openfeedbackform();
});
$("#popup-overlay-bg").click(function(){
closefeedbackform();
});
$("#submit-feedback-button").click(function(){
// closefeedbackform();
});
$(window).resize(function(){
updatefeedbackform();
});
$("#submit-feedback-button").click(function(){
var category=$(".dropDownCate").val();
var roption=$('input:radio[name=view]:checked').val();
var message=$("#comments").val();
var email=$("#email").val();
$.ajax({
type: "POST",
url: "feedback.php",
data: "category="+category+ "&roption="+roption+ "&message="+message+ "&email="+email,
success:function(result)
{
if(result=="true"){
$("#form").hide();
$("#container1").html("<h3>Thank you for your feedback We will get back to you ASAP</h3> ");
}
else{
$("#form").hide();
$("#container1").html("<h3> database error </h3>");
}
}
});
return false;
});
});
function openfeedbackform(){
$("#popup-content").find('input:text').val('');
$("#popup-content").fadeIn();
$("#popup-overlay-bg").fadeIn();
updatefeedbackform();
}
function updatefeedbackform(){
$popup=$("#popup-content");
var top = "50px";
var left = ($(window).width() - $popup.outerWidth()) / 2;
$popup.css({
'top' : top,
'left' : left
});
}
function closefeedbackform(){
$("#popup-content").fadeOut();
$("#popup-overlay-bg").fadeOut();
}
</script>
</body>
</html>
earlier i used same this for form validation. but i don't why its not working here. i tried to debug but function has not been call.
The problem is you are doing ajax submit in the button click event, not in the form submit.
The click handler is triggered before the submit event handler, so the validation does not have any effect.
The solution will be to use the form submit event handler for both validation and the ajax call as given below, and then there is no need to have the inline event handler like onsubmit="return validateForm()"
$("#form").submit(function () {
if (validateForm() === false) {
return false;
}
var category = $(".dropDownCate").val();
var roption = $('input:radio[name=view]:checked').val();
var message = $("#comments").val();
var email = $("#email").val();
$.ajax({
type: "POST",
url: "feedback.php",
data: "category=" + category + "&roption=" + roption + "&message=" + message + "&email=" + email,
success: function (result) {
if (result == "true") {
$("#form").hide();
$("#container1").html("<h3>Thank you for your feedback We will get back to you ASAP</h3> ");
} else {
$("#form").hide();
$("#container1").html("<h3> database error </h3>");
}
}
});
return false;
});
I've added some validation to my jQuery code to check for blank text fields before it posts a message but it doesn't seem to be working. No messages are being posted at all to my wall. Any idea how I can fix this?
HTML
<div id="header">
<div class="container"> <span id="text_header">Virtual Idea Wall</span> </div>
</div>
<div id="main">
<div class="container">
<div id="chat"></div>
</div>
</div>
<div id="footer">
<div class="container">
<p>
<label for="title">Please give your idea a title</label>
<br />
<input type="text" id="title" name="title"/>
</p>
<p>
<label for="message">Please provide details of your idea</label>
<br>
<input type="text" id="message" name="message"/>
</p>
<p>
<input type="submit" id="sendmessage">
</p>
</input>
</div>
</div>
jQuery
jQuery(function ($) {
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function () {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message', '<b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val());
$messageTitle.val('');
$messageBox.val('');
}
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
});
Your click function is not passing in the event "e" so that would stop this from working when you make a call to "e.preventDefault()".
I made this jsfiddle - no socket support - but it does alert my message.
http://jsfiddle.net/4v2QT/
This is the only change (the e passing into the function)
$messageForm.click(function (e) {
... code goes here!
}
Please find my code below. My problem is that I the inner jQuery.get() doesn't get executed. Could some one help me out with this?
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert(url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
});
});
My html form looks like
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
I'd really appreciate any pointers.
Thanks!
The problem you are experiencing is that you dont do anything to stop your form from being submitted, thus it submits the form before it gets a chance to get the data from the worldweatheronline.com.
Change your click handler to be like this:
$(".button").click(function(event) {
event.preventDefault();
Here is my completed sample code that works the way you want it to:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function(event) {
event.preventDefault();
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert('first'+url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ){
return false;
}
});
}, 'jsonp');
});
});
</script>
</head>
<body>
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
</body>
</html>
Turn on Fiddler or Firebug and watch the HTTP call go out. You'll see the HTTP error message there. Also, turn on your console in Chrome or Firefox to see a potential JavaScript error.
Part of the problem could be the extra set of parentheses after your .get() function call. You have:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
It should be:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
});
}, 'jsonp');
Im going to go out on a limb and guess that (based on the url 'http://www.worldweatheronline.com/feed/weather.ashx?q=' ) that you are attempting to perform an AJAX request to an external site. This violates Same Domain Policy and will fail silently.