jQuery change text based on drop down list option - javascript

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

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

check if user inserted value higher then 0 with vanilla js

I am creating a custom js validator from scratch, without the use of any libraries.
I want to validate a numeric input by checking if the user-inserted content in the input tag is great than 0:
<label>Price
<input type="text" id="price" name="price">
</label>
Attempt:
function price()
{
if (#price.value>0)
console.log('0.');
else
console.log('Incorrect');
}
Would this not work:
if(price.value.match(/^[0-9]+$/) && +(price.value) > 0){
im not quite sure what the hash symbol is being used for so i removed it in my example. Unless you are trying to find the ID in which you would have to look for the element like so:
var price = document.querySelector("#price");
function price()
{
var price = document.getElementById("#price"); // get the element
if (isNaN(price.value) || price.value <= 0) // if the value is not a number or is less than 0
console.log('Incorect');
else // otherwise
console.log('Correct');
}
How about some thing like that
var price = document.getElementById("price").value;
if (parseInt(price) > 0 && !isNaN(price)))
{
// then do something
}
else
{
// else do something
}

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]);
}

How to write simplified and generic validation logics and rules in JQuery

I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}

Why this javascript executes in Chrome but not in Firefox?

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

Categories

Resources