I have used this function for form validation. I have used this function without
$ function(document).ready(function(){.............});
Its working well. Now I want to add my code under this
$ function(document).ready(function(){.............});
How could I do that. Thanks.
function myFunction () {
var a = document.getElementById("num").value;
var b = document.getElementById("num2").value;
var msg = "";
if(a==""){
msg+="Please Fill this field.\n";
num.className = "color";
}
if(b==""){
msg+="Please Fill this field.\n";
num2.className = "color";
}
if(msg=="") {
return true;
}
else {
document.getElementById("result").innerHTML="Please fill the user name";
document.getElementById("result2").innerHTML="Please Put your E-mail";
return false;
}
}
$(document).ready(function(){ myFunction(); });
Related
please help here: the if condition always return true though it is false??
these are the html code for variable div and variable your at the beginning
(<div class="div" id="div" style="background:yellow"></div>)
(<input type="text" id="your">)
$(document).ready(function generate() {
"use strict";
var x = $(".2").text(Math.floor((Math.random() * 10))),
z = $(".3").text(Math.floor((Math.random() * 10)));
$(".div").text(x.text() + z.text());
});
var show = document.getElementById("show"),
your = document.getElementById("your").value,
div = document.getElementById("div").textContent;
show.onclick = function () {
"use strict";
if (your == div) {
alert("yes");
} else {
alert("noo");
}
};
The problem is, that you are defining the values outside of the function. So in the onclick handler you are comparing the initial values.
If you want the actual values, you should access the values inside the function:
var show = document.getElementById("show"),
your = document.getElementById("your"),
div = document.getElementById("div");
show.onclick = function () {
if (your.value == div.textContent) {
alert("yes");
} else {
alert("noo");
}
};
A document contains script
$(document).ready(function() {
$(function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
});
$("#reset").click(function() {
reset;
/* $("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = []; */
});
});
and in page html
<p>
Reset all
</p>
The function reset executed on page load.
How can I prevent it from executing on page load?
When I press link Reset all the function reset does not work? Why?
Give this a shot
Remove the $( ) around your function. - This is what makes it execute automatically.
Then in the button put ()'s after the name reset() - This is how you call a function in Javascript
$(document).ready(function() {
function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
};
$("#reset").click(function() {
reset();
/* $("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = []; */
});
});
Remove the $(...) from the function declaration and call reset() like a normal function.
$(document).ready(function() {
function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
}
$("#reset").click(function() {
reset();
/* $("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = []; */
});
});
You just want it to be a normal function. When you put it in $(...), jQuery thinks it's a function that'll return a set of selectors, so it calls it immediately. You don't want that.
check this
$(document).ready(function() {
function reset(){
$("#select-result").empty().html(" ");
userInputSumm = 0;
userInput = [];
console.log('reser was executed!');
}
$("#reset").click(reset);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Reset all
</p>
There is no need to have an anonymous function in the click event binding,you can directly set to the reset function
Remove "$" before your function and add () for call the function.
function reset(){
};
$("#reset").click(function() {
reset();
});
As I needed help here
#ryanpcmcquen offered great help, but as a "noob" at javascript I would like to know 2 more things
When I want to create another function how do I make it?
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var unitBlock = document.querySelector('select#unit_block');
var unitRowBig = document.querySelector('select#unit_row_big');
var unitRow = document.querySelector('select#unit_row');
var unitColumn = document.querySelector('select#unit_column');
var unitSize = document.querySelector('select#unit_size');
unitBlock.addEventListener('change', function () {
if (unitBlock.value === 'A') {
unitRowBig.disabled = false;
unitRowBig[4].disabled = false;
} else {
unitRowBig.disabled = false;
unitRowBig[4].disabled = true;
}
});
unitBlock.addEventListener('change1', function () {
if ((unitRowBig.value === '1') && (unitBlock.value === 'A')) {
unitRow.disabled = false;
unitRow[8].disabled = true;
unitRow[9].disabled = true;
unitRow[10].disabled = true;
unitRow[11].disabled = true;
unitRow[12].disabled = true;
}
});
});
Because it doesn't seems to work my way.
No need to add a new event, besides change1 is not a valid event, you can find a list of events here:
https://developer.mozilla.org/en-US/docs/Web/Events
Just put that conditional inside the original event handler:
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var unitBlock = document.querySelector('select#unit_block');
var unitRowBig = document.querySelector('select#unit_row_big');
var unitRow = document.querySelector('select#unit_row');
var unitColumn = document.querySelector('select#unit_column');
var unitSize = document.querySelector('select#unit_size');
unitBlock.addEventListener('change', function () {
// You may want to comment out all of this section:
if (unitBlock.value === 'A') {
unitRowBig.disabled = false;
unitRowBig[4].disabled = false;
} else {
unitRowBig.disabled = false;
unitRowBig[4].disabled = true;
}
// Down to here.
// Here's your code!
if ((unitRowBig.value === '1') && (unitBlock.value === 'A')) {
unitRow.disabled = false;
unitRow[8].disabled = true;
unitRow[9].disabled = true;
unitRow[10].disabled = true;
unitRow[11].disabled = true;
unitRow[12].disabled = true;
// Including an antithetical clause,
// to account for the user changing their mind.
} else {
unitRow.disabled = true;
unitRow[8].disabled = false;
unitRow[9].disabled = false;
unitRow[10].disabled = false;
unitRow[11].disabled = false;
unitRow[12].disabled = false;
}
});
});
Note that I also included the opposite disabled conditions in an else clause, in case the user makes one choice, and then changes to another.
In case you really need two separate functions (what is not the case here), just do it like this:
unitBlock.addEventListener('change', function () {
console.log('First event listener')
});
unitBlock.addEventListener('change', function () {
console.log('Second event listener')
});
document.addEventListener stores all the functions you sent to him, so when the change event will be fired, it will execute all of them, in the order you passed them to it.
In short, when the change event is fired, you will have:
> "First event listener"
> "Second event listener"
I hope this helped you!
I am writing a script which will verify username . I am able to put check on user name. In case username is not fulfilling criteria then I am throwing error.
<script>
//<![CDATA[
function visitPage() {
if (validateUsername()) {
var div = document.getElementById("totalpricecheck");
var spans = div.getElementsByTagName("span");
var totalprice = spans[3].innerHTML;
var name = document.getElementById("name").value;
alert(name);
}
}
function validateUsername(fld) {
var fld = document.getElementById("name").value;
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
//fld.style.background = 'Yellow';
error = "You didn't enter a username.\n";
document.getElementById("nmessage").innerHTML = "You didn't enter a username.\n";
// $("#nmessage").fadeOut(3000);
// alert(error);
return false;
} else if ((fld.length < 5) || (fld.length > 50)) {
//fld.style.background = 'Yellow';
error = "The username is the wrong length.\n";
document.getElementById("nmessage").innerHTML = "OOps!! The username is too short \n";
// alert(error);
return false;
} else if (illegalChars.test(fld.value)) {
//fld.style.background = 'Yellow';
document.getElementById("nmessage").innerHTML = "The username contains Unsupported characters.\n";
error = "The username contains Unsupported characters.\n";
// alert(error);
return false;
} else {
// fld.style.background = 'White';
}
return true;
}
return false;
}
// ]]>
</script>
I am trying to hide this error using fadeout effect as given in
Hide div after a few seconds
setTimeout(function() {
$('#mydiv').fadeOut('fast');
}, 1000); // <-- time in milliseconds
but am not getting how can I use jQuery method in JavaScript for error message removal. someone suggest me what are possible option I have to get desired effect.
As #iFTrue mentioned in the other post, correct div ID has to be provided.
As #chitrang mentioned in comment jQuery library has to be
included in the page if its not already done.
To inlude jQuery from CDN use the below code. Paste it inside head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
You should set the timer inside visitPage()
function visitPage() {
if(validateUsername()) {
var div = document.getElementById("totalpricecheck");
var spans=div.getElementsByTagName("span");
var totalprice=spans[3].innerHTML;
var name = document.getElementById("name").value;
alert(name);
}
else {
// show error message
$('#nmessage').show();
// hide error message after 3 sec
setTimeout(function() {
$('#nmessage').fadeOut('fast');
}, 3000);
}
}
Update
I see that you are using jQuery only to hide and show the div. If you don't need the fadeOut animation effect, you can remove jQuery library and use the below code.
function visitPage() {
if(validateUsername()) {
var div = document.getElementById("totalpricecheck");
var spans=div.getElementsByTagName("span");
var totalprice=spans[3].innerHTML;
var name = document.getElementById("name").value;
alert(name);
}
else {
// show error message
document.getElementById("nmessage").style.display = 'block';
// hide error message after 3 sec
setTimeout(function() {
document.getElementById("nmessage").style.display = 'none';
}, 3000);
}
}
Judging by your code here:
document.getElementById("nmessage").innerHTML ="The username contains Unsupported characters.\n";
Your setTimeout function is not calling the right div to hide. It should look like this:
setTimeout(function() {
$('#nmessage').fadeOut('fast');
}, 1000); // <-- time in milliseconds
I also did not see this implemented in your script at all so add that setTimeout function call after you change the innerHTML.
I have defined a div within which a form with default input values is appended based on MySQL table data returned by PHP via an ajax $.get call.
The div looks like:
<div id="esfContainer1">
</div> <!--end esfContainer1 div-->
The div is absolutely positioned relative to the body tag.
The script associated to the form validation broke when it was included on the main page where the call to the form was being made, so I moved it to the PHP output $formContent.
Here is the form validation and submit script included in the PHP output:
<script type="text/javascript">
var senderName = $("#sendName");
var senderEmail = $("#fromemailAddress");
var recipientEmail = $("#toemailAddress");
var emailError = $("#esemailerrorDiv");
senderName.blur(checkName);
senderEmail.blur(checkSEmail);
recipientEmail.blur(checkREmail);
function checkName() {
if (senderName.val() == "YOUR NAME") {
$("#esemailerrorText").html("Please provide your name");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
} else {
return true;
}
};
function checkSEmail() {
var a = senderEmail.val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(a)) {
return true;
} else {
$("#esemailerrorText").html("Please enter a valid email address");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
}
};
function checkREmail() {
var a = recipientEmail.val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(a)) {
return true;
} else {
$("#esemailerrorText").html("Your friend\'s email is invalid");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
}
};
$("#emailForm").submit (function() {
if (checkName() && checkSEmail() && checkREmail()) {
var emailerData = $("#emailForm").serialize();
$.get("style.php",emailerData,processEmailer).error("ouch");
function processEmailer(data) {
if (data=="fail") {
return false;
} else if (data=="pass") {
$("#c1Wrapper").fadeOut("slow","linear");
$("#confirmation").fadeIn("slow","linear");
$("#esfContainer1").delay(2000).fadeOut("slow","linear");
$("#backgroundOpacity").delay(2000).fadeOut("slow","linear");
return false;
}
};
return false;
};
return false;
});
I have splatter-bombed the above submit function with "return false;" because the submit function has been simply opening the processing PHP script rather than executing the $.get. Watching the submit function with Firebug reports that processEmailer is undefined.
I am very new to this. I was assuming that because the ajax callback is being defined within the submit function (and that the processEmailer function is defined directly below the ajax call) that there wouldn't be a problem with definition.
Thanks in advance for any help.
You've been trapped by function statements. Function declarations (which would be hoisted) are not allowed inside blocks (if/else/for bodies) and if they are appear there, behaviour is not defined. Firefox defines them conditionally, and in your case after you've used it in the $.get call - where it was undefined then - like in var functionName = function() {} vs function functionName() {}.
To solve this, simple put it outside the if-block (or even outside the whole callback). Btw, .error("ouch") won't work, you need to pass a function.
$("#emailForm").submit (function() {
if (checkName() && checkSEmail() && checkREmail()) {
var emailerData = $("#emailForm").serialize();
$.get("style.php",emailerData).done(processEmailer).fail(function() {
console.log("ouch");
});
}
return false;
// now a proper function declaration, will be hoisted:
function processEmailer(data) {
if (data=="fail") {
return false;
} else if (data=="pass") {
$("#c1Wrapper").fadeOut("slow","linear");
$("#confirmation").fadeIn("slow","linear");
$("#esfContainer1").delay(2000).fadeOut("slow","linear");
$("#backgroundOpacity").delay(2000).fadeOut("slow","linear");
return false;
}
}
});