prompt function does not accept input which only contains numbers - javascript

I have added confirmation dialog to input again the status I get before submitting.
That park works.
Problem is that prompt() function does not except inputing just numbers?
Is there anyway I can added that part to so it can pass?
$(".delete-status").click(function (ev, el) {
var status = $(this).data("status");
var statusInput = prompt("Confirm deletion by entering the status:");
if (statusInput === status) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
});
Any idea how to fix the code? I am pretty new at jQuery and JS. Thanks
I want to cover both cases. With string and with number.

jQuery's .data() method automatically parses the data as JSON if it can, so if it looks numeric it will return a number, not a string.
prompt() always returns a string (or null if you cancel).
So you need to convert status and statusInput to the same type if you want to compare them with ===. You can use parseInt() to convert the user input to an integer.
$(".delete-status").click(function(ev, el) {
var status = $(this).data("status");
var statusInput = parseInt(prompt("Confirm deletion by entering the status:"));
if (statusInput === status) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
});

You could convert statusInput string to a number.
This could be better but something along the lines of:
$(".delete-status").click(function (ev, el) {
var status = $(this).data("status");
var statusInput = prompt("Confirm deletion by entering the status:");
if (Number(statusInput) === Number(status)) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
})

Related

JavaScript function sending string but receiving Boolean value

I am facing the unexpected behavior of javascript function. Im an passing the ID of a field as string to function but it is receiving as bool value. Please help the code is below.
Function
function page_smooth_scroll(target_id) {
if (target_id =! null) {
$j('html, body').animate({
scrollTop: $j("#" + target_id).offset().top - 120
}, 500);
}
}
calling function
function validatePassword(){
var validPassword = false;
var pwd = $j("#Password").val().trim();
var cfmPwd = $j("#ConfirmPassword").val().trim();
if((pwd == "") || (cfmPwd == "")){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Please enter Password</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
if(pwd != cfmPwd){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Password does not match</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
validPassword = true;
}
}
return validPassword;
}
the image is below while debugging
passing string
receiving bool
if (target_id =! null) {
I think you mean a != b
Because a=!b means a = !b which means "assign the opposite boolean value", which will indeed turn anything into a boolean.
Next time if you think a function is "receiving a boolean", make sure to debug the value before running any statements. I'm sure it's still a string when going into the function.

If statements not initialising JavaScript

Here is my code for a simple HTML form with JavaScript Validation. I simply want to return an error message if the fields are blank.
At the moment the page just goes straight to the success.html page without initialising the javascript. Any help would be greatly appreciated!
Ok so I've made some changes and its still not working. Here is the edited code:
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value==="") {
msg+="You must enter your name \n";
document.ExamEntry.Name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value==="") {
msg+="You must enter the subject \n";
document.ExamEntry.Subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(msg===""){
return result;
}else{
alert(msg)
return result;
Thanks for all the contributions
The curly parentheses surrounding the logic following the below if statement are invalid
if (msg !== "") {
return result;
} {
alert(msg)
return result;
}
Simply, you should write:
if (msg !== "") {
return result;
}
alert(msg);
return result;
Am I reading this wrong or are your if statement logic backwards?
if (document.ExamEntry.name.value !== "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value !== "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
result by default is true. If you fail to enter a value for either fields, then !== "" will be false (because it does equal the empty string) and therefore result will be left true, which enables form submission.
Try:
if (document.ExamEntry.name.value === "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value === "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
Also, as others pointed out, you are missing an else statement:
if (msg !== "") {
return result;
} else {
alert(msg)
return result;
}
And finally, you mentioned this is Java. This is JavaScript. And no, JavaScript is not just a smaller version of Java. It is a very different language.
It looks like you are comparing with non-empty string while the comparision should have been for an empty string i.e.,if (document.ExamEntry.name.value !== "") { should be changed to if (document.ExamEntry.name.value == "") {
This implies to check for a a non empty string in the text box and redirect to the appropriate page (success page).
Also move the alert(msg) to the if (msg !== "") block. I think you would want to alert the user in case of empty text box.

Javascript OR statment result different in Chrome

I have a problem with following code:
var status = null;
var action = 1;
function test() {
if(status != null || action == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
I get expected results in Firefox and IE alert('I should be here'). But in Chrome i get alert('Why am i here?').
I'm not able to reproduce this for you, but I might just have the answer:
if(status !== null || action === 3) {
Compare the variable not just by value but also by type, by using an extra =
status and action var names seem too good to not be system reserved. maybe your chrome has something running with a status var allocated. try changing them to something else and see if it makes a difference.
var myStatus = null;
var myAction = 1;
function test() {
if(myStatus != null || myAction == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();

Javascript If statement evaluation not working correctly [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
So this is my code for some ajax that I'm doing.
function check_password(){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
},
function(response) {
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
return response.indexOf('success');
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
and here I'm trying to handle the return value from the check password function.
jQuery(function() {
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
} else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
} else if (check_password() != 73) {
hasError = true;
$("#password").after(check_password());
}
if (hasError == true) {
return false;
}
});
});
For some reason the if statement is returning true even when the index(return value) is 73. I test this by using jquery within the if statement to print out the value of the returning function and it prints out 73. I have a feeling my error is caused because of dynamically typed variables in javascript.
Typical asynchronous behavior issue of AJAX calls. You return response.indexOf('success'); from your AJAX callback, but since it is an asynchronous callback, there is nothing to return to. The rest of you check_password function has long finished when the callback is being called.
To fix this you need to completely restructure your code. In your click handler, you first need to call your post() function and then in the callback you need to go through your if/else if blocks.
Your function ´checkpassword()´ doesn't actually return a value.
It launches a request to a PHP-file and immediately returns (without a value).
You do specify a callback for when the call returns, but that never gets back to your original function.
You could do something like this:
function check_password(callback){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
callback(response.indexOf('success'));
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
jQuery(function(){
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
}
else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
}
else (
check_password(function(returnValue) {
if (returnValue != 73) {
hasError = true;
$("#password").after(check_password());
}
})){
}
if(hasError == true) {return false;}
});
});
Of course, this code just shows you how to get the value inside the other function, but you still need to handle the fact that you're other function doesn't return immediately and that for example the value of HasError is not set immediately.
Your problem is that you return from within a inner function, which will never ever work in JavaScript. Pass a callback:
function check_password(callback) {
// ...
callback(response.indexOf('success'));
}
// ...
check_password(function(result) {
if(result != 73) {
// ...
}
})
Just search for JavaScript AJAX and you will find a lot of sites to study. Here is one of them: http://www.html5rocks.com/en/tutorials/async/deferred/

What's wrong with this javascript code?

var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod != '' && newprod != null) {
$.ajax({
//posting code here
});
}
if (act != false) { document.location.href = window.location; }
The page is refresh in every condition even act false or not.
It is fired on an event.
Can anyone tell me why it page is refreshed in all condition?
var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod) { // not null, undefined or 0
$.ajax({
//posting code here
});
}
if (act) { window.location.reload(1); }
assuming that is what the code was supposed to do. document.location is deprecated and in theory read-only.
This should work
if( newprod != null && newproda.length != 0) {
//Execute the code
}
To the reason why it was always working was that newprod was not the same as ''.
As the question is what is wrong with that JavaScript code i will advise.
if(act) {
document.location.href = window.location;
}
You may want to learn more about false-y values in JavaScript. My guess is that your if statement is giving you some problems because it does not compare the way you think it should compare.

Categories