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!
}
Related
I am trying to develop a form. Before submitting to server i validate it using jquery, everything is working fine except function on submit event, form is being submitted with errors, while checking in console window, error is like this, "unreachable code after return statement",please give some suggestions
Excerpt of html:
<form name="empform" action="editformProcess.php" method="POST" id="empform1"><a name="profileform1"></a>
<div class="row">
<div class="col-md-5 box"><label>First Name </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="firstName" id="fName" required /></div>
</div>
<div class="row ErrorMessg">
<div class="col-md-5 "></div>
<div class="col-md-7 " id="firstNameErrorMsg"> </div>
</div>
<div class="row">
<div class="col-md-5 box"><label>Last Name </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="lastName" /></div>
</div>
<div class="row">
<h3>Contact Details </h3>
<div class="col-md-5 box"><label>Email Id </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="email" name="emailId" required /></div>
</div>
<div class="row">
<div class="col-md-5 box"><label>Mobile Number </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="mobileNumber" id= "mobNum" required /></div>
<div id="mobbox"></div>
</div>
<div class="row ErrorMessg">
<div class="col-md-5"><label></label></div>
<div class="col-md-7" id="mobileNumMess"> </div>
<div id="mobbox"></div>
</div>
<input type="submit" name="submitDetails" value="Submit Details" id="submit"/>
</form>
excerpt of jquery:
$(function(){
//firstNameErrorMsg
$("#firstNameErrorMsg").hide();
$("#mobileNumMess").hide();
var errorFirstName= false;
var mobileNum= false;
$("#fName").focusout(function(){
checkFirstName();
});
$("#mobNum").focusout(function(){
checkMobNum();
});
function checkFirstName(){
var fNameLength = $("#fName").val().length;
if(fNameLength < 5 || fNameLength > 20){
$("#firstNameErrorMsg").html("sholud be between 5-20 charecters ");
$("#firstNameErrorMsg").show();
errorFirstName= true;
}else
{
$("#firstNameErrorMsg").hide();
}
}
function checkMobNum(){
var pattern = new RegExp(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/);
if(pattern.test($("#mobNum").val())){
$("#mobileNumMess").hide();
}else{
$("#mobileNumMess").html("Invalid Mobile Number");
$("#mobileNumMess").show();
mobileNum = true;
console.log("h from begin sub");
}
}
$("#empform1").on('submit',function(){
//return true;
//console.log("h from begin2 sub1");
var errorFirstName= false;
var mobileNum= false;
checkFirstName();
checkMobNum();
//console.log("under var");
if(errorFirstName == false){
return true;
console.log("under if");
}else{
return false;
}
})
});
You need to correct your code in 2 places.
To solve form submit issue, you need to remove the variable declaration inside submit method
$("#empform1").on('submit',function(){
//return true;
//console.log("h from begin2 sub1");
//var errorFirstName= false;
//var mobileNum= false;
Dont forget to reset the var errorFirstName inside checkFirstName method
} else {
$("#firstNameErrorMsg").hide();
errorFirstName = false;
}]
When an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. Here,
if(errorFirstName == false){
return true;
console.log("under if");
}
is the error. The string is being logged after the return statement. Change this to:
if(errorFirstName == false){
console.log("under if");
return true;
}
I hope this was should fix it, though I am not able to reproduce the error.
Referring to any problems with submit, here's how I would suggest you edit the code:
function checkFirstName(){
var fNameLength = $("#fName").val().length;
if(fNameLength < 5 || fNameLength > 20){
$("#firstNameErrorMsg").html("sholud be between 5-20 charecters ");
$("#firstNameErrorMsg").show();
return true;
}else
{
$("#firstNameErrorMsg").hide();
return false
}
}
function checkMobNum(){
var pattern = new RegExp(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/);
if(pattern.test($("#mobNum").val())){
$("#mobileNumMess").hide();
return false;
}else{
$("#mobileNumMess").html("Invalid Mobile Number");
$("#mobileNumMess").show();
console.log("h from begin sub");
return true;
}
}
$("#empform1").on('submit',function(){
var errorFirstName= checkFirstName();
var mobileNum= checkMobNum();
if(errorFirstName == false){
return true;
console.log("under if");
}else{
return false;
}
})
What you apparently intended to do with the code was to modify the errorFirstName and mobileNum in the scope of the function (the event handler) according to the check functions. But it doesn't work that way.
When you changed the variables in the check functions, the global variable was referred first of all. That's not something I guess you had intended.
As a good practice, I suggest you return the test results, as I have in the edited code.
This problem could also be solved by removing the lines of code which declares local variables with the same name in the handler function.
when i click on span remove address it removes it from ui but not from the list and the printed value of removeItem is an empty string "".
and how can i pass the stringList to input value="" with id clientAdd without showing it on the input .
var stringList = [];
$("#clientAdd").keypress(function(e) {
if (e.which === 13) {
$(".target").append("<a href='#' class='tag'>" + "<span class='removeAddress'>" + '+' + "</span>" + this.value + "</a>");
stringList.push(this.value);
this.value = "";
console.log(stringList);
$(document).on("click", ".removeAddress", function() {
var removeItem = $(this).parent().parent().val();
console.log(removeItem);
stringList.splice($.inArray(removeItem, stringList), 1);
$(this).parent().remove();
console.log(stringList);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label>Address *</label>
<div class="target"></div>
<input type="text" id="clientAdd" name="address" value="" class="form-control required">
</div>
</div>
</div>
Try this
Its parent text not a parent of parent .so you need get the text value of the parent use with $(this).parent().clone().children().remove().end().text() .It will get the parent text only .end() documentation
After removing clicked element .you are create the array using remaining removeddress via map function
var stringList = [];
$("#clientAdd").keypress(function(e) {
if (e.which === 13) {
$(".target").append("<a href='#' class='tag'>" + "<span class='removeAddress'>" + '+' + "</span>" + this.value + "</a><br>");
stringList.push(this.value);
this.value = "";
console.log(stringList);
$(document).on("click", ".removeAddress", function() {
var removeItem = $(this).parent().clone().children().remove().end().text();
console.log(removeItem);
stringList = $('.removeAddress').map(function(){
return $(this).parent().clone().children().remove().end().text()
}).get()
$(this).parent().remove();
console.log(stringList);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label>Address *</label>
<div class="target"></div>
<input type="text" id="clientAdd" name="address" value="" class="form-control required">
</div>
</div>
</div>
you can hide whole input or you can use input type="hidden". Usually you have one input displayed for humans as a event trigger and input hidden for the value which is processed on the server side
<div class="row">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label>Address *</label>
<div class="target"></div>
<input type="text" id="clientAdd" name="address" value="" class="form-control required">
<input type="hidden" id="clientAddCode" name="addressCode">
</div>
</div>
</div>
var stringList = [];
$("#clientAdd").keypress(function (e) {
if (e.which === 13) {
$(".target").append("<a href='#' class='tag'>" +"<span class='removeAddress'>"+'+'+"</span>"+ this.value + "</a>");
stringList.push(this.value);
this.value = "";
console.log(stringList);
$("#clientAddCode").val(stringList);
$(document).on("click", ".removeAddress", function() {
var removeItem = $(this).parent().parent().val();
console.log(removeItem);
stringList.splice( $.inArray(removeItem, stringList ) ,1 );
$(this).parent().remove();
console.log(stringList);
$("#clientAddCode").val(stringList);
});
}
});
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.
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;
});
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.