Trouble getting a Javascript function to run - javascript

I am still fairly new to Javascript and I am having some trouble getting a function to run properly. Here is what I have:
<script type='text/javascript'>
function GravityCalc (ratio, name)
{
Weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}
</script>
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick='GravityCalc(2.3,Jupiter)'>calculate</button>
<div id='WeightText'> </div>
The form displays perfectly, but nothing happens when the button is pressed. It also should probably be noted that eventually, the name and ratio parameters is going to be parsed in with PHP.

You have a couple things wrong...
'Weight' should be 'weight'. JS is case sensitive, and you had it in Camel case in one line and Pascal case in another line.
You need to use 'document.getElementById'. Just 'getElementById' doesn't work in all browsers.
You need to declare the 'Weight' variable.
The value in a dom element is stored as a string or char array if you will, thus you need to parse it to an int, like so, parseInt(document.getElementById('WeightBox').value)
Here's my JSFiddle... http://jsfiddle.net/EH5j6/
function GravityCalc (ratio, name)
{
var weight;
weight = parseInt(document.getElementById('WeightBox').value) * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}

javascript variables are case sensitive! Your Ws didn't match up. I also highly recommend using var to explicitly declare your variables.
var weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
plus, as a commenter noted, strings must be enclosed by quotes.
<button onclick='GravityCalc(2.3,"Jupiter")'>calculate</button>

Make sure that you include the javascript in the head of the html page.
function calc (ratio, name) {
var weight = document.getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = "You would weigh " + weight + " on " + name;
}
and change the HTML to be:
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick="calc(2.3, 'Jupiter')">calculate</button>
<div id='WeightText'> </div>

Related

HTML Textarea not compatible with JavaScript email form (I can work with 220 characters only)

I have developed the javascript email form, which was discussed here:
HTML Assigning the checkbox to the form action already defined
and everything works fine, also with jQuery elements.
The problem unfortunately lies in the textarea, where the text input seems to be limited for no reason.
According to the word counter here:
https://textool.io/character-counter/
I can work only with 220 characters. If I exceed this limit, the mailto: fails.
When I put i.e. one sentence, everything is alright. The problem emerges when I cross some unknown limit of characters. Then the email is not populated.
The full code is here:
https://jsfiddle.net/pq63e4yr/
and the situation depicted here:
I have "discovered" it by using the lorem ipsum text from here:
https://www.lipsum.com/
and now I am trying to find where the problem might be. I saw, that MS Edge has the similar problem
FormData constructor loses textarea value in Edge
but it looks like the Chrome too...
The sample of code (apart from the link above) looks as this:
document.getElementById("cfsubmit").addEventListener("click", function() {
var check = document.getElementById("cfemail");
var formEl = document.forms.cityfibre_form;
var formData = new FormData(formEl);
var jobAddress = formData.get('address');
var jobPostcode = formData.get('postcode');
var surveyorName = formData.get('surveyor');
var feedback = formData.get('feedback');
var subject = jobAddress + ", " + jobPostcode + " - site survey submission from " + surveyorName;
var body = 'SURVEYOR: ' + surveyorName + '\n' +
'ADDRESS: ' + jobAddress + ' ; POSTCODE: ' + jobPostcode + '\n' +
'FEEDBACK: ' + feedback;
var mailTo = "mailto:mk#gmail.com?subject=" + encodeURI(subject) + "&body=" + encodeURI(body);
if (check.checked == true) { // If checked then fire
let link = document.createElement("a");
link.href = mailTo;
link.click();
link.remove();
}
mainForm.submit();
});
<figure class="feedback">
<label class="feedtitle" for="Message">Leave
feedback</label>
<textarea id="opfeedback" name="feedback"></textarea>
<br>
<div class="emailreceipt">
<input type="checkbox" id="cfemail" name="email">
<label class="checking" for="cfemail">Send me an email
receipt of my responses</label>
</div>
</figure>
and I have no idea what's going on here. Is the formData.get attribute limited with characters?
The similar question:
Getting around mailto / href / url character limit
says about the 2083 characters limit, since according to this counter: https://textool.io/character-counter/
I can work only for 220 characters. I use the Chrome browser.
Is there some reason behind it?

jQuery append implementation is breaking

So I have this code that I am trying to alter –
Original:
jQuery(document).ready(function() {
var name = '';
var firstLastName = '[[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.first_name]]]] [[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.last_name]]]]';
var screenname = '[[T6:[[S48:0:screenname]]]]';
if (screenname) {
name = screenname;
} else {
name = firstLastName;
}
var splitName = name.split('');
var nameCheck = splitName[splitName.length-1];
jQuery('#personal_page_header h2').html("Support " + name + "'s Fundraiser" );
});
someone wrote this up and are no longer here, and what I'm trying to do now is figure out how to instead of replace the existing text, add to it.
So right now what this code does is it replaces the h2 content with the constituents registered name, or screenname.
What I'm trying to do now is append to that so that it will say something like
<h2>
Welcome to my fundraiser
<br/>
"Support" + name + "'s Fundraiser"
</h2>
but unfortunately what I tried breaks the code and stops it from working.
what I tried to do is this:
jQuery('#personal_page_header h2').append('<span><br />"Support " + name + "'s Fundraiser"</span>' );
I've tried to do a variety of other things that gave the same unsuccessful result.
Any help would be really appreciated!
Thanks
This should work for you:
jQuery('#personal_page_header h2').append("<span><br/>Support " + name + "'s Fundraiser</span>");
You've just got your quotations a little out of place.
You need to concatenate your code correctly, so if you'd like to keep the " use ' to concatenate. Further you need to escape the ' inside the string with \:
jQuery('#personal_page_header h2')
.append('<span><br />"Support ' + name + '\'s Fundraiser"</span>');

How can I use the output of a JavaScript function as a string inside a HTML textarea box?

I have been creating a profile making program and I would like to use the output of this JS function as a simple string text inside the textarea box which the user can copy using the "Copy to Clipboard" button. Any ideas, please let me know ASAP. Here is my current code:
<!--HTML-->
<!--Button Code-->
<button onclick="copyprofile()">Copy to clipboard</button><br>
<!--Textarea Code-->
<textarea id="text" cols="60" rows="13">I want output of createProfile() to be here</textarea><br>
//Javascript
function createProfile(){
var fn,ln,a,fc,fs,ff,profile;
fn = prompt("Please enter your first name","Enter first name here");
ln = prompt("Please enter your last name","Enter last name here");
a = prompt ("Please enter your age","Enter age here");
fc = prompt("Please enter your favourite colour","Enter favourite color here");
fs = prompt("Please enter your favourite sport","Enter favourite sport here");
ff = prompt("Please enter your favourite food","Enter favourite food here");
profile = ("Name: " + fn + " " + ln + "<br>Age: " + a + "<br>Favourite colour: " + fc + "<br>Favourite sport: " + fs + "<br>Favourite food: " + ff);
return profile;
}
function copyProfile(){
var text = document.getElementById('text');
var range = document.createrange();
range.selectNode(text);
window.getSelection().addRange(range);
document.execCommand(copy);
}
If you have any thoughts or ideas on how to achieve this, please let me know
Being that you have already saved everything in a string assigned to profile, just reference the element you want to update and assign it as the value.
In javascript:
document.getElementById("text").value = profile;
And if you want the to keep the line breaks, you'll need to do something other than <br> as a textarea doesn't typically render HTML. I'd suggest doing a carriage return or line feed. \n
profile = ("Name: " + fn + " " + ln + "\nAge: " + a + "\nFavourite colour: " + fc + "\nFavourite sport: " + fs + "\nFavourite food: " + ff);;
Here is a JSFiddle with an example https://jsfiddle.net/x1w1t8ux/
Update
I took some time to look at the rest of your code as you said it still was not working as you expected. Your copyProfile function has a couple of errors. If you open up your developer console when trying to run these functions, you'll see the error messages:
Uncaught TypeError: document.createrange is not a function
You're line document.createrange() is not a function. You need to camel case it to be document.createRange().
After you fix that error, try to run the code again will display another error in the console:
Uncaught ReferenceError: copy is not defined
In this line document.execCommand(copy); you are referencing a variable called copy. That variable does not exist, nor is it what you're looking for. You are wanting to pass the string copy to the function execCommand. It should look like document.execCommand('copy'); (with quotes, as that's how you identify a string in JavaScript.
In your HTML, when you click on your Copy To Clipboard button <button onclick="copyProfile()">Copy to clipboard</button> it throws an error
Uncaught ReferenceError: copyprofile is not defined
You do not have a function called copyprofile, you have one called copyProfile. Function names are case sensitive. I would recommend sticking to a consistent naming convention (such as camel case)
Lastly, no where in your code are you calling the function createProfile(). So I created it as a second button in my testing.

Display form input in same page

I am working on a simple form demo and i would like the input to display in a below the form. Currently i have it populating in the console. How do i may it display in the div when i click the submit button?
My code:
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$('#firstName').val();
$('#lastName').val();
$('#phoneNumber').val();
$('#address').val();
console.log($('#firstName').val());
console.log($('#lastName').val());
console.log($('#phoneNumber').val());
console.log($('#address').val());
});
});
Well, you're currently not putting the values anywhere but into the console.log.
I would expect to see something like (let's call your div you want the values to go to, "output"):
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
// Borrowing from another response, this is better
// Putting these in variables protects you from
// 1) accidentally modifying your form values
// 2) invalid input, if you add some basic checks, like
// testing to see if the length is > 0, doesn't contain
// bad characters, etc.
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
phone = $('#phoneNumber').val(),
address = $('#address').val();
// get a reference to the div you want to populate
var $out = $("#output");
// This is a better way of dealing with this
// because every call to .append() forces DOM
// reparsing, and if you do this too often, it can cause
// browser slowness. Better to put together one string
// and add it all at once.
$out.html("<p>" + firstName + "</p>" +
"<p>" + $('#lastName').val() + "</p>" +
"<p>" + $('#phoneNumber').val() + "</p>" +
"<p>" + $('#address').val() + "</p>");
});
});
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$(this).after('<div>First name: '+$('#firstName').val()+'<br>'+
'Last name: '+$('#lastName').val()+
' .... ');
});
});
First of all, the four lines where you read the .val() but don't do anything with it are essentially wasted cycles, you probably meant to store them in variables:
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var phoneNumber = $('#phoneNumber').val();
var address = $('#address').val();
To show them in some other element, use the setter version of .val() for input types, or .text() if it's a display type (div, span, etc):
$('#someOtherElement').text(firstName + '\n' +
lastName + '\n'
phoneNumber + '\n'
address);
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
//$('#firstName').val();
//$('#lastName').val();
//$('#phoneNumber').val();
//$('#address').val();
var htmlContent = $('#firstName').val() + '<br />' + $('#lastName').val() + '<br />' + $('#phoneNumber').val() + '<br />' + $('#address').val();
$('#ID_OF_YOUR_DIV_HERE').html(htmlContent);
});
});
Maybe this is what you're after??
You can add it to a div you want with .append(), for example
$("#divYouWantToAddTo").append($('#firstName'));
I don't know where to start... What is all that $('#....').val() in the middle there, wasting time only to throw away the result..?
What is wrong with document.getElementById('...').value instead of wasting time creating an entire jQuery object just to access something trivial?
Adding text to a node is as simple as container.appendChild(document.createTextNode(sometext)); - and if you want to have newlines between them you can also do container.appendChild(document.createElement('br'));.
There is no need for jQuery here at all...

term_exists not working in Javascript

I finally got my back-end to create the wheel codes from the checked taxonomies in the add custom post admin area.
Now, I want to add that tire code to the wheel_type taxonomy.
The below code ran great, until I added the if statement under //Add code to Taxonomy
Now nothing is working, but I get nothing in the error console.
I figure it must be a stupid syntax mistake - can anyone help me out?
Or am I missing something else?
jQuery('#replace').click(function(){
//get tire code and name
var code = jQuery('input[name="tire_code"]').val();
var name = jQuery('input[name="tire_name"]').val();
var bname = jQuery('input[name="tire_bname"]').val();
alert(code + " + " + name + " + " + bname);
//get tire brand
var tirebran = jQuery('#tire_brandchecklist').find(":checked").parent('label').text();
tirebran = jQuery.trim( tirebran );
//Add code to Taxonomy
if( term_exists( code, wheel_type ){
continue;
}
else
{
wp_insert_term( code, wheel_type );
}
//update title
var title = code + ' : ' + name + ' tires';
if(tirebran!=''){
title += ' with ' + bname + ' letters';
}
jQuery('input[name="post_title"]').focus().val(title);
});
//-->
</script>
unless i've misunderstood your question, you're trying to call wordpress methods via javascript.
term_exists() and wp_insert_term() are PHP methods within the wordpress code, not accessible directly via Javascript (unless you have written interfaces to them).
continue doesn't make any sense there; just check for !term_exists... and call wp_insert_term when it doesn't exist.
if (!term_exists(code, wheel_type)) {
wp_insert_term(code, wheel_type);
}
The continue statement is for continuing loops from the top of the loop; it does not stand on its own.

Categories