HTML/Javascript: Trigger 2 different action from 1 button - javascript

How can we trigger 2 action from 1 button? How do we make a button/or links which can go/scroll to element "#result" and trigger the function "calculateThis" (proceed data from a form)
How do I mix the these into 1 button/link?
Submit
and
<button class="button" onclick="calculateThis(this.form); return false;">Submit</button>
// UPDATED
Here is the complete code
<script type="text/javascript">
function calculateThis(form) {
var userweight=parseInt(form.weight.value, 10);
var caffeineamount=parseInt(form.caffein.value, 10);
var caffeinetimes=parseInt(form.caffeintimes.value, 10);
var totalcaffeine=caffeineamount*caffeinetimes;
console.log(totalcaffeine)
// Calculate max caffeine per person
var maxcaffeine=userweight*10;
// Calculate remaining after 24 hours
// Half life = 6 hours
var totalcaffeineafter=totalcaffeine*(1/16);
// Calculating how many hours until the caffeine completely digested
var totaldigest=totalcaffeine;
var digesttime=0;
while (totaldigest>0.05) {
totaldigest=totaldigest*(1/2);
digesttime++;
}
digesttime=digesttime*6;
// Calculating when the user will probably die of overdose
var countcaffeine=0;
var overdosetime=1;
while (countcaffeine<maxcaffeine){
countcaffeine=countcaffeine+totalcaffeine;
overdosetime++;
}
// Show total amount of caffeine
document.getElementById("showtotalkafein").innerHTML=totalcaffeine;
// Show amount of caffeine after 1 day
document.getElementById("showtotalkafeinsetelah").innerHTML=totalcaffeineafter;
// Show digest time
document.getElementById("showwaktudigest").innerHTML=digesttime;
// Show overdose
document.getElementById("showberapakali").innerHTML=overdosetime;
return false;
}
</script>
<form class="form">
Weight<br />
<input type="text" name="weight" class="required" value="" /><p />
Amount of caffein in coffee<br />
<input type="text" name="caffein" class="required" value="" /><p />
How many times drinking coffeein a day<br />
<input type="text" name="caffeintimes" class="required" value="" /><p />
Submit
</form>
<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br />
<h1 id="result">Result</h1>
<p id="showtotalkafein">Show Caffein Total Here</p>
<p id="showtotalkafeinsetelah">Show Caffeine Amount After 24 hours</p>
<p id="showwaktudigest">Show Digest Time Here</p>
<p id="showberapakali">Show Overdose Time Here</p>

You should be able to do the same as in the button, i.e
Submit
Doesn't this work?

JaggenSWE's answer is almost there, but don't return false since this suppresses default behaviour, which is to follow the link.
Submit
I wouldn't advise using inline event handlers though.
Edit
This works. http://jsbin.com/uwatab/3/
Its always preferable to attach an onsubmit handler to a form, rather than button onclick. This way, pressing enter in your form still executes your javascript.

Related

Multiple inputs update multiple textarea's

exactly what the title describes.
i'm wanting 1 set of 6/7 input fields to be able to update 4/5 different textareas for different templates to copy paste from with the input elements.
ive tried using getelementsbyclassname but it doesnt seem to work with multiple textareas.
a simple example for multiple inputs updating multiple textarea's would be enough to play with.
This is what i have so far, and its not complete.
1 name: <input type="text" name="1stTarget" onblur="tst1(this);" /><br />
2 name: <input type="text" name="2ndTarget" onblur="tst1(this);" /><br />
Email address: <input type="text" name="3rdTarget" onblur="tst1(this);" /><br />
Phone #: <input type="text" name="4thTarget" onblur="tst1(this);" /><br />
Schedule: <input type="text" name="5thTarget" onblur="tst1(this);" /><br />
<textarea name="result" id="result1" onClick="this.select();" class="disable">Hello 1stTarget, 2ndTarget i would like to confirm your email address 3rdTarget and phone # 4thTarget and the time you will be at work 5thTarget</textarea>
<br />
<textarea name="result2" id="result2" onClick="this.select();" class="disable">1stTarget and 2ndTarget updated their 5thTarget and their 4thTarget including their 3rdTarget</textarea><input type="reset" value="Reset!" />
using
<script type="text/javascript">
function tst1(elm){
var trgt=document.getElementById('result1');
trgt.value=trgt.value.replace(elm.getAttribute('name'), elm.value);
}
</script>
If I were you, I would not try to replace the text in the textarea but instead simply build the string you need from your inputs and set the text when that's done. Something like the below would work for that:
Note THe main function you need is jQuery's eq()
$('#fill').click(function(elm) {
var hasErrors=false;
var $updateElms=$('.update');
$updateElms.removeClass('hasError');
$updateElms.each( function(i,e){
if($(e).val()==''){
hasErrors=true;
$(e).addClass('hasError');
}
});
if(hasErrors) return;
var name1 = $updateElms.eq(0).val();
var name2 = $updateElms.eq(1).val();
var email = $updateElms.eq(2).val();
var phone = $updateElms.eq(3).val();
var schedule = $updateElms.eq(4).val();
var text0 = 'Hello '+name1+', '+name2+' I would like to confirm your email address '+email+' and phone # '+phone+' and the time you will be at work '+schedule;
var text1 = 'Hi '+name1+', '+name2+' we have recieved your confirmation that your email address is '+email+' and phone # is '+phone+' and that you will be at work '+schedule;
var text2 = 'Hello '+name1+', '+name2+' we have attempted to reach you via your email address '+email+' and phone # '+phone+' to advise that you missed your shift at '+schedule;
$('.result:eq(0)').val(text0);
$('.result:eq(1)').val(text1);
$('.result:eq(2)').val(text2);
});
.hasError{
color:red;
background-color:#F9B9B9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1 name:
<input type="text" class="update"/>
<br />
2 name:
<input type="text" class="update"/>
<br />
Email address:
<input type="text" class="update"/>
<br />
Phone #:
<input type="text" class="update"/>
<br />
Schedule:
<input type="text" class="update"/>
<br />
<input type="button" id="fill" value="Fill Textareas"/>
<br />
<textarea name="result" class="disable result"></textarea>
<br />
<br />
<textarea name="result" class="disable result"></textarea>
<br />
<br />
<textarea name="result" class="disable result"></textarea>
<br />
<input type="reset" value="Reset!" />using

JavaScript math not adding up correctly

I am having a problem with my math function below. The depreciationFee variable adds up correctly, but for some odd reason the financeFee variable does not. I am trying to calculate the monthly lease payment of a vehicle. Whenever I submit the numbers for financeFee it shows two number appended to each other rather than added together. Is there a reason the numbers aren't adding up correctly?
$(".submit").click(function() {
function calculateLease() {
var capitalCost = $(".capital-cost").val();
var downPayment = $(".down-payment").val();
var residualCost = $(".residual-cost").val();
var monthTerm = $(".month-term").val();
var moneyFactor = $(".money-factor").val();
var depreciationFee = (((capitalCost - downPayment) - residualCost) / monthTerm);
// THIS IS THE ONE THAT DOESN'T WORK
var financeFee = ((capitalCost - downPayment) + residualCost);
alert(financeFee);
}
calculateLease();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lease-calculator-container">
<h3>LEASE CALCULATOR</h3>
<form method="get">
<input type="text" class="capital-cost" placeholder="MSRP" />
<br />
<input type="text" class="down-payment" placeholder="DOWN PAYMENT" />
<br />
<input type="text" class="residual-cost" placeholder="RESIDUAL" />
<br />
<input type="text" class="month-term" placeholder="TERM IN MONTHS" />
<br />
<input type="text" class="money-factor" placeholder="MONEY FACTOR" />
<br />
</form>
<input type="submit" class="submit" value="CALCULATE" />
<div class="monthly-cost"></div>
<div class="total-cost"></div>
</div>
Do a parseInt(value,10) for intergers or parseFloat(value) for float.
JavaScript appends the values if the data type is not a number.

Why won't my button run my javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hi im having trouble figuring out why my button will not work below is my code any help is appreciated. basically once i hit button it should either print story with typed in words or if a spot is left blank story doesnt show and box thats missing characters is surrounded with red border
thanks.
HTML code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="script.js"></script>
<title>assignment2</title>
</head>
<body>
<div id= "list">
<form id="form1" method="get">
<h3> Fill in the blanks and then press the submit button. </h3>
<label> Adjective
<input type="text" name="adjective"id ="adjective"/>
</label>
<br />
<br />
<label> Adjective
<input type="text" name="adjective2"id ="adjective2"/>
</label>
<br />
<br />
<label> Plural Noun
<input type="text" name="pluralnoun"id ="pluralnoun"/>
</label>
<br />
<br />
<label> Verb (ending in "ing")
<input type="text" name="verb"id ="verb"/>
</label>
<br />
<br />
<label> Edible object
<input type="text" name="edibleobject"id ="edibleobject"/>
</label>
<br />
<br />
<label> Monster
<input type="text" name="monster"id ="monster"/>
</label>
<br />
<br />
<label> Adjective
<input type="text" name="adjective3"id ="adjective3"/>
</label>
<br />
<br />
<label> Monster (again)
<input type="text" name="monster2"id ="monster2"/>
</label>
<br />
<br />
<label> Verb (ending in "ing")
<input type="text" name="verb2"id ="verb2"/>
</label>
<br />
<br />
<button type="submit" id="btn" name="btn"/>View Story</button>
</form>
</div>
<div id="story">
<p> Rain was still lashing the windows, which were now <span class ="adjective"> </span>, but inside all looked bright and cheerful. The firelight glowed over the countless <span class ="adjective2"></span><span class ="pluralnoun"></span> where people sat <span class ="verb"></span>, talking, doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a <span class ="edibleobject"></span> to a <span class ="monster"></span>. Fred had "rescued" the <span class ="adjective3"></span>, fire-dwelling <span class ="monster2"></span> from a Care of Magical Creatures class and it was now <span class ="verb2"></span> gently on a table surrounded by a knot of curious people.
</p>
</div>
</body>
</html>
Javascript code:
$(document).ready( function() {
$('#story p').hide();
$('#form1').on('submit', function(event)
{
for(var i=0 ;i<$('#form1 input').length; i++) //tyler suggested this to make it easier fo my error borders.
{
$('#form1 input').eq(i).removeclass("errorborder");
}
if (!formFilled()){
event.preventDefault();
}
else
{
$('span.adjective').html($('#form1 input#adjective').val());
$('span.adjective2').html($('#form1 input#adjective2').val());
$('span.pluralnoun').html($('#form1 input#pluralnoun').val());
$('span.verb').html($('#form1 input#verb').val());
$('span.edibleobject').html($('#form1 input#edibleobject').val());
$('span.monster').html($('#form1 input#monster').val());
$('span.adjective3').html($('#form1 input#adjective3').val());
$('span.monster2').html($('#form1 input#monster2').val());
$('span.verb2').html($('#form1 input#verb2').val());
$('#story p').show();
event.preventDefault(); //Tyler informed me this would stop the page from refreshing and deleting the inputted words.
}
});
function formFilled(){
var filled=true;
for(var i=0;i<$('#form1 input').length; i++)
{
if ($('#form1 input').eq(i).val() === "")
{
$('#form1 input').eq(i).addClass("errorborder");
filled=false;
}
}
return filled;
}
});
CSS code:
.errorborder{
border:red, 3px,solid;
}
span {
color: blue;
text-decoration: bold;
font-style: italic;
}
I've used some of the suggestions in comments above, and changed around a few things myself and cleaned up the code. I've made it work...
The primary changes were
change the form method to post
change your <button> to <input type="submit">
please see this jsFiddle to see a working example of your code.
Hope you're able to see your mistakes by comparing with your own code!

How to disable radio button After 1 Click

JS :
function checkValue(option) {
if (option == "4") {
alert("Correct");
var pop = parseInt(window.name++);
alert(pop);
window.location="q2.html";
}
else {
alert("False, Option (4) is the Correct Answer.");
window.location="q2.html";
}
}
Html :
<html>
<input type="radio" name="option_1" value="1" onclick="checkValue(this.value);" /> Hyper Text Markup Languages <br /> <br />
<input type="radio" name="option_2" value="2" onclick="checkValue(this.value);" /> Highest Text Markup Language <br /> <br />
<input type="radio" name="option_3" value="3" onclick="checkValue(this.value);" /> Hyper Total Markup Language <br /> <br />
<input type="radio" name="option_4" value="4" onclick="checkValue(this.value);" /> Hyper Text Markup Language <br /> <br />
</html>
First thing, I'd clean up the HTML code a bit... I assume the four radio buttons are all possible answers to one question, in which case they should all have the same name (not value) so that you can only choose one answer; then in the script I'd would need to use more information than just the value of the checked answer, so instead of sending this.value to the function, I'd just send this:
<input type="radio" name="question_1" value="option_1" onclick="checkValue(this);" /> Hyper Text Markup Languages <br /> <br />
<input type="radio" name="question_1" value="option_2" onclick="checkValue(this);" /> Highest Text Markup Language <br /> <br />
<input type="radio" name="question_1" value="option_3" onclick="checkValue(this);" /> Hyper Total Markup Language <br /> <br />
<input type="radio" name="question_1" value="option_4" onclick="checkValue(this);" /> Hyper Text Markup Language <br /> <br />
In the script, to disable the radio buttons after they've been clicked, I would add a function that goes through each radio button that has the same name (as mentioned above) as the one that's been clicked, and disable it:
var radiobuttons = document.getElementsByName(option.name);
for(i = 0; i < radiobuttons.length; i++) {
radiobuttons[i].disabled = true;
}
Then, of course, the alert to let the visitor know whether they've got the right answer:
if (option.value == "option_4") {
alert("Correct");
} else {
alert("False, Option (4) is the Correct Answer.");
}
Here's a fiddle: http://jsfiddle.net/Niffler/nyqk6gga/
(I'm assuming you don't want to use jQuery; otherwise there would be much nicer-looking ways to do this...)
$(document).delegate(".rndmyradio","click",function () {
$(this).hide();
//if you want values of selected
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="rndmyradio" type="radio" name="option_1" value="1" /> <label>Hyper Text Markup Languages </label><br /> <br />
2. <input class="rndmyradio" type="radio" name="option_2" value="2" /> Highest Text Markup Language <br /> <br />
3. <input class="rndmyradio" type="radio" name="option_3" value="3" /> Hyper Total Markup Language <br /> <br />
4. <input class="rndmyradio" type="radio" name="option_4" value="4" /> Hyper Text Markup Language <br /> <br />

Implementing Scrolling progress bar for more than one element

I'm trying to implement the scrolling progress bar. (The bar that'll tell the user about How much of an article within an div (s)he has read).
Something like implemented on this site.
I've Designed my custom bar and coded it on fiddle. It works fine you can see it.
Here is code:
HTML:
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="xyz">
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
Hello !!<br />
XYZ<br />
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="xyzprog"><div id="prog">Intro</div></div>
JQuery/JS:
$(function(){
$(window).scroll(function(){
var elemTop=$("#xyz").offset().top,elemHeight=$("#xyz").height();
var total=elemTop+elemHeight;
var scTop=$(window).scrollTop();
var prog=((scTop-elemTop)/elemHeight)*100;
var html="Intro;Read=";
if(prog>100){ prog=100; html="Intro;Read=" }
if(prog<0){ prog=0; }
$("#prog").animate({
"width":""+prog+"%"
},1).html(html+""+prog+"%");
});
});
CSS is irrelevant so not posting it.
Now what I want is:
Is there any way to make this code work for more than one element (say 10 minimum)?
Can anyone design a plugin that will work like say $(elem).scrollProgress() and how? I'm really eager to design one but don't know how to start :(.
Is there any better way to do it?
Any advice, idea, thoughts are greatly appreciated!
Thanks in advance :).
There are already some plugins doing what you want. Check out toc-scrolling-progress.
But if you want it on the whole page you could do something like this:
$(window).scroll(function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var distanceToTop = $(window).scrollTop();
var percentScrolled = distanceToTop/(documentHeight - windowHeight) * 100;
$('#progress-bar').css({'width': percentScrolled + '%'});
});
I created a jsfiddle with a demo

Categories