Alert textbox is empty when checkbox is checked - javascript

This might be a bit confusing but bear with me.
I need 2 textbox and 1 checkbox.
When the checkbox is checked, it needs to check whether the textboxes are filled or not.
If the textboxes are filled in, it will do nothing.
I'm really struggling with this so I would really appreciate it.
If you don't understand what I even said, here's the question that I need to solve.
*In page order.html, create a checkbox with label “same as delivery address” somewhere  appropriate near the fields for billing address. When this checkbox is checked, the fields for  billing address will be filled with the delivery address automatically. If the delivery address is  not completed when this checkbox is checked, display an alert or inline message: “Please  enter your delivery address first”. *
I've managed to do the duplicate part with these codes.(address and post codes are separated)
function copy() {
var daddress = document.getElementById("daddress");
var baddress = document.getElementById("baddress");
baddress.value = daddress.value;
var dpost = document.getElementById("dpost");
var bpost = document.getElementById("bpost");
bpost.value = dpost.value;
}
But I cannot figure out the part after this.
Here's the code for the checkbox
<input id="duplicate" type="checkbox" name="duplicate"
value="Duplicate" onClick="copy();"/>Same as delivery address
<p id="dalert"><b><i>Please  enter your delivery address first</i></b><p>

In this case you could use a textarea for the address:
<textarea id="delivery-address"></textarea>
Then you would use JavaScript to get the contents of it with:
var deliveryAddress = document.getElementById("delivery-address").value.trim();
To check if they entered an address, you would use:
if (deliveryAddress === "") { ... }
In most cases, the address would be broken up into several inputs, often two lines for the street address, an input for city, state and postal code.
An alert is displayed like so:
alert('Some text');

You can use an if statement to check whether there's any input before setting them.
if (daddress.value && dpost.value) {
baddress.value = daddress.value;
bpost.value = dpost.value;
} else {
alert('Please enter your delivery address first!');
e.preventDefault(); // Stops checkbox from becoming checked.
}
JSFiddle
Edit: Forgot to mention that to use e.preventDefault(), you need to change your function to accept the e parameter (function copy(e) {...}) and pass event in your onclick event (onclick="copy(event)"). You'll see those in the JSFiddle.

Related

Use app.response to obtain text and then append to text from another field

All,
I have been trying to figure this out for a few days now, but to no avail.
I am trying to use a check mark as the trigger to first ask the user to input some text, and then "concatenate" that text with the text from a previous text field.
I can copy the text form one field to the other, but can not figure out how to incorporate the app.response part of the goal.
Any help would be appreciated
here is what I am using currently and it is located in Actions as a "Mouse up - Run a Javascript"
var fFrom = this.getField("MOB Address");
var fTo = this.getField("Relative");
if(event.target.value=="Off"){
fTo.readonly=false;
fto.value="";
}else{
fTo.readonly=true;
fTo.value=fFrom.value;
The return value from app.response is the entered text. You'd use it like this where your field is named "foo"...
var responseText = app.response({
cQuestion: "How are you today?",
cTitle: "Your Health Status",
cDefault: "Fine",
cLabel: "Response:"
});
if (responseText != null) {
var originalValue = this.getField("foo").value;
this.getField("foo").value = originalValue + " " + responseText;
}
The text entered into the response dialog will get appended to the end of any text already in the "foo" field. I'm not sure how you want that added to your code above but hat's how it's used.
Joel,
OK...I have it working, and I thik I understand what you did. I had tried something similar, but couldn't get it to work for some reason.
Anyway...my question now is...since I am using a checkmark field as the trigger for this action, how can I build in code so that this only happens when the checkmark is clicked to "true" or "Yes"? I would also like to clear the receiving field if the checkmark is unchecked or set to "False" or "Null".
As it stands, anytime you click the checkmark field to mark is checked or unchecked, it runs the code.
Here is what I ended up with:
var cRes = app.response({cQuestion: "Enter Nearest Relative First and Last name:", cTitle: "Nearest Relative", cDefault: "", cLabel: "Response:"
});
if(cRes != null){
var fFrom = this.getField("MOB Address").value;
this.getField("Relative").value = cRes + "\r" + fFrom;
}
I tried integrating my original code with this, but...couldn't get it to work.
Again...thanks for your help!

jQuery Regex Check on field works but alert message doesn't change

I have this function to validate postcodes (UK):
/* validate Post Code */
$.fn.validatePostCode = function(postcode)
{
regex = /^[A-Za-z]{1,2}\d{1,2}\s*\d{1}[A-Za-z]{2}$/i;
if (!regex.test(postcode)) {
return false;
}
};
as you can see it's just a simple regex checking for amount of character types at certain points.
To trigger it (or at least in the part I'm using it for) I use:
$(document).ready(function()
{
$('#nextBtn').on('click', function()
{
var postcode = $('#postcode').val();
console.log(postcode);
if (!$.fn.validatePostCode(postcode)) {
alert('hi');
} else {
alert('not valid');
}
});
});
doing the console.log is so I can see the value of the postcode each check, and I can see it updates. However, upon changing the input so I know it should be wrong still alert('hi') instead of Not Valid. I've even added a console.log in my validate function and that shows when the postcode is invalid, so why doesn't the alert message change each click?
I used this to validate my regex: http://www.regextester.com/ and it said my pattern was ok when I typed various postcodes in, so I'm a little lost at the moment, any ideas?
Thanks
Ok, so I found the solution rather quickly - it's because my function doesn't return a value until it fails. Needed to add a return true; outside of the if statement.
Hope this helps anyone who has a similar problem :)

How to select and set multiple textboxes text in jquery

Please I have my Jquery code that I want to do few things since. I have a form with a bunch of textboxes. I want to validate each textbox to allow numbers only. To also display error where not number.
var validateForm = function(frm){
var isValid = true;
resetError();
$(":text").each(function(variable){
console.log("The variable is" , variable);
if(!isNormalInteger(variable.val))
{
$("#error"+variable.id).text("Please enter an integer value");
isValid = false;
}
});
if(!isValid)
return false;
};
The above fails. When I print the variable on my console I was getting numbers 0 - 9. My textboxes where empty yet, it returns numbers. I tried variable.val() still fails and return numbers. I modified my select to
$("input[type=text]", frm).each();
Where my form is my form selected by id. It also failed. Below is the example of my html label and textbox. I have about ten of them
<div class="grid-grid-8">
<input class=" text" id="id" name="name" type="text">
<br>
<p class="hint">Once this limit is reached, you may no longer deposit.</p>
<p class="errorfield" id="errorMAXCASHBAL"></p>
Please how do I select them properly? Moreover, my reset function above also returns incrementing integers for value. The p property is of class errorField and I want to set the text property. Please how do I achieve this? Previously I tried the class name only $(.errorField). It also failed. Any help would be appreciated.
var resetError = function(){
//reset error to empty
$("p errorfield").each(function(value){
console.log("the val", value);
//value.text() = '';
});
};
//filter non integer/numbers
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
The main problem is your selectors in javascript. And as laszlokiss88 stated wrong usage of .each() function.
Here is a working example of your code: jsFiddle in this example all .each() functions use $(this) selector inside instead of index and value
You are using .each wrong because the first parameter is the index and the second is the element. Check the documentation.
Moreover, the correct selector for the resetError is: p.errorfield
So, you should modify your code to look something like this:
var resetError = function(){
$("p.errorfield").each(function (idx, element) {
$(element).text("");
});
};
With this, I believe you can fix the upper function as well. ;)

Validate form required fields based on class?

What would a JavaScript script be that, on submit, gets all form elements with class="required" and if they're empty, displays an alert box, "you must fill out so-and-so"?
I was thinking of an if-else, and in the if section we would get a while that loops through all the class=required elements, and the else would submit the form.
There are many many JavaScript libraries on the internet that do exactly this.
Try this one:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Or try a Google search for JavaScript Form Validation.
It is fairly easy to loop over the elements of a form and check that those with a certain class have a value that meets certain criteria:
<form name="f0" onsubmit="return validate(this);">
<input name="inp0" class="required" >
<input name="inp2" class="required" >
<input type="submit">
</form>
<script type="text/javascript">
var validate = (function() {
var reClass = /(^|\s)required(\s|$)/; // Field is required
var reValue = /^\s*$/; // Match all whitespace
return function (form) {
var elements = form.elements;
var el;
for (var i=0, iLen=elements.length; i<iLen; i++) {
el = elements[i];
if (reClass.test(el.className) && reValue.test(el.value)) {
// Required field has no value or only whitespace
// Advise user to fix
alert('please fix ' + el.name);
return false;
}
}
}
}());
</script>
The above is just an example to show the strategy.
Using an alert is less than optimal, usually an area is set aside adjacent to the required fields so that error messages can be written there to direct the user's attention to the invalid fields. You can also set all the error messages in one go, then return, rather than one at a time.
Edit—updating multiple errors
Have an element adjacent to each control to be validated with an id like the element's, so if an input is called firstName, the error element might have an id of firstName-err. When an error is found, it's easy to get the related element and put a message in it.
To do all at once, use a flag to remember if there are any errors, say "isValid" that is set to true by default. If you find any errors, set it to false. Then return it at the end.
Using the example above, the HTML might look like:
<input name="firstName" class="required" >
<span id="firstName-err" class="errMsg"></span>
Errors for firstName will be written to firstName-err.
In the script, if an error is found:
// At the top
var isValid = true;
var errEl;
...
// When entering the for loop
el = elements[i];
errEl = document.getElementById(el.name + '-err');
// when error found
isValid = false;
if (errEl) errEl.innerHTML = '... error message ...';
// else if error not found
// remove message whether there is one or not
if (errEl) errEl.innerHTML = '';
...
// At the end
return isValid;
You can also use a popup to show the errors, however that is really annoying and the users must dismiss the popup to fix the errors. Much better to just write next to each one what is wrong and let the user fix things in their own time.

Javascript not working in firefox

I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";

Categories