Can I declare and call functions in javascript like in php - javascript

Can this be done? I'm coming form php and trying to optimize jquery code I'm writing for validation and I'm repeating my self a lot.
This would be the function:
function errorHint(e,hint){
if(e.parent().hasClass("has-success")){
return false;
}else{
e.addClass('form-control');
e.parent().addClass('has-error');
e.parent().append('<span id="glyph-error" class="glyphicon glyphicon-remove form-control-feedback"></span>');
e.parent().append('<div class="error-hint-empty alert alert alert-warning"><span class="warning-glyph glyphicon glyphicon-warning-sign"></span>'+hint+'</div>');
if(e.parent().hasClass("has-success")){
e.parent().removeClass("has-success");
e.parent().find('span#glyph-ok').remove();
}
}
}
And I would call it like this:
if($('#username').length){
if(testuser == 0 && $('#username').val() !=='' && $('#username').val() !== null){
hint = 'That user already exists!';
errorHint($("#username"),hint);
formvalid = false;
}
}

Your function should be:
function Alert (text){
alert(text);
}
$(form).on("submit", function() {
var text = 'This is alert text';
Alert(text);
});
This is because there is an ambiguous call between javascript's native alert and your defined alert. So I changed the function name to Alert, which should work fine.
Just a side thought..
Why are you doing this?
You can just use alert(text).
I don't think what you are doing is called code optimization. It is called code lengthification ;)
My advice is if you aren't doing anything inside Alert() except again just alerting, you should be better off using native alert('some text');

Related

jQuery and livequery error on javascript code not executing?

I have some very old javascript code on an existing site and I wanted to update it, but I'm running into errors and I'm not sure what to replace it with. The code is just part of a section where it does a .submit() call to the form. Then the code reaches the try condition, it throws the error that livequery is not a function. Code is also below the screenshot.
Also I'm not sure if the "var form" is outside the scope of the try for form to work or not. What could I have wrong here?
var submit = false;
var form = $("#webform-client-form-2")[0];
try {
if (repair) {
console.log('repair is true - line 317');
$(".simple-dialog").click();
$(".ui-dialog, .ui-widget-overlay").hide();
$(".form-actions").livequery(function() {
console.log('livequery - line 321');
$("#edit-submitted-name").val(subject_field);
$("#edit-submitted-phone").val(phone);
$("#edit-submitted-email").val(email);
$("#edit-submitted-details-of-issue").val(problem);
var find = $(".form-actions")[0]; //get the 1st form actions on the page. if more than 2 forms on page, this might submit wrong form.
if (!submit && find) {
console.log('repair is true - line 328');
submit = true;
$("#webform-client-form-2").submit();
$(".form-actions").expire();
return false;
}
});
} else if (contact) {
console.log('yyy');
console.log(form);
$("#edit-submitted-phone-number").val(phone);
$("#edit-submitted-message").val(problem);
$(form).submit();
} else {
console.log('zzz');
$(form).submit();
}
} catch (error) {
console.log(error);
console.log("no form - line 346");
}

Change variable value on button click

very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes". The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.
Was hoping someone would be kind enough to help.
I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)
HTML:
<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>
JS:
var beast
function imageAdd(choice) {
beast = choice;
}
if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010
You have just a couple of problems with your code. The first is this:
if (beast = "yes") {
In this case, you're assigning "yes" to beast, not comparing it. Change it to
if (beast == "yes") {
Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.
var beast;
function imageAdd(choice) {
beast = choice;
updateUI();
}
function updateUI() {
if (beast == "yes") {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
You have a function imagemap wrapped in a conditional but you aren't calling that function.
Also for your conditional, beast will always be null since the conditional is called straight away.
Consider the following adjustment
var beast;
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
function imageAdd(choice) {
beast = choice;
if (beast === "yes" ) {
imagemap();
}
}

MessageBox shown after function is over

I have a javascript function that calls my javascript function, my func islike this:
function sugParitValidation(){
var isValid = false;
Ext.MessageBox.confirm(' ','Are you sure you want to do this?', function(btn){
if(btn == 'yes'){
isValid = true;
}
});
return isValid ;
}
My problem is - if statement and the return statment is happening, and only after that the confirm window being shown.
That way I can't react to what the user choosed.
how to solve this? tried allready use setTimeOut, no change at all....
i think you are trying to do something like this.
someFunction(){
if(sugParitValidation()){
//todo something
}
else{
//todo another thing
}
}
you can do this easyly with callbacks. This is the example.
someFunction(){
var messageCallback = function(btn){
if(btn === 'yes'){
//todo something
}
else{
//todo another thing
}
}
Ext.MessageBox.confirm(' ','Are you sure you want to do this?',
messageCallback);
}

e.preventDefault doesn't work 2

Can anyone help me to find out why this script doesn't work? After hitting the submit button, my form is still being submitted.
Here is the code:
submitadd.submit(function(e){
var submitadd = jQuery('#submitadd'),
yearofmanufacturing = jQuery('#yearofmanufacturing'),
price = jQuery('#price'),
addtext = jQuery('#addtext');
if(yearofmanufacturing.val()==''){
jQuery('#yearofmanufacturing').addClass('bordered2');
jQuery('#yearofmanufacturing').removeClass('styled_select');
jQuery("#yearofmanufacturing").attr("placeholder", "Εισάγετε Χρονολία").placeholder();
e.preventDefault();
return false;
alert('yearof......enter in the if');
}
else {
alert("yearnotempty?");
}
if(price.val()=='') {
jQuery('#price').addClass('bordered2');
jQuery('#price').removeClass('styled_select');
jQuery("#price").attr("placeholder", "Εισάγετε τιμή").placeholder();
e.preventDefault();
return false;
alert('price...enter in the if');
}
if(addtext.val()==''){
jQuery('#addtext').addClass('bordered2');
jQuery('#addtext').removeClass('styled_select');
jQuery("#addtext").attr("placeholder", "Εισάγετε περιγραφή αγγελίας").placeholder();
e.preventDefault();
return false;
alert('add text...enter in the if');
}
alert('addtext = ' +addtext.val());
});
None of the alerts shows when the submit has been clicked. Any help will be deeply appreciated.
Regard, John
To save space you could do something like this:
JQuery
jQuery('#submitadd').submit(function(){
var checks = [jQuery('#yearofmanufacturing'),
jQuery('#price'),
jQuery('#addtext')];
for(var i = 0; i < checks.length; i++){
var x = checks[i];
if(x.val() == ''){
x.addClass('bordered2').removeClass('styled_select');
x.prop("placeholder", "Εισάγετε Χρονολογία");
console.log('Value for ' + x.prop('id') + ' is empty.');
return false;
}
else {
console.log('Value for ' + x.prop('id') + ' is not empty.');
}
}
});
Demo
I have rewritten most of the function but it still does the same stuff. I have removed e.preventDefault();, instead I am using return false;.
If the value is empty. This is also logged to the console (console.log()), this is visible when you debug with F12
Note Aksu's answer too:
You have specified the submitadd variable inside the event. You must move it outside to get event handler fire, otherwise the variable isn't defined, and the code doesn't work.
You have specified the submitadd variable inside the event. You must move it outside to get event handler fire, otherwise the variable isn't defined, and the code doesn't work.
var submitadd = jQuery('#submitadd');
// user fill all fields as it should, so form can be submitted
submitadd.submit(function(e){
var yearofmanufacturing = jQuery('#yearofmanufacturing'),
price = jQuery('#price'),
addtext = jQuery('#addtext');
...
change this:
submitadd.submit(function(e){
to this:
jQuery('#submitadd').submit(function(e){
In your case the variable submitadd is been used before its been declared.
or you can declare it before submit:
var submitadd = jQuery('#submitadd')
submitadd.submit(function(e){
The solution: Move var submitadd = jQuery('#submitadd'); out of your function!
I would recommend you some things:
Use your jQuery variables:
Instead of using yearofmanufacturing, you write jQuery('#yearofmanufacturing') multiple times
Naming conventions:
I would recommend you to use variable names like $price instead of price, if you are declaring jQuery objects.
Don't write unreachable code:
You are trying to call alert() after returning something. This doesn't makes any sense.
Don't abuse alert() for debug issues:
Use console.log(), console.debug(), console.info() and console.warn() for best debugging exceperience.
Crossbrowser support:
Internet Explorer <= 8 doesn't know .preventDefault(). Be happy with something like this:
(e.preventDefault) ? e.preventDefault() : e.returnValue = false;

java script is not working in mozila

I have added some javascript in html page for input validation.same page is working correct in IE and chrome but in mozila its not working.The problem is when user inputs invalid data its supposed to show alert msg box and when user clicks OK it should return false to form...BUT mozila is not waiting for alert box it just shows alert box for 5-6 sec and then goes to next page defined in form action="nextpage.php"
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(oldpassword, "<b>Error: </b>Please enter the Old Password!") == false)
{ changeColor("oldpassword"); return false; }
else if (valid_length(newpassword, "<b>Error: </b>Please enter the New Password!!") == false)
{newpassword.value=""; changeColor("newpassword"); return false; }
else if (valid_length(cnfpassword, "<b>Error: </b>Please enter the Confirm Password!!") == false)
{cnfpassword.value=""; changeColor("cnfpassword"); return false; }
else if (document.getElementById('newpassword').value != document.getElementById('cnfpassword').value)
{changeColor("newpassword");cool.error("<b>Error: </b>Passwords entered are not same!");
newpassword.value="";cnfpassword.value="";return false;}
}
}function validate_required(field, alerttxt)
{
with (field)
{
if (value == null || value == "")
{
cool.error(alerttxt);return false;
}
else
{
return true;
}
}
}
cool.error is nothing but CSS nd Js for alert box.I thing there is not any problem in my code weather problem is in some browser settings.Is it so??? because it is working fine in IE and Chrome.
You're using a non-standard IE-only behavior that creates global variables for every element with an ID.
To fix it, add a global variable for each element that you use:
var oldpassword = document.getElementById("oldpassword");
Also, you should never use Javascript's with block.
It is very different from VB's with block, and should not be used unless you truly understand its pitfalls and shortcomings. It will also slow down your code.
You could also use some javascript library to get past browser issues. I'm rooting for jQuery.

Categories

Resources