Which button calls javascript file - javascript

Hi I have an HTML for with 2 buttons
<li>
<!--<input type="button" onclick="getOptions()" value="Click Me!" style="margin-left:156px">-->
<button class="submit" type="button" id="orderTickets" onclick="">Order Tickets</button>
<button class="submit" type="button" id="startAgain" onclick="">Start Again</button>
</li>
Both buttons call the the external script file:
$(document).ready(function()
{
$("#departing").datepicker();
$("#returning").datepicker();
$("button").click(function()
{
var destinationTo = $("#myDestination option:selected").text();
var departingFrom = $("#myDepart option:selected").text();
var departing = $("#departing").val();
var returning = $("#returning").val();
var numAdults = $("#adults option:selected").text();
var numChildren = $("#children option:selected").text();
var travelType = $("#class option:selected").text();
if (departing === "" && returning === "")
{
alert("Please enter your travel dates.");
}
else if (returning === "")
{
alert("Please enter a return date.");
}
else if (departing === "")
{
alert("Please enter a departing date.");
}
else
{
confirm("Please confirm your travel: outward journey from " + departingFrom + " on " + departing + " to " + destinationTo + " returning on " +
returning + " adults " + numAdults + " children " + numChildren + " travelling in " + travelType + " coach " + "?");
}
});
});
I only want the button "orderTickets to run the script. I'm sure I can establish the buttin ID within the script then determine if I want to run it, but not sure how. The other button "startAgain" simply clears the form! Maybe my attempt is not the best solution?
HTML and javascript is not my thing and would appreciate some help with this?

Please use
$("#orderTickets").click(function()
{
.
.
.
instead of
$("button").click(function()
{
.
.
.
A little Ps:
$("#orderTickets") selects by id attribute, if you want to select by class you can use $(".orderTickets")

I would use a submit handler on the form itself and change the type of #orderTickets to submit instead of button. A button with type="button" will not submit a form
This way if user uses keyboard enter you catch the event also and aren't relying on click of a button (which may never occur).
If any of the validation fails just return false to prevent the event completing.
$('#formID').submit(function(){
var errors = false;
/* do your validation making errors= true if anything fails */
return !errors;
});

Related

JavaScript validate, then print and submit

I have a submit function to validate form inputs, then optionally (checkbox) print as part of the submit process.
The problem is that when printed, form submission never completes, without printing form submission works correctly.
<INPUT class=checkboxes id="Place order" onclick="return checkfields()" type=submit value=SUBMIT name="Place order">
The validation always works correctly (AFAIK).
function checkfields() {
var missinginfo="Please fill the following information";
var bres = true, qty=0, elem;
var tqty = document.getElementById('bottles').value;
if (tqty ==0){alert("No wine selected");bres=false;return bres;}
if (tqty %6 !=0){
alert("Orders need to be in 6 bottle packs please add " + (6 -(tqty %6)) + " Bottles to order");
bres=false;
return bres;
} //end if
for (i=1; i<30; i++) {
elem = document.getElementById('f'+i);
if(elem !=null){
if(elem.value== ""){ // ||
//(document.form.website.value.indexOf("http://") == -1) ||
//(document.form.website.value.indexOf(".") == -1)) {
bres = false; missinginfo += "\n " + (document.getElementById('f'+i).name);
} //end if
} //end if
} //end for
if(!bres){alert (missinginfo );}
// end of validation here, print if checkbox checked
if(bres && document.getElementById('cprint').checked==true){window.print();}
document.getElementById('doc').value = "";
return bres;
} //end function
Any suggestions on how to remedy, or am I doing something completely wrong?
Use onsubmit instead of onclick:
<INPUT class="checkboxes" id="Place order"
onsubmit="return checkfields();"
type="submit" value="SUBMIT" name="Place order">

want to check the value of the input type number

i'm new to js i wanted to check the entered number of amount in input type "number"
<input type="number" id="val" value="1" class="input-text" >
I was trying
$("input: number").focus(function(){
var val = $("#val").val();
alert("there are", val + "in your cart");
});
i don't know how to get value from form fields with jquery i just wanted to display the number entered in number field
Here is an fiddle example https://jsfiddle.net/s81g6963/
Find the below code. When the document is ready you can get input field value. For more info check my jsfiddle link. Note: you can use blur event instead of focus.
$(document).ready(function()
{
var get_val = $("#val").val();
alert("there are " + get_val + " in your cart");
$("#val").blur(function(){
var get_val = $(this).val();
alert("there are " + get_val + " in your cart");
});
});
jsfiddle

Javascript code disappears after button click

I'm trying to make a sub-total calculation tool, but I can't continue because I don't know what the problem is. When the form is submitted, or the button is clicked, everything quickly disappears.
Here's the fiddle :: http://jsfiddle.net/xFmBK/
I'm clueless...
function calcSub(){
var input = document.getElementById('fld'),
subTotal = document.getElementById('sub-total'),
tax = document.getElementById('tax'),
total = document.getElementById('total');
var subTotalCalc = input.value / 1.06;
var flag = true;
if(input.value == "" || input.value == null){
alert("Please enter in a total!");
return false;
} else {
subTotal.innerHTML = "Subtotal:" + " " + "$" + subTotalCalc;
tax.innerHTML = "Tax:" + " " + "$" + input.value - subTotalCalc;
total.innerHTML = input.value;
return flag;
}
}
That happens because your submit button actually does a form submit on some action and page is being refreshed. There are some ways to fix behavior, such as:
make your submit button just a button: <input type="button">
actually doesn't seem you need a form there
or add return false to onClick handler:
<button type="submit" onclick="calcSub(); return false;">Calculate</button><br>
Be aware of another issue: You have to use parentheses around (input.value - subTotalCalc). Without parentheses, you're trying to add and subtract strings, which results in NaN.
tax.innerHTML = "Tax:" + " " + "$" + (input.value - subTotalCalc);`
Your form is getting submitted when you click on the button, so the values are getting calculated but are disappearing immediately as the page is re-loaded.
Try adding onsubmit='return false;' to your form tag and the page re-load will be prevented.
Alternately you can change the button type to button.
Check this fiddle.
Just remove all the return from your code and add return false at the end
You need to prevent the form from being submitted. The form might be submitted by the user pressing enter when the form element is in focus, or by clicking the submit button. Even if the onclick event returns false, the submit event isn't altered.
I've taken the liberty of forking your fiddle:
Check the demo
window.addEventListener('load',function()
{
var input = document.getElementById('fld'),
subTotal = document.getElementById('sub-total'),
tax = document.getElementById('tax'),
total = document.getElementById('total'),
subTotalCalc;
document.getElementById('calcForm').addEventListener('submit',function(e)
{
e = e || window.event;
e.preventDefault();//prevent form's default behaviour
e.stopPropagation();//if submit was sent by clicking submit button, stop the event here
if (input.value === '' || input.value != +(input.value))
{
alert('Please enter valid subtotal (numeric)');
return;
}
subTotalCalc = input.value / 1.06;
subTotal.innerHTML = "Subtotal:" + " " + "$" + subTotalCalc;
tax.innerHTML = "Tax:" + " " + "$" + (input.value - subTotalCalc);
total.innerHTML = input.value;
},false)
},false);
I'd be happy to explain the code further if needs be...
Note that this doesn't fix the issue JS has with floating-point precision, if you're thinking about asking a follow-up question on that matter, check this fiddle first! I've added a simple toDecimal function here:
var toDecimal = function(num, precision)
{
precision = precision || 2;
num = +(num || 0);
return ( Math.round(num*Math.pow(10, precision))
/ Math.pow(10,precision)
).toFixed(precision);
};
So first multiply by 10^n, round and divide to 10^n again to get the desired float. To avoid any issues that might occur still (though there shouldn't be any AFAIKT, I've added a toFixed(n) call, too. This might be useful in case the rounded number is 213.00

Unable To Send Emails With JavaScript

An old thread on Stack Overflow discusses how to use JavaScript to fill in a mailto email:
Sending emails with Javascript
I was interested in applying the technique, but couldn't get it to work.
In the code below, when I set a breakpoint on return false in the makecontact() method, and look at the URL that it logs, it looks fine.
But the browser does not open the email client.
If I hardcode the same URL in an href in the Submit button, then it launches the email client.
Why doesn't setting the href work?
ANSWER: It was the wrong href.
Fixed version:
<!-- TODO: Validate name and text fields and don't allow submit until they are valid. Limit total mailto URL length to 2000. -->
<form name="contact">
<br/>Reason for contact:
<br/>
<input type="radio" name="reason" value="Product Inquiry/Presales Questions" checked="checked"/>Product Inquiry/Presales Question<br/>
<input type="radio" name="reason" value="Support/Warranty"/>Support/Warranty<br/>
<input type="radio" name="reason" value="Feedback"/>Feedback<br/>
<input type="radio" name="reason" value="Other"/>Other<br/>
<input type="text" name="name" id="name"/>Your name:</div>
<textarea name="contacttext" rows="20" cols="60" id="contacttext"></textarea>
<button id="submit">Submit</button>
</form>
<script type="text/javascript" id="contactjs">
<!--
var submit = document.getElementById("submit");
function getreason() {
var radios, i, radio;
radios = document.getElementsByName("reason");
for (i = 0; i < radios.length; i += 1) {
radio = radios[i];
if (radio.checked) {
break;
}
}
return encodeURIComponent(radio.value);
}
function makecontact(e) {
var subject, name, text;
subject = getreason();
name = document.getElementById("name").value;
text = document.getElementById("contacttext").value;
body = "From: '" + name + "', Content: '" + text + "'";
body = encodeURIComponent(body);
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
console.log(document.location.href);
e.preventDefault();
return false;
}
if (submit.addEventListener) {
submit.addEventListener("click", makecontact, true);
} else if (form.attachEvent) {
submit.attachEvent("onclick", makecontact);
} else {
submit.click = makecontact;
}
//-->
</script>
</div>
body = "From: '
" + name + "
', Content: '
" + text + "
'";
This is not valid JavaScript. It will cause an "Unterminated string constant" error. Try this instead:
body = "From: '\n" + name + "\n', Content: '\n" + text + "\n'";
You have two main problems:
button elements don’t have hrefs (HTML4, HTML5). Setting one won’t do anything. At the end of your submit handler, you should instead set document.location.href:
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
You can’t have literal newlines in strings in JavaScript. Use \n instead:
body = "From: ' \n" + name + " \n', Content: ' \n" + text + " \n'";
Also be aware…
You should accept an event object in your event handler, and call event.preventDefault() instead of just returning false from your event handler, to stop the form from being submitted.
There’s no function called resume, but you’re using it if neither addEventListener nor attachEvent exists.

How do I use onFocus, onChange, and onClick events on a <input type="text"> field

I have a homework assignment where I am supposed to use the onFocus, onChange and onClick events on each of three form fields. Each event is supposed to pass the field name to the function. The function is supposed to alert that the event has taken place and let the user know how many alerts have occurred. I have spent the last week trying to find the answer and all I have been able to consistently find is that the onFocus event is NOT to be used with text fields (that does not change my assignment though). The code I have so far is as follows:
<SCRIPT LANGUAGE="JavaScript">
<!--
var numEvents = 0;
var field1 = "";
var field2 = "";
var field3 = "";
function clickedField(fieldId) {
if (document.form1.field1.value = field1){
events=runningTotal(1);
alert("You have clicked Field 1. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field2.value = field2){
events=runningTotal(1);
alert("You have clicked Field 2. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field3.value = field3){
events=runningTotal(1);
alert("You have clicked Field 3. Alert Count = " + runningTotal(i) + ".");
}
}
function changedField(fieldId) {
if (document.form1.field1.value!= field1){
events=runningTotal(1);
alert("You have changed Field 1. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field2.value!= field2){
events=runningTotal(1);
alert("You have changed Field 2. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field3.value!= field3){
events=runningTotal(1);
alert("You have changed Field 3. Alert Count = " + runningTotal(i) + ".");
}
}
/*
function focusedField(fieldId) {
if (document.form1.field1.value = field1){
events=runningTotal(1);
alert("You have focused on Field 1. Alert Count = " + runningTotal(i) + ".");
}
else if (document.form1.field2.value = field2){
events=runningTotal(1);
alert("You have focused on Field 2. Alert Count = " + runningTotal(i) + ".");
}
else if (document.form1.field3.value = field3){
events=runningTotal(1);
alert("You have focused on Field 3. Alert Count = " + runningTotal(i) + ".");
}
}*/
function runningTotal(i){
numEvents += i;
return numEvents;
}
// -->
</SCRIPT>
I know there are several errors though not in the actual code because it is not doing what I need it to do. Before I added the . Alert Count = " + runningTotal(i) + "." and the argument to the alert it was telling me when I changed a field.
I'm not sure you need the folloing code to trigger those javascript functions
<input name="field1" id="field1" onfocus="focusedField(this.id)" onclick="clickedField(this.id)" onchange="changedField(this.id)"/>
<input name="field2" id="field2" onfocus="focusedField(this.id)" onclick="clickedField(this.id)" onchange="changedField(this.id)"/>
<input name="field3" id="field3" onfocus="focusedField(this.id)" onclick="clickedField(this.id)" onchange="changedField(this.id)"/>
if (document.form1.field1.value = field1){
Need to be
if (document.form1.field1.value == field1){
First, I don't see anywhere in your code that you assign those functions to the necessary events.
Second, I don't see anywhere that the field1, field2, and field3 vars are assigned to a value. Along with that, you are checking the value of the field, and I'm not sure why you are doing that, anyway.
And third, you have to use == to test for equivalency, not =.
first things first: your if statements need comparison operators (==) instead of assignment operators (=), after that
something like this would work:
window.onload = function(){
document.form1.field1.onclick = function(){
changedField(this);
}
}
It would send a reference to itelf to the function, where you can access its value or id etc.
It needs to be handled after window.onload to ensure the form items exist before the event is assigned.

Categories

Resources