Javascript convert alert to string - javascript

I have this small javascript to validate form input.
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
I'm tryin to figure out how to get the "alert" message as a string to show it later on the page instead of popping this ridiculous box. Looks simple to me but i'm a big zero in js. Any help appreciated, Thanks !

The alert() method is what makes the big pop up box. If you want to save the value for later use save it to a variable. Something like:
var message = "";
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
message = "Some fields need correction:\n" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}

var alerter;
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alerter = "Some fields need correction:<br/>" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
document.body.innerHTML = alerter;

How about assigning the string to a property of "window" :
window.myAlert ="Some fields need correction:\n" + reason);
Then you can get it from anywhere:
document.body.innerHTML = window.myAlert;

Related

How to give alert message after all form validation is complete?

After the submit button for my form is clicked the function formvalidtion() is executed from a javascript file, below.
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
return FirstName(fname) && LastName(lname) && PhoneNumber(pnumber) && Email(email) && thankyou();
return false;
}
Example of individual validation.
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
As noted in the function formvalidtion() I have the function thankyou() referenced which is below.
function thankyou() {
if (formValidation() === true){
alert("Thank you for subscribing!");
}
}
The rest of the validation functions are working not this though, the acknowledgement alert is not appearing. TIA!
You send your function into a recursive pattern without a base case by allowing two functions call themselves(formValidation and thankYou). You can fix this by removing the conditional in the thankYou function
function thankyou() {
alert("Thank you for subscribing!");
}

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.

JSON object and string function

I am trying to call startsWith() string function on a JSON property value:
{"message":"xyzabc"}
var jsonResponse = JSON.parse(httpResponse.text);
var stringMessage = jsonResponse.message.toString();
if(stringMessage.startsWith('xyz')) {
...
}
but I get the error:
Object xyzabc has no method 'startsWith'
How can I do that?
The code is running on server side, Express on Node.js
It may be happen that your browser does not support the startsWith() function so you can use use the RegExp to overcame this problem like this...
var jsonObject={message:"xyzHELLO"};
var regex=new RegExp("^xyz");
if(regex.test(jsonObject["message"])){
alert("hello");
}
Live Demo HERE
[EDIT]
If you want to add the function startsWith() in your each and every string than you can add like this
if (String.prototype.startsWith !== "function") {
String.prototype.startsWith = function (searching) {
var regex = new RegExp("^" + searching);
if (regex.test(this.toString())) {
return true;
}
else {
return false;
}
}
}
and after that you can use like this:
var jsonObject = { message: "xyzHELLO" };
if (jsonObject["message"].toString().startsWith("xyz")) {
alert("start with");
}
else {
alert("not start with");
}
[EDIT]
if (String.prototype.startsWith !== "function") {
String.prototype.startsWith = function (searching) {
if (this.toString().indexOf(searching) == 0) {
return true;
}
else {
return false;
}
}
}
As per the comment by #nnnnnn and I also think it is good practice if we use the native function of the JavaScript, Thanks #nnnnnn.
Please double check your input JSON. Your code works like a charm with a correct JSON input in httpResponse.text.
var json = '{"message": "xyztest"}';
var jsonResponse = JSON.parse(json);
var stringMessage = jsonResponse.message.toString();
if(stringMessage.startsWith('xyz')) {
alert('It works!');
}
Also please make sure the browser you are working in supports startsWith method. Here you can find a list with all supported browsers.
If you need to work around the browser compatibility issues, you can use the widely supported indexOf method.
if(stringMessage.indexOf('xyz') === 0) {
alert('It works!');
}
HERE is a Fiddle for both cases.
Apparently, Js has startsWith function for the strings. However, using your own function to see if the string starts with the value should cause no error.
function StartsWith(s1, s2) {
return (s1.length >= s2.length && s1.substr(0, s2.length) == s2);
}
var jsonResponse = JSON.parse(httpResponse.text);
var stringMessage = jsonResponse.message.toString();
if(StartsWith(stringMessage,'xyz')) {
//Doing Stuff!
}

Why doesn't Chrome allow changing of style tag via JS?

I'm running this code:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=".concat(document.getElementById('name').value).concat(document.getElementById('domain').value), function(data) {
if(data == "true") {
document.getElementById('containerThree').style = "background-color:#20bb47;";
}else{
document.getElementById('containerThree').style = "background-color:#b33535;";
}
document.getElementById('avail').style = "color:#272727;";
document.getElementById('emt').style = "color:#272727;";
});
It works fine in FireFox, but in chrome not at all. I've tried using .style.background = "#mycolorcode" but it still doesn't work in chrome(and in that case, firefox too).
Try this:
if (data === 'true') {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
http://devdocs.io/html/element/style
http://youmightnotneedjquery.com/
NOTE: 'true' is a string. You would most likely would rather use the Boolean true.
Based on the latest edit to your question, does this cleanup of your surrounding code help?
jQuery.get('http://email.hackmailer.com/checkuser.php?email='
.concat(document.getElementById('name').value)
.concat(document.getElementById('domain').value),
function (data) {
if (data === true) {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
document.getElementById('avail').style.color = '#272727';
document.getElementById('emt').style.color = '#272727';
});
You don't need to send a string as 'true' to check a condition. Use it like:
var data = true; //use boolean but not 'true' as string.
Then you can simple use it as follows:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=" + document.getElementById('name').value + document.getElementById('domain').value, function(data) {
var colorValue = "#272727";
document.getElementById('containerThree').style.backgroundColor = data == "true"?"#20bb47":"#b33535";
document.getElementById('avail').style.color = colorValue;
document.getElementById('emt').style.color = colorValue;
});
BTW, I am not sure how .style = "background-color:#20bb47;"; is working for you.

Using javascript to check true/false condition on viewmodel

I am using local storage variable to hold the location of a users current progress. I have ran into a problem whereby if the last section that the user was on has been since deleted I am getting a target invocation must be set error. This is my code:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
I need to check using javascript that the localStorage course section is still existing in the database so I created the following ViewModel method:
public bool CourseSectionLaunchStillExistCheck(int courseSectionID)
{
this.TargetCourseSection = courseSectionRepository.Get(cs => cs.CourseSectionID == courseSectionID).FirstOrDefault();
if (this.TargetCourseSection != null)
{
return true;
}
else
{
return false;
}
}
But when I try to use the following javascript:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
if ('#Model.CourseSectionLaunchStillExistCheck(id)' != true) {
var id = '#Model.CourseSections.First().CourseSectionID';
}
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
It is failing to recognise the id parameter saying it does not exist in the current context. How can I ensure that the course section exists using javascript before setting the variable?
Could I use a post such as:
var postData = { 'courseSectionID': id };
$.post('/Course/CourseSectionLaunchStillExistCheck/', postData, function (data) {
});
and then how could i check if the result of this post data would be true or false?

Categories