So Im learning jQuery at the moment, and have to make a Loan calculator based on choices, as well as validate enteries, then output a result.
l wanted to make sure you guys knew what I was trying to do, so I have here a flow chart of what is supposed to happen: http://i59.tinypic.com/8z02sh.jpg
Problem is I dont know how to do this is Jquery. I asked a question earlier, got some feedback. None of the code people provided to outright fix my code, actually worked. I took a guy named "Parody"s work, and rewrote my code. I am no longer getting errors, and what im doing now makes sense to me. Problem is, when i input a number, and click the button, nothing happens. So here's my code so far.
Thanks ahead of time.
http://jsfiddle.net/mL74efjd/1/
HTML -
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="0">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="0">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="0">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
JS-
$('#check').click(function()
{
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid)
{
if (salary < 40000)
{
if ($('#over1').is(':checked'))
{
if ($('#job1').is(':checked'))
{
$('#message').html("Loan Approved.")
}
else {
$('#message').html("Loan Denied.")
}
}
else
{
$('#message').html("Loan Denied.")
}
}
else if (salary >= 40000)
{
if ($('#under1').is(':checked'))
{
if ($('#job2').is(':checked'))
{
$('#message').html("Loan denied.")
}
else
{
if ($('#job1').is(':checked'))
$('#message').html("Loan Approved.")
}
}else
{
$('#message').html("Loan Approved.")
}
}
}
});
// form validation
$.validator.setDefaults({
errorElement: "span",
errorClass: "form_error",
errorPlacement: function(error, element){
error.insertAfter(element)
}
});
$.extend($.validator.messages,{
required: "* Required field"
});
$('#salaryForm').validate(
{
rules:
{
salary:
{
required: true,
digits: true,
range: [1, 1000000]
}
}
});
variable salary is not initiailized inside click method. Put--
var salary=$("#salary").val();
Also in fiddle jquery and jquery-validation library are not included
I think you haven't added jQuery validation libraries. The line
$('#salaryForm').validate().form();
will give error as validate() method doesnt exist.
So add validation libraries in your html and assign a value to the salary variable.
var salary = $("#salary").val();
It will work fine then.
Related
(Duplicate?) I've tried several Stackoverflow postings related to this, but I cannot get a javaScript example to work. I'd like to avoid having to use jQuery, for the time being.
I want to create the information shown by radio buttons dynamically, using javascript. In this example, I would want to write a function that displays some other values for these radio buttons 'Answer 1' and 'Answer 2'. For example, I don't actually want 'Answer 1'. Goal is for the user to click on one of the multiple choice answers, then hit submit/save to self-check their own knowledge.
I have already learned, through my more complex project code, that a submit/save button that is hard-coded into the html <form> section does not seem to associate with values displayed by the radio buttons, that I managed to add in using javaScript * It seems to me that changing hardcoded information already displayed by the radio buttons might work.
When user clicks on the submit/'save' button, I don't need to refer to the actual answer information that the radio button is displaying. I only need to know whether , in this case, it's the first or second answer chosen.
<html>
<script type="text/javascript">
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
}
</script>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" name="operation" value="1" checked>Answer 1
<input type="radio" name="operation" value="2">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
</html>
(I don't know if I should include this following example I tried as well)
BTW Here is another of the example I tried - a posting but I cannot get this idea to work . I was trying to get the first radio button to display 'junk' instead of 'Answer1' as originally hard coded. But I have an error from code borrowed from posting, that I cannot resolve.
It's from
Javascript how to change radio button label text?
<html>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1" checked <label for="alsoFirst"> Answer 1
<input type="radio" id = 'second' name="operation" value="2"<label for="alsoSecond">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementById('first').getElementsByTagName('alsoFirst') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
if (document.uniqueName.checked == true){
alert ( "You have selected the THIRD answer" );
}
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
I previously got values from my arrays to display by inserting table rows and concatenating strings. This worked, and went into the table, but did not tie into the submit/save button hardcoded into original <form>. I still plan to have radio answer buttons in a table, but I'm trying to make a more basic example here.
I Have made some modifications for getting label through document.getElementByTagName() and also some changes to OnSubmitForm() function. And just pasted your code with those changes below and demo link at the end.
<html>
<form name="myform" onsubmit="OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1"
checked> <label for="alsoFirst"> Answer 1 </label>
<input type="radio" id = 'second' name="operation" value="2">
<label for="alsoSecond">Answer 2</label>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementsByTagName('label') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.getElementById('first').checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.getElementById('second').checked == true)
{
alert ( "You have selected the SECOND answer" );
}
return false;
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//http://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
Demo : https://jsbin.com/sojojiy/27/edit?html,console,output
Hope this helps. Thanks !
Looking at posts such as https://stackoverflow.com/a/15453130/1032531, I see how I can validate the quantity of checked boxes.
Instead, I wish to validate checkboxes based on some other criteria such as whether another input is filled out.
EDIT. Context: Inputs are users home, work, and mobile phone. Checkboxes are "call me at home", "call me at work", and "call my mobile phone". They are checkboxes and not radioboxes, and as such, the user will get multiple responses if they check multiple checkboxes.
I've put together the following, however, it appears that jQuery Validator only looks at the first element of a given name. I can probably change the names to be unique instead of using the [], however, I wish the elements to be posted to the server as an array.
How can this be accomplished?
http://jsfiddle.net/suu44yng/
<p>one:
<input id="one" type="text" value="foo" />
</p>
<p>two:
<input id="two" type="text" />
</p>
<p>three:
<input id="three" type="text" value="bar" />
</p>
<hr>
<form id="myform">
<p>
<input type="checkbox" name="test[]" value="1" checked data-check="one" />One</p>
<p>
<input type="checkbox" name="test[]" value="2" checked data-check="two" />Two</p>
<p>
<input type="checkbox" name="test[]" value="3" checked data-check="three" />Three</p>
<p>
<input type="submit" />
</p>
</form>
(function() {
$.validator.addMethod("checkboxes", function(value, element, params) {
console.log(this, value, element, params);
console.log($(element).data('check'), $('#' + $(element).data('check')).val());
console.log(!$('#one').val(),!$('#two').val(),!$('#three').val());
var error = false;
if (value == 1 && !$('#one').val()) {
error = true;
}
else if (value == 2 && !$('#two').val()) {
error = true;
}
else if (value == 3 && !$('#three').val()) {
error = true;
}
console.log(error)
if (error) {
$(element).data('error', value);
return false;
} else {
return true;
}
},
function(params, element) {
return $.validator.format('This checkbox is not allowed since ' + $(element).data('error') + ' is empty.')
})
})();
$(document).ready(function() {
$('#myform').validate({
rules: {
'test[]': {
checkboxes: true
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false;
}
});
});
"I can probably change the names to be unique instead"
That's exactly what you're going to have to do. This plugin uses the name attribute to keep track of input elements and if you have multiple input elements with the same name, only the first one will be considered for validation and the others are ignored.
However, when you have a grouping of checkbox or radio elements sharing the same name, they are considered as a single data point for the form. Example: when setting the grouping to required, then at least one will need to be checked.
There is no workaround if you want each one to be considered individually with a custom rule. Naming would have to be specified as test[1], test[2], etc.
<input type="checkbox" name="test[1]" value="1" checked data-check="one" />One
<input type="checkbox" name="test[2]" value="2" checked data-check="two" />Two
<input type="checkbox" name="test[3]" value="3" checked data-check="three" />Three
rules object:
rules: {
'test[1]': {
checkboxes: true
},
'test[2]': {
checkboxes: true
},
'test[3]': {
checkboxes: true
}
},
Relatively new to html coding, and very new with javascript. On this page, I don't want the option to email an editor to become visible until a tripID is filled in (but form not submitted yet). Here is the form so far without that option added yet:
TripID:
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' /><br><br>
Port:
<input type='text' id='aport' name='aport' size='6' maxlength='6' /><br><br>
<div id=acheckbox><br> E-mail editor? </b>
<input type='checkbox' name='acheck' onchange='copyTextValue(this);'/><br>
<div id='div' style='display:none'>
<br> <b>Subject:</b> <input type='text' id='asubject' name='asubject' size='70' maxlength='75'/><br><br>
<textarea name='aemailbody' cols='85' rows = '10'>Explain any packaging or labeling mistakes here...</textarea>
</div>
</div>
<script>
function copyTextValue(bf) {
if(bf.checked){
document.getElementById('div').style.display = 'block';
var atext = 'Frozen Sample Error Notice: '+ document.getElementById('atripid').value;
}else{
document.getElementById('div').style.display = 'none';
var atext = '';
}
document.getElementById('asubject').value = atext
}
</script>
</div>
Now to hide the email editor option until tripid is filled in, I got something like this to work on jfiddle:
<form action="">
tripid:<input type="atripid" id="atripid" value="">
port:<input type="aport" id="aport" value="">
</form>
<div id="acheckbox" style="display:none">
<br><br><br>
This is where the email options (subject and textbox) would appear.
</div>
<script>
$("#atripid").keyup(function(){
if($(this).val()) {
$("#acheckbox").show();
} else {
$("#acheckbox").hide();
}
});
</script>
But for some weird reason, it won't work anywhere else, so I can't figure out how to incorporate it into what I already have. Does anyone have any ideas that could help me? Thanks!
You can do something like this with pure javascript:
<input type="atripid" id="atripid" value="" onkeyup="keyupFunction()">
And define your keyupFunction().
See jsfiddle
The code you attempted on jsfiddle requires that you import jquery.js files. An alternate way of doung what you intend to do is
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' onkeyup="toggleCheckBox(this)" />
<input type='checkbox' name='acheck' id="acheckbox" style="display:none;" onchange='copyTextValue(this);'/>
with js
function toggleCheckBox(element) {
if(element.value=='') {
document.getElementById('acheckbox').style.display = 'none';
}
else {
document.getElementById('acheckbox').style.display = 'block';
}
}
The issue is the .keyup() method, which is not consistent across browsers and does not account for other means of user input. You would rather, use an Immediately Invoked Function Expression (IIFE) that will detect the propertychange of the input field in question and then to fire the desired event if the condition is met. But for the purposes of simplicity, and the fact that I'm not as well versed enough in IIFE syntax, simply bind some events to the input field, like so:
$("#atripid").on("keyup change propertychange input paste", (function(e) {
if ($(this).val() === "") {
$("#acheckbox").hide();
} else {
$("#acheckbox").show();
}
}));
#acheckbox {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="">
tripid:
<input type="atripid" id="atripid" value="">port:
<input type="aport" id="aport" value="">
</form>
<div id="acheckbox">
<br>
<br>
<br>This is where the email options (subject and textbox) would appear.
</div>
I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.
I need to validate two things on this form:
1. There are two radio buttons:
• OPTION 1 - On click function hides mm/dd/yyyy fields for OPTION 2
• OPTION 2 - On click function shows mm/dd/yyyy fields which aren't required.
2. Zip code field - Need to validate an array of acceptable zip codes.
I've got this form MOSTLY working aside from a few issues:
1. If you click submit without checking or filling out anything it replaces some of the text on the page with the word "Invalid" and vice versa when valid info has been filled in.
2. It does not go to the next page if valid info has been submitted.
3. It only validates the zipcode field and does not require the radio buttons.
Any help would be greatly appreciated! Thanks!
Test page here: http://circleatseven.com/testing/jquery/zipcodevalidation/
If i have you understand you search for this:
I dont have write a Message with "invalid", i give an alert.
In your HTML add "onsubmit" to your form-Tag:
<form method="post" action="success.php" id="step1" onsubmit="checkdata();">
and add a submit-Button to your form or trigger on your pseudo-submit-button .submit() with jQuery.
In your Javascript you add following function:
function checkdata() {
if ($(":radio:checked").length < 1) {
alert('Please choose an Option!');
return false;
}
zipCodeOk = false;
zipCodes = new Array(75001, 75002, 75006); //Your Zip-Codes
for (var i = 0; i <= zipCodes.length; i++) {
if ($('#enterZip').val() == zipCodes[i]) {
zipCodeOk = true;
break;
}
}
if (!zipCodeOk) {alert('Please enter a valid Zip-Code!');return false;}
}
A friend helped me out.. We ended up using the Jquery validate plugin - here's what we came up with:
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("validZip", function(value) {
var zips=['12345', '23456', '34567', '45678', '56789', '67890', '78901', '89012', '90123', '01234'];
if ($.inArray(value,zips) > -1) {
return true;
} else {
return false;
}
}, "invalid zip");
$("#step1").validate({
rules: {
currentServiceStatus: "required",
enterZip: { validZip : true }
}
});
$('.moveInDates').hide();
$(":radio:eq(0)").click(function(){
$('.moveInDates').hide();
});
$(":radio:eq(1)").click(function(){
$('.moveInDates').show();
});
});
</script>
And here's the html:
<form method="post" action="success.php" id="step1">
<h1>CHOOSE *</h1>
<input name="currentServiceStatus" type="radio" value="Switch Me" /> OPTION 1
<br/>
<input name="currentServiceStatus" type="radio" value="Move-In" /> OPTION 2 (reveals more fields on click)
<div id="dateInputs" class="moveInDates">
<h2>Move-In Date (not required)</h2>
<p><span class="mmddyyyy"><input name="moveInDateMonth" type="text" class="text" id="moveInDateMonth" /> / <input name="moveInDateDay" type="text" class="text" id="moveInDateDay" /> / <input name="moveInDateYear" type="text" class="text" id="moveInDateYear" /></span>
</div>
<hr/>
<h1>ZIP CODE *</h1>
<p>Enter one of the following acceptable Zip Codes:</p>
<p>12345, 23456, 34567, 45678, 56789, 67890, 78901, 89012, 90123, 01234</p>
<input name="enterZip" type="text" class="text" id="enterZip" />
<hr/>
<input type="image" id="submitButton" src="http://circleatseven.com/testing/jquery/zipcodevalidation/library/images/btn_submit.jpg" />
<p><em>* Required</em></p>
</ul>