Create Bootstrap alert in JQuery - javascript

I'm new to bootstrap and was using noty before to generate alerts, however I'd like to try and do this without adding more plugins because bootstrap is already somewhat heavy in loading. I can create the text easily enough, it's just when I add the class in.
This is my Jquery:
$(function(){
$("#passsubmit").click(function(event){
event.preventDefault();
$(".error").hide();
var hasError = false;
var newpass = $("#password").val();
var checkVal = $("#password-check").val();
if (newpass == '') {
$("#password").after('<span class="error">Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#password-check").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (newpass != checkVal ) {
$("#password-check").after('<span class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) {return false;}
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {newpass:newpass},
success: function(){
//alert("Password Changed");
$("#password").val("")
$("#password-check").val("");
$(document.createElement('<div class="alert alert-success">Password Changed</div>'));
}
});
};
});
});
This is the part it is failing on due to an invalid character, which I assume is the "
$(document.createElement('<div class="alert alert-success">Password Changed</div>'));
I know that I could simply have this in the html:
<div class="alert alert-success" style="visibility: hidden">Password Changed</div>
And then just show it, but that wouldn't be particularly good when I want many different alerts across multiple pages...
There must be a better way of doing this?
Thank you :)

You just have you syntaxes mixed up:
document.createElement(tagName)
is a DOM method that takes a single tag name as a string.
$(html)
is a jQuery method that will return DOM elements given a complex HTML string.
You typically only use one, and each for its own purpose.
Then, just figure out where you want the new div to go, pick any DOM insertion method*, and then call like this:
$('#selector').after('<div class="alert alert-success">Password Changed</div>');
Here's a working Demo in fiddle
* DOM Insertion Types:
There are more methods, but these are some popular ones
Around
Inside
Append
Prepend
Outside
After
Before

Related

Changing value of a text box is not working

My HTML(simplified):
<input class="text" type="text" id="emailbox" value="None">
Note: content1 is the ID of a div that contains the email retrieved from a file using PHP and this part works (it returns the email)
My Javascript:
var email = $.trim(document.getElementById('content1').textContent);
if (!email == "") { document.getElementById("emailbox").value = email; }
The value of the input box is not changing at all
The error is with the line
document.getElementById("emailbox").value = email;
or with the html
ALL CODE: https://pastebin.com/5JSLzHdw
I grabbed your Pastebin code, and if I set the content of your content1 div to be this:
<div id="content1" style="display: none;">EXAMPLE#EXAMPLE.COM</div>
then the following code works as a replacement for the script starting at line 327. This is completely unstyled and I haven't changed any of the code except the essential to make it work.
<script>
$(document).ready(function(){
var email = document.getElementById('content1').textContent;
var register = document.getElementById("para7");
var login = document.getElementById("para8");
var logout = document.getElementById("para9");
if (email !== "") {
register.style.display = "none";
login.style.display = "none";
// It's an input so you need to set VALUE, not innerHTML
document.getElementById('mailbox').value = email;
console.log("We are here")
} else {
window.location.href = "../login/";
logout.style.display = "none";
}
document.getElementById("logo").addEventListener("click",function(){
document.getElementById("homebutton").click();
});
document.getElementById("account").addEventListener("click",function(){
if(!email == ""){
document.getElementById("accountbutton").click();
}
});
})
</script>
Others correctly commented that you shouldn't run your code until the document is ready, hence wrapping it inside that jQuery ready handler.
As you are using jQuery, I would suggest replacing all of your document.getElementById("whatever") instances with the jQuery method $("#whatever") as it will make the code more concise.
If I try your code like this, then document.getElementById('content1') returns null
Did you wrap your code in
window.onload = function() {
// run your script in here
}
or for jQuery
$(document).ready(function() {
...
}
Otherwise your code may try to access the DOM while it isn't ready yet.
See here https://stackoverflow.com/a/13921149/11472484 and here Running jQuery code before the DOM is ready?

Uncaught TypeError: Cannot set property 'display' of undefined

I am in the process of migrating an existing platform to a new server. I am taking the opportunity to upgrade PHP ect and standardise/debug the code as the previous maintainers have had different standards.
I have opted for PHP version 5.4.33 for now, once I have managed to move everything over to mysqli I will look to go to a more recent version. I didnt think anything server side would make a difference to AJAX/JS? As far as I am aware is it not client side?
Since I have moved the code over I am having issues with AJAX/JS. I am not the greatest at AJAX/JS and could use some assistance please. Even though every submit works differently through the entire platform I do not want to remove the AJAX/JS that already exists. I will most likely use it as an opportunity to how to use it as it makes end user experience smoother.
Using Chrome to debug I am receiving the following error on clicking the Save button:
Uncaught TypeError: Cannot set property 'display' of undefined
email_user
onclick
This is the Save button code
<span id="loading" style="color: red; font-size: x-small; display: none; text-decoration: blink;">Loading... Please wait..</span><input type="button" value="Save" class="save" onclick="if(validate()){ email_user(); }" />
This is the function code for validate()
function validate() {
var errorString = "";
if(isBlank(document.getElementById("forename").value)) {
errorString += " - Please input a forename\n";
}
if(isBlank(document.getElementById("surname").value)) {
errorString += " - Please input a surname\n";
}
if(isBlank(document.getElementById("company_name").value)) {
errorString += " - Please select a company\n";
}
if(document.getElementById("username").value != "" || document.getElementById("password").value != "") {
if(isBlank(document.getElementById("username").value)) {
errorString += " - Please input a username\n";
}
if(isBlank(document.getElementById("password").value)) {
errorString += " - Please select a password\n";
}
}
//if not a solicitor then cases mandatory
if(document.getElementById("company_role_type_id").value == 2) {
if(document.getElementById("other_view_if").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(document.getElementById("company_role_type_id").value == 3) {
if(document.getElementById("other_view_ea").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(errorString) {
alert('Please correct the following items:-\n\n'+ errorString);
return false;
}
else {
return true;
}
}
This is the function code for email_user()
function email_user(){
if(skip_email == true){ $('user').submit(); }
var url = 'email_user.php';
var params = '?' + $('user').serialize() + '&from_edit=1';
$('loading').style.display = 'inline';
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: params,
onComplete: show_response
});
function show_response(this_request){
//alert(this_request.responseText);
var reply = this_request.responseText.evalJSON(true);
if(reply['status'] == false){ var blah = ''; }
else{ alert(reply['message']); }
//$('loading').style.display = 'none';
$('user').submit();
}
}
Thinking about it, maybe it is more to do with the Apache version?? Just in case Apache version is 2.2.15.
Any assistance you guys can give me will be greatly appreciated! If you need any more information please let me know.
Kind Regards,
n00bstacker
As previously stated in comments, your code has some issues, your line (the one that is triggering the error, can be optimized in the following way:
$('#loading').css("display","inline"); //Selector is ok now...
In the other hand, I also noticed that you have a second selector $('user') that won´t work. Remember that anything without a dot, or a sharp will be considered as an element selector (loading, and user elements, won´t exist in your document unless you created it.
Remember:
$("#myId") //id selector
$(".myClass") //class selector
If "user" is the form name, the code may work. Remember that you want to catch the form submit event.
Regards,
Guillermo
Try changing $('loading') to $('#loading')?

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

How to validate javascript "not null" for ajax return values [duplicate]

This question already has answers here:
Making sure at least one checkbox is checked
(10 answers)
Closed 9 years ago.
My Php form (organisation.php) has this javascript validation
if(document.orgform.startdate.value == '')
{
alert('Enter Start Date');
document.orgform.startdate.focus();
return false;
}
if(document.orgform.enddate.value == '')
{
alert('Enter End Date');
document.orgform.enddate.focus();
return false;
} //these work fine
JQUERY
function getorgname(key)
{
var orgvalue = key.value;
$.ajax({
type:"POST",
url:"searchorg.php",
data:{orgname : orgvalue},
success: function(res) {
$('#org').html(res);
}
});
} //returns organisation names with checkboxes, working fine
HTML Part of organisation part is as follows:
<input type="text" name="startdate" id="sdate" >
<input type="text" name="enddate" id="edate">
<div id="organisation></div> //ajax returned values displayed here, working fine.
Now how do I test if at least one checkbox is checked?
I tried putting validation in ajaxorganisation.php as well as orgnaisation.php and called that function while submitting organisation.php, but it does not work.
Server side validation is working fine, but would appreciate if there is a way for client side validation too
A. Fix your html code. The containing div id attribute is missing the ending double quote delimiter.
B. whenever you wish to check if at least one is clicked, call the following function with an argument of '#organisation'
function at_least_one_checked(container) {
var $c_list = $(container + ' input[type="checkbox"]');
for (var i = 0; i < $c_list.length; ++i)
if ($($c_list[i]).prop('checked'))
return true;
return false;
}
Better you should create a group of these checkboxes by keeping same name for them. Like in future if you've added more input element, it will not affect the code.
try something like this
// chkbx class on checkbpx element
var flag = false
jQuery('.chkbx').each(function(){
if(this.checked){
flag = true;
}
})
return flag;// true if checked else false

Check jquery unobtrusive validation is true by jQuery

I use MVC 3 Model Validation Attributes and jquery unobtrusive to show validation error message also use the script when form submitted return a confirm. So I need to check if the all fields are valid then return Confirm: some thing like the following pseudo-script:
$('div.FormNeedConfirm form').submit(function () {
if ($(this).validate() == true) {
var Message = $('#FormConfirmMessage').val();
return confirm(Message);
}
});
But I don't know what exactly should be in the if condition. What is your suggestion?
if ($(this).valid()) {
var Message = $('#FormConfirmMessage').val();
return confirm(Message);
}
if ($(this).validate() = true) // your if condition should be "==".
change to like this
if ($(this).validate() == true)

Categories

Resources