.blur not firing on previously hidden tables - javascript

So the issue I seem to having is a bit of a weird one. So I have a form that is hidden until a button is clicked, once it's clicked the table is visible and has a .blur function on the inputs to check if they're empty. I've tried adding alert() throughout the pcontroller and it just never get's into the function.
Here's what's in the controller (document ready is done earlier on)
var newQuestionName = $('#questionName');
function basicValidate(object) {
var val1 = object.val();
if (val1 != null && val1 != ' ' && val1 != '') {
// invalid
object.removeClass('error');
return true;
// alert('true');
} else {
// true
object.addClass('error');
return false;
// alert('invalid');
}
}
newQuestionName.blur(function () {
alert('TEST');
if (basicValidate($(this))) {
add_newQuestionName_valid = true;
alert('new question true')
} else {
add_newQuestionName_valid = false;
alert('new question false')
}
});
Here's the HTML
<form action="">
<div class="row">
<label for="questionName">
FAQ Question:
</label>
<div class="input-container">
<input id="questionName" type="text" class="text" value="">
</div>
</div>
<div class="row">
<label for="questionAnswer">
FAQ Answer:
</label>
<div class="input-container">
<textarea id="questionAnswer" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="submit-container submit" >
<div type="submit" ng-click="newFaq()" id="addNew" class="button" value="save">save</div>
</div>
</div>
</form>

Since I don't have all your code, I can't for sure know whether this is your problem. But I am, however, almost certain that it is, so hear me out.
The problem is that when this statement is run:
var newQuestionName = $('#questionName');
the element with id questionName hasn't yet loaded, due to the order that the DOM loads in. In order to solve this, you can wrap your JavaScript code in:
$(document).ready(function() {
...
});
Try replacing your JavaScript with the following:
$(document).ready(function() {
var newQuestionName = $('#questionName');
function basicValidate(object) {
var val1 = object.val();
if (val1 != null && val1 != ' ' && val1 != '') {
// invalid
object.removeClass('error');
return true;
// alert('true');
} else {
// true
object.addClass('error');
return false;
// alert('invalid');
}
}
newQuestionName.blur(function () {
alert('TEST');
if (basicValidate($(this))) {
add_newQuestionName_valid = true;
alert('new question true')
} else {
add_newQuestionName_valid = false;
alert('new question false')
}
});
});
EDIT: Not sure if it was added afterwards, but since you're saying that "document ready" is done earlier on, the problem is still probably related to that, considering that it works fine when I use the code I provided. Make sure that the newQuestionName variable is referring to what you want. You can check it using alert(newQuestionName.length).

Related

error classes do not show up when form is submitted

I'm trying to validate my signup form using JavaScript. I submit the form and the default action is prevented but none of my error handler classes show up, nor do I get any errors in my error log. if anyone can show me what I'm doing wrong, it would greatly appreciated. I'm trying to show a red background on the input fields if the user doesn't fill in the input.
$(document).ready(function () {
$("#signupForm").submit(function (e) {
removeFeedback();
var errors = validateSignup();
if (errors == "") {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
});
function validateSignup() {
var errorFields = new Array();
//Check required fields to see if they have anything in them
if ($('#signupFirst').val() == "") {
errorFields.push('first');
}
if ($('#signupLast').val() == "") {
errorFields.push('last');
}
if ($('#signupEmail').val() == "") {
errorFields.push('email');
}
if ($('#signupPassword').val() == "") {
errorFields.push('pwd');
}
if (!($('#signupEmail').val().indexOf(".") > 2) && ($('#signupEmail').val().indexOf("#"))) {
errorFields.push('email');
}
return errorFields();
}
function provideFeedback(errorFields) {
for (var i = 0; i < errorFields.length; i++) {
$("#" + errorFields[i]).addClass("inputError");
$("#" + errorFields[i] + "Error").removeClass("errorFeedback");
}
}
function removeFeedBack() {
$('input').each(function () {
$(this).removeClass("inputError");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="index-bg-wrapper">
<div class="main-signup-container">
<form id="signupForm" class="signup-form" action='include/signup.inc.php' method='POST'>
<input id="signupFirst" type="text" name="first" placeholder="First Name">
<input id="signupLast" type="text" name="last" placeholder="Last Name">
<input id="signupEmail" type="text" name="email" placeholder="Email">
<input id="signupPassword" type="password" name="pwd" placeholder="Password">
<button type="submit" name="submit">Signup</button>
</form>
</div>
</div>
</body>
This is not ok:
return errorFields(); // Here you're trying to call a function with an array.
Just return the array: return errorFields;
Another problem is the comparison:
if (errors == "") { // This is not ok (it's always false), so, what you want to check is the length of errors.
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
So, check for the length:
if (errors.length === 0) {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
Here you go buddy, I have fixed multiple errors though very minor in your code but its working fine now.
Plnkr:
http://embed.plnkr.co/MaUzZh1zUFBL4y8qAf6n/
You were pushing wrong name inside the errorFields array.
Due to wrong field name and DOM id mismatch jquery couldn't find the element and apply the class.
I hope you can compare and get this code working.

Google chrome identification popup

I have this line of Javascript:
if (true){
$('#custom-tag').html('HTML');
}
else {
$('#custom-tag').html('DifferentHTML');
}
If a variable is yes, it will run this html code at startup.
If the variable is not yes, then it will run this line of html at startup.
How can I do this?
EDIT: I'm afraid I forgot to say, I was wanting this to detect your browser. If using chrome, it will put out no HTML. If using other browsers than chrome, it will put out HTML.
EDIT#2: I have this code. I need to fix this for the popup that identifies if it's chrome.
$(function() {
$('#in').on('keyup', function() {
validate();
});
});
function validate() {
var x = $('#in').val();
if (navigator.userAgent.indexOf("Chrome") != -1) {
$('#result').html('<h3>Chrome</h3>');
} else {
$('#result').html('');
}
}
<input type="text" id="in" onChange="validate()" />
<div id="result">
<div id="popup" class="overlay">
<div class="popup">
<h2>Browser</h2>
<a class="close" href="javascript:popupClose();">×</a>
<div class="content">
</div>
</div>
</div>
Just need to connect all of these. EDIT: I need to add the last line of html into the java code if it's not chrome.
Here it works
var name;
if(name.checked == true){
$('#custom-tag').html('HTML');
}else{
$('#custom-tag').html('DifferentHTML');
}
Try the one line snippet which use ternary operator.
// Check if not chrome
if(!$.browser.chrome){
// If its variable.
$('#custom-tag').html( (variable == 'yes') ? 'html' : 'different html' );
}
// If its checkbox.
$('#custom-tag').html( $('#checkboxId').is(":checked") ? 'html' : 'different html' );
var x = true; // Your dynamic result True or False is stored in x
if(x)
{
$('#selector').html();
}
else
{
$('#selector').html();
}
You can also do it by defining var x = ''; in the beginning of script and then depending upon your other script statements, it would get value either true or false. Then you need to check x = '' or not. That's it!
$(function(){
$('#in').on('keyup',function(){
validate();
});
});
function validate(){
var x = $('#in').val();
if(x == "x"){
$('#result').html('<h3>x entered</h3>');
}else{
$('#result').html('<h5>something other than x entered</h5>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="in" onChange="validate()"/>
<div id="result">
</div>
You can check if its chrome this way:
if( navigator.userAgent.toLowerCase().indexOf('chrome') > -1 ){
// chrome, do nothing
}
else {
// not chrome put html
$('#custom-tag').html('HTML');
}

How to disable a function when another one is enable?

function send() {
alert("Your message sent.");
}
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue != "" && messageValue != "") {
document.getElementById("af-form").submit();
} else {
alert("Nickname or message is blank. Please fill.");
return false;
}
}
These are my JS codes
<input type="text" name="nickname" id="input-nickname" required>
<textarea name="message" type="text" id="input-text" required></textarea>
<input type="submit" value="Send" onclick="wrongNickNameorMessage() + send()" />
And these are my HTML codes.
When I click on Send button. First alert("Your message sent."); then alert("nickname or message is blank. Please fill."); is working. Or exact opposite.
I wanna disabled send() function if wrongNickNameorMessage() is true.
How can I do that?
You have the right idea but you're going about it very out-of-the-way. Try this:
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue === "" || messageValue === "") {
alert("Nickname or message is blank or improper input detected. Please fill.");
return false;
}
document.getElementById("af-form").submit();
alert("Your message sent.");
}
You dont need the other function or the other part of the if statement since you're just validating input. You can get more creative but that's all you really need. Your function will completely stop if there's a problem but otherwise, it'll show the right message and submit.
Although your practice is horrible, this may help you in the future:
/* first give your submit button an id or something and don't use the onclick
attribute
*/
<input type='submit' value='Send' id='sub' />
// Now the JavaScript, which should be external for caching.
var doc = document;
// never have to use document.getElementById() again
function E(e){
return doc.getElementById(e);
}
function send() {
alert('Your message was sent.');
}
// put all your sub onclick stuff in here
E('sub').onclick = function(){
var nicknameValue = E('input-nickname').value;
var messageValue = E('input-text').value;
if(nicknameValue !== '' && messageValue !== '') {
send(); E('af-form').submit();
}
else {
alert('Nickname or message is blank. Please fill.');
return false;
}
}
Note, that this is not sufficient to handle a form. It just shows concept. JavaScript can be disabled, so you must account for that as well, Server Side.
You need to call a wrapper method that will call the wrongNickNameorMessage() check result and than continue only if returned true.
function conditionalSend(){if (wrongNickNameorMessage()){send();}}

Not returning a value for some reason

Basically I have a script the function "hola ()" that should return the value of 1 if the radio button value is 1. But for some reason when I try to get the return value in another function i never get it.
The form works perfectly.. the only issue is that it doesnt return the value
Can anyone tell me what i did wrong?? thanks
$(document).ready(function(){
function hola() {
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
return 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
})
}
$("#iForm").submit( function(event){
event.preventDefault();
var user = $("input[name=username]").val();
var password = $("input[name=password]").val();
var dbName = $("input[name=dbName]").val();
var server = $("input[name=server]").val();
$.get("1.php",
{username: user, password: password, dbName: dbName, server: server },
function(data){
if (data == "The table PAGE exists" || data == "The table SUBJECTS exists" || data == "The table USERS exists" ) {
// CALLING THE hola () function and expecting a return
var opt = hola();
$("p").html(data + opt);
}
}
)
})
})
HTML
<!-- Yes or No form -->
<form name="yN" style= "display: none; margin-left: auto; margin-right: auto; width: 6em">
<input type="radio" name="yN" value="1">yes</input>
<input type="radio" name="yN" value="0">no</input>
<button id=1 >click me!</button>
</form>
<!-- Login Form -->
<form id="iForm" style= "display: show">
<label id="username" >Username</label>
<input id="username" name="username"/>
<label id="password">Password</label>
<input id="password" name="password" />
<label id="server" >Server</label>
<input id="server" name="server"/>
<label id="dbName" >dbName</label>
<input id="dbName" name="dbName"/>
<input type="submit" value="submit" />
</form>
<p> </p>
Event handlers cannot return values because they're called asynchronously*.
Your existing hola() function will return immediately and the return statements in the click handlers are only called much later, i.e. when the button is clicked.
My approach would be this, using jQuery deferred objects (jQuery 1.6+):
function hola() {
var def = $.Deferred();
// show the popup confirm form
...
$('input[type=radio]').click(function() {
// determine return value
...
// send it back to anything waiting for it
def.resolve(retval);
});
// return a _promise_ to send back a value some time later
return def.promise();
}
$.get("1.php", { ... }).done(function(data) {
if (...) {
hola().done(function(opt)) { // will be called when the promise is resolved
$("p").html(data + opt);
});
}
});
If you prefer, instead of returning the opt value you could use def.reject() to indicate "non-acceptance" and then use a .fail handler to register a handler to be called for that condition.
You return 1 only in the click function of the radiobutton.
If you want to have a function "hola" that returns 1 if the radiobutton is checked, you simply need something like this:
function hola() {
return $("input:radio[name='yN']:checked").val();
}
hola does not even have a return statement. That's the reason for its not returning anything (more precisely: returning undefined always).
A JavaScript function that does not contain a return statement at all or whose all return statements are within nested functions will never return anything but undefined.
Your are tring to return the value from withing the click callback function. Move the return outside that:
function hola() {
var result;
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
result = 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
});
return result;
}

Validation stuck at first validation

I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />

Categories