Why this javascript executes in Chrome but not in Firefox? - javascript

I need to set the "cmd" hidden text to the values below. Chrome executes this scripts, but Firefox (at least 3.6) doesn't.
I've checked the java in firefox, also the "execute javascript" option. I've been running jquery stuff in firefox quite well. What should I do?
function envia() {
frm = document.forms['detalha'];
tx = frm.elements("cmd");
tx.value = '0';
alert('document pressed' + document.pressed);
if (document.pressed == '2') {
tx.value = '2';
} else if (document.pressed == '3') {
tx.value = '3';
} else if (document.pressed == '4') {
tx.value = '4';
}
return true;
}
<form name="detalha" action="/publicopj/Altera" onsubmit="envia()">
<input type="submit" value="Save" name="acao" onclick="document.pressed=3"/>
Thanks in advance.

document.forms[...].elements is an array, not a function. You've got () on your .elements bit, trying to call it as a function.
tx = frm.elements["cmd"]; // note the square brackets

Related

If and Else Statements Always Output If

I was messing around with a previously existing snippet and ran into an issue.
Whenever I try to enter an input that doesn't apply the to If statement it always gives me the If output. Also I was looking to, instead of saying approved, have you sent to a URL, like Google for example, and I'm not sure about a solution for either of the two.
function myFunction() {
var a = document.getElementById("text_a").value;
if (a == "02035", "02048", "02067") {
document.getElementById("answer").innerHTML = "Approved";
} else {
document.getElementById("answer").innerHTML = "Our service currently isn't available in your area! Try again soon!";
}
}
<p>Enter Zip Code </p>
<input id="text_a" type="text" />
<p id="answer"></p>
<button onclick="myFunction()">Check</button>
May be you need to change the condition in if statement:
if (a == "02035" || a == "02048" || a == "02067"){
document.getElementById("answer").innerHTML="Approved";
}
else{
document.getElementById("answer").innerHTML="Our service currently isn't available in your area! Try again soon!";
}
if (a=="02035","02048","02067")
You can't do like this.
There are many ways to check it. You could do like this
function myFunction() {
var a = document.getElementById("text_a").value;
var list = ["02035", "02048", "02067"];
console.log(a)
if ((list.indexOf(a) > -1)) {
document.getElementById("answer").innerHTML = "Approved";
} else {
document.getElementById("answer").innerHTML =
"Our service currently isn't available in your area! Try again soon!";
}
}
I made a sample: https://codepen.io/anon/pen/bWBvMj?editors=1011

How to change the value of an active text input using Javascript?

I am trying to make a form with a date input.
However, this input is in date format, and I would like to change the value while the control is still active.
Here is the full code :
// Javascript code
function add_value()
{
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length = 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length = 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onchange="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
But this is only updating the text when you exit of the control, and I would like to know how to run this javascript function while the control is still active.
Thanks.
You need to use onkeyup.
<input id="fin_mater" type="text" onkeyup="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
From the docs
Execute a JavaScript when a user releases a key
Also in your if your are using =, you should be using ==
...
if(document.getElementById("fin_mater").value.length == 2)//==
...
else if(document.getElementById("fin_mater").value.length == 5)
...
First let's make the code smell more like the "javascript" :)
// Javascript code
function $(id) {
return document.getElementById(id);
}
function add_value(event) {
var dataOriginale = $("fin_mater").value,
len = dataOriginale.length,
key = event.keyCode || event.charCode;
// Allow BACKSPACE and DEL
if (key === 8 || key === 46) {
return true;
}
if(len === 2 || len === 5) {
$("fin_mater").value = dataOriginale + '-';
}
return false;
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onKeyUp="add_value(event);" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
If you want to append the "-" automatically when you input numbers, you can listen on the "onKeyUp" event of the text box rather than the "onchange".
PS: You can use the key code to limit only numbers input and also do some validations.
You can use keypress():
$(document).ready(function()
{
$( "#fin_mater" ).keypress(function() {
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
});
});
Fiddle
With some of your help and some documentation, I finally went to this, that works perfectly on every browser that supports javascript.
$(document).ready(function(event)
{
$( "#fin_mater" ).keypress(function(event) {
var dataoriginale = document.getElementById("fin_mater").value;
if(event.keyCode != 8)
{
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
});
});
Thanks everyone !

Form is submitting even after failing Javascript validation?

I have a form called here:
<span class="aligncenter button">Submit</span>
And I have a JavaScript function here:
if (myForm == 'newIncident')
{
var vDemAge = document.forms['newIncident']['demAge'].value;
var vBibNumber = document.forms['newIncident']['bibNumber'].value;
// Run through validations before submitting form
validateTime();
validateDate();
validateAge();
validateGender();
validateLocation();
validateType();
validateDisposition();
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
else
{
document.getElementById(myForm).submit();
}
So I have each of the validations as a separate function that I am calling in sequence when submitting the form. If I comment out the "document.getElementById(myForm).submit();", the validations run as expected. However, if I leave it uncommented, it submits every time even if the validations fail. How can I stop this from happening?
Thanks!
EDIT:
So this is one of the validations I'm running. They're all structured the same way. Somewhere I should be returning a boolean true/false? How exactly would I insert that in this one below?
function validateDisposition()
{
var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
if (vIncidentDisposition == '')
{
document.forms['newIncident']['incidentDisposition'].className = 'required';
}
else
{
document.forms['newIncident']['incidentDisposition'].className = 'formborder';
}
}
assuming your validation functions return a bool, you should have something like
if( validateTime() && validateDate() && validateAge()... etc ) {
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
I got it working! The boolean idea put me on the right path. Thanks!
I just added a "return true" and "return false" to each of the validations, then used the answer above with the "&&" if to build the logic into the myform "if". If it doesn't pass all of them the else does a "return false". Works like a charm!

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

jQuery change text based on drop down list option

Hi I am looking for guidance on how I can change the interest rate value based on what type of account a customer chooses from the drop down.
Form:
<form id="account" action="" method="post">
<select id = "acc_type">
<option value="current">Current</option>
<option value="savings">Savings</option>
</select>
<input type="text" id="interest" value="">
</form>
<script>
$("#account").change(function() {
var rate = "0.6%";
if $(#acc_type).val == ("current") {
rate = "0.6%");
} else if $(#acc_type).val == ("savings") {
rate = "0.8%");
}
$(#interest).val = rate;
</script>
http://jsfiddle.net/rmjKV/
Can I have some explanation of why this does not work?
It does not work since that is not valid JavaScript. Use a tool like JSLInt to check your code to see the errors.
You are missing many ( and ) in that code.
Look at the if statements on MDN
if (cipher_char == from_char) {
result = result + to_char;
x++;
} else {
result = result + clear_char;
}
Do you see what you are missing? The ( and ) around the check.
Now jQuery val is a method, you are not calling a method. You need (). You can not set .val either.
The docs for jQuery val()
Your selector is also wrong, you are missing quotes.
Learn to use your console! It will show you the errors.
You have a lot of syntax errors and improper way of using jQuery functions and selectors
$("#account").change(function() {
var rate = "0.6%";
if($('#acc_type').val() == "current")
{
rate = "0.6%";
}
else if ($('#acc_type').val() == "savings")
{
rate = "0.8%";
}
$('#interest').val(rate);
});
You need to read more about JS syntax and jQuery selectors and functions use
Check the fiddle update
http://jsfiddle.net/sedz/rmjKV/2/
Stuff like this
$(#acc_type)
should be
$('#acc_type')
You've got numerous errors in your code. I think I've fixed most of them below.
I've also wrapped you code in jquery's ready function, so the the script doesn't try and add the event before the page is fully loaded etc.
$(document).ready(function() {
$('#account').change(function() {
var rate = "0.6%";
if ($('#acc_type').val() == "current") {
rate = "0.6%";
} else if ($('#acc_type').val() == "savings") {
rate = "0.8%";
}
$('#interest').val(rate);
})
})
JSHint doesn't validate your code. Aside that, it looks like you are binding to the form change not the acc_type change.
$("#acc_type").change(function() {
}
Valid JS Code:
$("#acc_type").change(function()
{
var rate = "0.6%";
if ($("#acc_type").val() == "current")
{
rate = "0.6%";
} else if ($("#acc_type").val() == "savings")
{
rate = "0.8%";
}
$("#interest").val(rate);
});
http://jsfiddle.net/rmjKV/5/
$("#acc_type").change(function() {
var rate = "0.6%";
if ($('#acc_type').val() == "current") {rate = "0.6%";}
else if ($('#acc_type').val() == "savings") {rate = "0.8%";}
$('#interest').val(rate);
});
Find here http://jsfiddle.net/rmjKV/8/ your jsFiddle working, your old code was full of typos

Categories

Resources