I am creating a custom control in Asp.net and there is a client side validation on an input field.
Control Code (extract of the whole code):
output.AddAttribute("OnBlur", "ValidateText(this)");
output.RenderBeginTag(HtmlTextWriterTag.Input);
And here is the JS code:
function ValidateText(ctl) {
if (ctl.value == '') {
alert("Enter something!");
ctl.focus();
}
}
I want the function to show an alert and then make the input field focused.
However, when I run the code, the alert box does not go away after a click or pressing the Enter key and I need to do it couple of times.
What is wrong in the code?
function ValidateText(ctl) {
if (ctl === '' || ctl === undefined) {
alert("Enter something!");
ctl.focus();
}
}
Related
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
can someone explain this to me? why is it prompt() running again?
And please give me some advice where and what should i change to have a better code. thank you.
function welcomeGuest() {
do {
guestName = prompt("Welcome to my Anime Website! May I know your name?");
if (guestName === null || guestName === false) {
alert("Please come back again.");
window.close();
}
if (guestName === "") {
alert("Please enter your name!");
} else if (guestName.length < 4) {
alert("Your name should be atleast 4 characters!");
} else if (!(isNaN(guestName))) {
alert("Your name can't be number!");
} else {
guestNamesmall = guestName.slice(1, guestName.length);
alert("Welcome to my Anime Website, " + guestName.charAt(0).toUpperCase() + guestNamesmall + "!");
//bodyContent();
}
} while (guestName.length < 4 || !(isNaN(guestName)));
}
// EDIT: adding call to function for demo purposes
welcomeGuest();
EDIT : I'm sorry but my question is when I enter correct input(it should go to else statement, right?) but what happens to me is that the prompt is running again if else statement is met. Why is that?
if you call your welcomeGuest function only once and the condition inside your while loop is respected guestName.length < 4 || !(isNaN(guestName))it will not running again.
The reason prompt is showing up again is because you have it in a loop until your condition is met. Therefore if guestName.length < 4 || !(isNaN(guestName)) is never met, then it will continue to show.
I would avoid using a loop for something like this. You can use css to prevent a user from going through your site instead of continuously prompting them through a loop. Then use events to handle your logic. Do you have a submit/enter button? Then add your logic on the click event. If not, then you can do it on the key down event and look for the enter key.
for example:
var textbox = document.getElementById("idOfTextbox")
with option 1
textbox.addEventListener("keydown", function(event) {
//stop the click event from propagating
event.preventDefault();
//check if enter key was clicked (#13)
if (event.keyCode == 13) {
//do your logic to verify pass/fail of user input
}
});
or option 2
textbox.addEventListener("click", function(event) {
//stop the click event from propagating
event.preventDefault();
//do your logic to verify pass/fail of user input
});
There are other events you may use, but I think these two would be the most beneficial in this situation.
Image of form that uses AJAX & JS
I've currently got a maintainer that uses AJAX so when I type a number into the "Order No" field the "Calc" field then gets updated with the "Account" associated with the Order No. It all works however the "Calc" field doesn't fill with the account number until a click away from the Order No field has been done which means that if you were to press the enter key after typing the number the calc is still blank when the checks were made to see if the account and calc numbers are the same.. If you were to type the number then click the "Accept" button the update is then done so the checks then work as expected. So I was wondering if there is a way so that this field could get updated without an extra click.
One solution I came up with was by doing the checks such as account==calc and calc != "" twice so it would run a function where the check would always say that the calc field is blank (as it hasn't updated at this point) which would return an alert saying "Blank" then after returning the alert it would run another function which is exactly the same to do the check again and this time it would work as expected but once the alert is taken out its as if it hasn't got that moments wait which allows for the Calc field to be updated in time.
Its hard for me to post all the code as I use a system that does all the AJAX behind the scenes for you but let me try explain how the AJAX works. Whatever you put in the Order No field will be sent to an external retrieval application that would check to see what account number is associated with the order no and then return it to the Calc field. If then the account and the calc field numbers match submit the form else say its an incorrect order number for that specific customer.
Here are the two JavaScript functions:
function testerRun() {
var abc = ('${row.CUSN760?html}').toString();
var def = document.getElementById("CALCULA001").value;
if (abc == def && abc != "") {
//alert("Order Number & Account Number Match!");
document.getElementById('FORM_M07052').submit();
return true;
} else if (document.getElementById('ORDN760').value == "") {
document.getElementById('FORM_M07052').submit();
return true;
} else {
//alert("Blank First Step!");
finalStep();
}
}
function finalStep() {
if (document.getElementById("CALCULA001").value == "") {
alert("Customers Account Details Need Amending..");
return false;
} else {
var abc = ('${row.CUSN760?html}').toString();
var def = document.getElementById("CALCULA001").value;
if (abc == def && abc != "") {
//alert("Order Number & Account Number Match!");
document.getElementById('FORM_M07052').submit();
return true;
} else if (document.getElementById('ORDN760').value == "") {
document.getElementById('FORM_M07052').submit();
return true;
} else {
alert("Order Number & Account Number Do Not Match!");
return false;
}
}
}
And here is where the script is called:
<input class="btn btn-primary accept" id="btnaccept" name="btn_accept" onclick="testerRun();return false" type="submit" value="Accept" />
#Shreyas Sorry there is no blur or change as im using a system called MRC and so they use behind the scenes AJAX scripts to handle thigns like this what I don't have access too so I need some sort of work around. Its only an issue when the user clicks enter in the order no field after entering the order number without doing anything else on the form as it doesn't update until the order number is deselected.
document.getElementById('ORDN760').onkeydown = function(event){
if (event.which == 13 || event.keyCode == 13) {
document.getElementById('ORDN760').blur();
testerRun();
}
}
Function call not working though doesn't seem to do anything just sits there after blur.
Add a keypress handler on the Order No field, which listens for the Enter key, and submits the form when Enter is pressed.
document.getElementById('ORDN760').onkeydown = function(event){
if (event.which == 13 || event.keyCode == 13) {
document.getElementById('ORDN760').blur();
return false;
}
}
Hi all im new to jscipt,,, well, programming in general to be honest, but learning slowly for personal use.
I seek guidence on how i could place all the textboxes(inputs) in my index file into a list container, loop through them to check if they are empty or not before clicking the calculate button. If they are empty then inform the user of which one is empty.
Also, is there a way of preventing users from entering text into the textboxes and numbers only.
Background: im creating a form that requires all fields to be populate with numbers(in hours), a graph will then be generated from those values.
ive placed the file in skydrive for folks to download with the link below.
Index file
I did try the following but this alerts me regardless of weather the texboxes are populate or not.
function checkInputsGenerateGraph()
{
if( $('#hutz-hoursInput').val() == ""||$('#hutz-weeksPerYearInput').val() == ""||$('#hutz-jobsPerWeekInput').val() == ""||$('#hutz-hourlyMachineRateInput').val() == ""||$('#hutz-maintneneceDowntimeInput').val() == ""||$('#hutz-scrapRateInput').val() == ""||$('#hutz-toolsPerJobInput').val() == ""||$('#hutz-timeToLoadToolInput').val() == ""||$('#hutz-timeToSetPartsInput').val() == "")
{
alert('One them is empty!!');
}
else
{
$("#hutz-graph").slideDown();
$("#hutz-lblImproveMyProcess").slideUp();
$("#hutz-hoursInput").slideUp();
$("#hutz-weeksPerYearInput").slideUp();
$("#hutz-jobsPerWeekInput").slideUp();
$("#hutz-ourlyMachineRateInput").slideUp();
$("#hutz-ntneneceDowntimeInput").slideUp();
$("#hutz-scrapRateInput").slideUp();
$("#hutz-toolsPerJobInput").slideUp();
$("#hutz-timeToLoadToolInput").slideUp();
$("#hutz-timeToSetPartsInput").slideUp();
$("#hutz-lblMachineDetails").slideUp();
$("#hutz-lblPartSetting").slideUp();
$("#hutzcurrencyPreferenceInput").slideUp();
createChart();
}
}
First off, give all the required elements a common class, for examples sake we'll call this required:
<input type="text" class="required" id="hutz-hoursInput" />
Then, when your checkInputsGenerateGraph() function is called, you can loop over the required elements and check them:
$('.required').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
}
});
You could also do something like the following to remove all non-digits from your inputs:
$('.required').change(function() {
this.value = this.value.replace(/[^\d]+/, '');
});
See it in action
Hope that points you in the right direction!
edit
Here's a complete example:-
function checkInputsGenerateGraph() {
var isValid = true;
$('.example').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
isValid = false;
}
});
if (isValid) {
alert('do calculations!');
}
}
So, loop over all of the elements first, and make sure they are all populated. If not, set isValid to false so that once the loop completes, the calculations are not performed.
I've written some JavaScript/jQuery code that adds a users email to my newsletter database. There is a "subscribe" button to start the process, but I also wanted the user to be able to hit return for usability.
Weirdly, the code works for both the button and when the return key is hit in that the email is added to the database, but the callback function which just displays an alert is only triggered when the button is hit, not when the return key has been pressed.
$('#newsletter_button').click(function(event) {
newsletterSignup();
});
$('#newsletter_email').bind('keyup', function(event) { newsReturn(event); });
function newsletterSignup() {
var email = $.trim($('#newsletter_email').val());
if(!validateEmail(email)) {
alert('Please enter a valid email');
return false;
} else {
// add email to database
$.post('newsletterSignup.php',
{ email: email },
function(data) {alert(data);}
);
$('#newsletter_email').val("");
}
}
function newsReturn(evt) {
if (evt.keyCode == 13) {
newsletterSignup();
}
}
The function has to work the same no matter how it's been called surely! Like I say the post function is obviously being called both times because the email is being added to the database.
The only thing I can think of is that it's something to do with events. Not sure what though.
Browser behaviour for what happens when Enter is pressed is quirky. Whether the submit button is considered to be ‘clicked’ on Enter press varies between browsers and also depends on (a) the number of buttons in the form, and (b) the number of text inputs in the form. Typically when there is one text field and one button, the button won't be considered ‘successful’, you won't get a click event, and the button's name/value pair wouldn't be included in the submitted form values.
Additionally, trapping Enter keypresses in input fields is unreliable and shouldn't be done. This will fire in various circumstances when the Enter press shouldn't submit the form (eg when IMEs are in use), won't fire in places that should submit the form (eg some other element in the form has focus), and again there are browser differences.
So avoid all this pain: always bind to the submit event on the <form> containing the elements, instead of trying to second-guess what UI events should trigger that submission.
The first thing I can think of is evt.keyCode -- try using evt.which (a jQuery property which unifies the different browser behaviors).
Edit: Now I noticed the second alert. Your code is a tad messy, let's clean it up and see if the problem persists:
$('#newsletter_button').click(newsletterSignup);
$('#newsletter_email').keyup(newsReturn);
function newsletterSignup(e) {
e.preventDefault();
var email = $.trim($('#newsletter_email').val());
if (!validateEmail(email)) {
alert('Please enter a valid email');
} else {
// add email to database
$.post('newsletterSignup.php',
{ email: email },
function (data) { alert(data); }
);
$('#newsletter_email').val('');
}
return false;
}
function newsReturn(e) {
if (e.which === 13) {
newsletterSignup.apply(this, arguments);
}
}
Also, I don't know what your markup looks like, but if you were to use a form:
<form action="newsletterSignup.php" method="post" id="newsletter-form">
<input type="text" id="newsletter-email" name="newsletter_email"/>
<button type="submit">Go-go-gadget!</button>
</form>
Then you can skip the keyup stuff:
$('#newsletter-form').submit(newsletterSignup);
function newsletterSignup(e) {
e.preventDefault();
var email = $.trim($('#newsletter-email').val());
if (!validateEmail(email)) {
alert('Please enter a valid email');
return false;
} else {
// add email to database
$.post(this.action,
{ email: email },
function (data) { alert(data); }
);
$('#newsletter-email').val('');
}
return false;
}
Plus, people will be able to sign up even if you have a JavaScript problem on the page.