Ive got some javascript im using to validate a form which works fine but I now need to add a checkbox which needs to be checked before the form submits. The name of the checkbox is terms in the html and ive managed to get it to not submit the form using the code below.
$(document).ready(function(){
$("#sendmail").click(function(){
var valid = '';
var isr = ' is required.';
var name = $("#name").val();
var mail = $("#mail").val();
var subject = $("#subject").val();
var country = $("#country").val();
if( !$("#terms").is(":checked") ){
valid += '<br />Please accept the terms and conditions.';
}
if (name.length<1) {
valid += '<br />Name'+isr;
}
if (!mail.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<br />A valid Email'+isr;
}
if (subject.length<1) {
valid += '<br />Website Link'+isr;
}
if (country.length<1) {
valid += '<br />Country'+isr;
}
if (valid!='') {
$("#response").fadeIn("slow");
$("#response").html("Error:"+valid);
setTimeout('$("#response").fadeOut("slow")',4000);
}
else {
var datastr ='name=' + name + '&mail=' + mail + '&subject=' + subject + '&country=' + country;
$("#response").css("display", "block");
$("#response").html("<img src='http://infashionation.com/female/images/response.jpg'>");
$("#response").fadeIn("slow");
setTimeout("send('"+datastr+"')",2000);
}
return false;
});
The problem is it now doesnt submit regardless of whether box is checked or not.
Ive been searched for some information to help me with this for a while but no luck so thought I would ask here to see if anyone can help me.
There appears to be an extra exclamation point after the valid variable. I suggest also using a javascript debugger.
if (valid!='') {
You're missing a closing curly brace for your .ready function.
It doesn't look like you've closed the $(document).ready() function. You close the sendmail click function, but not the main function. I think the tail end of your code should look like this:
}
return false;
}); // close sendmail function
}); // close document.ready
If that happened because of copying it to SO, then disregard this, but if this is in your code, your browser will probably not do a thing and appear not to react to the JavaScript.
Related
My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable
I have a Javascript problem that I cannot find the answer to. Hope you can help me.
I have this element called 'scanValue', that has an onFocus and an onBlur trigger:
<input name="scanValue" class="searchFormText" style="width: 220px; font-size: 22px;" onfocus="onFocusElement(this)" onblur="onBlurElement(this)" type="text" maxLength="20" value="510210006823414"/>
If I tab out of the field the onBlurElement() function is called as expected:
function onBlurElement(object) {
alert('onBlurElement: Start blur on ' + object.name + ' (old val = ' + prevObjectVal + ', new val = ' + object.value + ')');
if (object.value !== prevObjectVal) {
check(object);
var checkFcn = 'check' + object.name;
var fcnParms = [object.value];
var fcn = window[checkFcn];
alert('onBlurElement: check if ' + checkFcn + ' is a function: ' + (typeof fcn));
if (typeof fcn == 'function') {
alert('fcnParms length = ' + fcnParms.length + '. ToString= ' + fcnParms.toString());
alert('fcnParms[0] length = ' + fcnParms[0].length + '. ToString= ' + fcnParms.toString());
fcn.apply(fcn, fcnParms);
}
}
}
Now this dynamic function call (fcn.apply()) should call the function 'checkscanValue(val)', but nothing happens. EXCEPT when I add an alert() to this function OR if I fire up the IE standard developer tools. In other words, if I track or debug the checkscanValue() function everything works, otherwise is does nothing. I've tried several different things, but nothing seems to work. I doubt this could have anything to do with the form being submitted with method post, but maybe someone could help me on that.
Code for the checkscanValue() function:
function checkscanValue(val) {
console.info('checkscanValue: start function');
document.forms[0].airNumber.value = 'test';
// Check if the scanned value is valid for submitting the form
if (val[0].length === 15) {
document.forms[0].submit();
}
}
Everything is working fine except that the "val" parameter that you are passing to the checkscanvalue function is the string that the user entered or is there by default.
So val[0] returns the first character of the string whose length can't be 15 and hence the check fails and nothing happens.
hope it helps!
This seems to answer my question: 'console' is undefined error for Internet Explorer
I've been using the function console.info() which is undefined if the console window of IE was never opened. This caused the function to stop. If I replaced it with an alert() it obviously worked and if I opened the console of IE, the console.info function was defined.
How do I use JavaScript to write cookies from form fields, and then print the info in an alert or hidden div?
Here is an example of what I have tried thus far.....
<script type="text/javascript">
function cookieForm() {
document.cookie = "name_first" + encodeURIComponent(document.forms[0].name_first.value);
}
function printCustomerInfo() {
var queryData = decodeURIComponent(document.cookie);
var queryArray = queryData.split(";");
if (document.cookie) {
window.alert("Your info. is:" + queryArray[0]);
window.alert[0].name_last.value = QueryArray[1].substring(queryArray[1].lastIndexOf("=") + 1);
}
}
</script>
<input type="submit" value="Submit" onclick="cookieForm(), printCustomerInfo()"/>
First, you're missing the "=" in the cookie string:
document.cookie = "name_first=" + encodeURIComponent(document.forms[0].name_first.value);
Second, your queryData has no ";" to split by, and no last name value - at least from what you show here.
This I do not understand:
window.alert[0].name_last.value = ...
I would call a single function from your event, and let that parent both setting the cookie and parsing it. That way you can at least debug it better.
re: a div, you could do something like this:
document.getElementById("yourDiv").innerHTML = "Your info. is:" + queryArray[0];
document.getElementById("yourDiv").style.visibility = 'visible';
But in general it's better to use jquery for manipulating elements, because it mitigates browser differences, though it wouldn't matter in this case:
$("yourDiv").html("Your info. is:" + queryArray[0]);
$("yourDiv").css ( { 'visibility': 'visible' } );
Good luck.
I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.
I need the values of the name, address, size, and topping fields to appear in a text box. Without problems the name and address appears correctly. However I can't seen to get the size function to work. It is a radio button, and thus I need only one size to appear. I haven't even tried an if else for the checkbox yet. Here is my code
<html>
<head>
<script>
function pizza() {
document.pizzaboy.comments.value = "Name:" + " " + pizzaboy.name.value + "\n" + "Address:" + " " + pizzaboy.address.value + "\n" + document.getElementById("small").value + document.getElementById("medium").value + document.getElementById("large").value + "\n" + pizzaboy.toppings.value;
{
var rslt = "";
if (document.pizzaboy.size[0].checked) {
rslt = rslt + "Size=Small\n";
} else if (document.pizzaboy.size[1].checked) {
rslt = rslt + "Size=Medium\n";
} else rslt = rslt + "Size=Large\n";
return rslt;
}
}
</head>
The second Javascript bracket might be throwing you an error, keeping your code from running correctly.
In this post, several (more general) ways to get values of radio buttons are explained:
Checking Value of Radio Button Group via JavaScript?
The first answer is using jQuery, but the following answers will help you i think.
You should try this. Answer here if you need further assistance.