Get element via jQuery quickly - javascript

I want to fetch the radio input element object.
In this approach, if the page is huge with many radio inputs, then it will take time to iterate over them before returning the object.
Is there a faster approach to get input object other than this? The condition is that the value should start with text '9Z'.
<html lang="en">
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>
<td>
<input type="radio" value="9Z>2">
</td>
</div>
<script>
var r = $("input:radio[value^='9Z']");
alert(r.length); //I got the object - length will be greater than 0
</script>
</body>
</html>

:radio is a jquery specific selector, therefore by using it, you're not allowing jquery to use the quicker document.querySelectorAll() method. Simply replace it with the attribute equals selector.
$("input[type=radio][value^='9Z']")
If that still isn't fast enough, we'll need to know more about the structure of your page.
You could also do this for a very small increase (no IE7 support):
$(document.querySelector("input[type=radio][value^='9Z']"))

Related

Properly declaring a variable

I don't know how to declare a variable here in javascript. I have an example situation that if the paragraph is equals to a, the alert will popup.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="sample">a</p>
</body>
</html>
<script type="text/javascript">
var sample = getElementById('sample');
if (sample == "a") {
alert("Correct")
};
</script>
You're declaring your variable just fine, however if you want the text within the element, you also need to use the innerHTML property. And when you use the getElementById method, you need to use it on the document object like document.getElementById:
var sample = document.getElementById('sample');
if (sample.innerHTML == "a") {
alert("Correct")
};
<p id="sample">a</p>
sample is a variable and you are correct but it is storing a reference to a DOM Element with id sample. To get the inner html of that you need
var sample = getElementById('sample').innerHTML;
Also, use === over == for no casting etc. Refer here
I will recommend you to have a quick look at JS from w3schools and then move to MDN. Nobody will report you here if you show your efforts, so relax :).
Your declaration is fine, but the assignment part is missing document as the object which has the .getElementById method. Then, once you have the reference to the element, you then need to access its content with .textContent (you can't compare the entire element to a value that the element might contain). As a side note on this, when the string you wish to set/get doesn't contain any HTML, you should use .textContent so that the browser doesn't parse the string for HTML unnecessarily. Often, people will suggest that the content of an element should be gotten/set using .innerHTML and, while that will work, it's wasteful if the string doesn't contain any HTML.
Also, the <script> must be located within the head or the body, not outside of them. I would suggest placing it just prior to the closing body tag so that by the time the processing reaches the script, all of the HTML elements have been parsed into memory and are available.
Lastly (and this is really just a side point), an HTML page also needs the title element to have something in it, otherwise it won't be valid. While browsers don't actually do HTML validation, it's important to strive for valid HTML so that you can be sure that your pages will work consistently across all devices. You can validate your HTML at: http://validator.w3.org.
<!DOCTYPE html>
<html>
<head>
<title>Something Here</title>
</head>
<body>
<p id="sample">a</p>
<script type="text/javascript">
var sample = document.getElementById('sample');
if (sample.textContent == "a") {
alert("Correct")
};
</script>
</body>
</html>

JavaScript Calculator using HTML forms

I want to create a calculator that, using JavaScript, takes a number from an HTML input box like this one.
// Take form input and multiply by four
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input placeholder="Side Length of Square"/>
</body>
</html>
How could I then relay the user input, say 5, so that the JavaScript would take "5" and multiply it to find the area of the square? This is my first question ever on Stack Overflow, so I apologize if I did something wrong. Thanks for the help!
You would use javascript's onkeyup to calculate the area of a square as the user types in numbers. Check out the code below!
function calc(){
var val=document.getElementById("myInput").value;
document.getElementById("area").innerHTML=Math.pow(val, 2);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="myInput" placeholder="Side Length of Square"onkeyup="calc()"/>
<p>Area : <span id="area"></span></p>
</body>
</html>
First, you need to decide where you want to place your output, e.g. introduce a new <div> element whose text content will hold the computed side length.
Also, you should give your <input> as well as your output <div> a unique id attribute so you can identify it later on from within your JavaScript code.
Then, you would introduce a new <script> before the closing </body> tag. This guarantees that at the time of script execution, all relevant HTML elements have already been loaded and added to the Document Object Model (DOM) so that your script can access them.
Finally, you write a JavaScript "input" event handler and attach it to the <input> element.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="side-length" placeholder="Side Length of Square">
<div id="area"></div>
<script>
let input = document.getElementById("side-length");
let output = document.getElementById("area");
input.addEventListener("input", function(event) {
let sideLength = input.valueAsNumber;
output.textContent = sideLength * sideLength;
});
</script>
</body>
</html>
Note: Above event handler computes the area of the square with given side length, as per your question and opposed to the comment above your code snippet.

Validate HTML5 field input without <FORM> and other server-side code

Been fiddling around with jQuery and HTML5, but I am stuck on a simple simple action.
JSFiddle here: http://tinyurl.com/oqmkyhr
I have a field input where I input a number, and when I press a button, the inputted number is rounded to 2 decimal places. The catch is, you cannot use or server side code AND it is all within 1 html document.
This is what I have:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Scotiabank Currency Converter</title>
<meta name="description" content="Converts currencies with Yahoo! Finance API">
<meta name="author" content="Kangze Huang">
<link rel="stylesheet" href="#">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<input type='number' id='Amount' value='Amount convert' step='0.01'>
<input type='button' id='Validate' value='Check decimals'>
<h1></h1>
<script>
jQuery(document).ready(function($) {
$('#validate').click(function(){
$('Amount').value = parseFloat(value).toFixed(2);
$('h2').text(value);
});
});
</script>
</body>
When I press the Validate button, it turns into NaN (On Chrome & other web-browsers)! On JSFiddle it does nothing.
What am I doing wrong? Perhaps syntax or something I'm missing?
It is because you have $('Amount').value. You are missing the '#' and the parenthesis and referencing the value wrong. But you have the right idea. What you can try is:
$('#validate').click(function(){
var amount = $('#Amount').value();
$('h1').text(parseFloat(value).toFixed(2));
});
});
Your selector should be $("#Amount"). You are missing the #.
Also, if you are trying to ASSIGN the value, you should be using:
$("#Amount").val( parseFloat(value).toFixed(2) );
I am not sure where you are getting your 'value' variable from, I don't see it getting assigned anywhere.
i see many syntax and other mistakes in your code, use the below code:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Scotiabank Currency Converter</title>
<meta name="description" content="Converts currencies with Yahoo! Finance API">
<meta name="author" content="Kangze Huang">
<link rel="stylesheet" href="#">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<input type='number' id='Amount' value='Amount convert' step='0.01'>
<input type='button' id='Validate' value='Check decimals'>
<h1></h1>
<script>
jQuery(document).ready(function($) {
$('#validate').click(function(){
$('#Amount').val(parseFloat(value).toFixed(2)); //you missed # in this, normally in jquery we use .val() method to set the value of the input types
$('h1').html(parseFloat(value).toFixed(2)); // in the above code you have used h1 so here also use h1
});
});
</script>
</body>
$('#validate').click(function(){
1^
$('Amount').value = parseFloat(value).toFixed(2);
2^ 3^ 4^
$('h2').text(value);
5^
validate is not Validate
Amount will match <Amount> elements which don't exist. ID selectors begin with a #
jQuery objects don't have value properties. DOM nodes (if they are form controls) do. You are probably looking for val()
value is an undefined variable. You need to define it before you use it. You probably want $('Amount').val() instead of using value at all.
You have no elements that match this selector, and heading elements should be used for headings.
So what you are probably looking for is:
$('#Validate').click(function() {
var value = $('#Amount').val();
value = parseFloat(value).toFixed(2);
console.log(value);
$('output').val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' id='Amount' value='Amount convert' step='0.01'>
<input type='button' id='Validate' value='Check decimals'>
<output></output>
If you want to select something by id in jquery, you need to use a # sign. In your case $('#Amount'); Also, there are no h2 elements on your page, so $('h2').text(value); won't do anything. Additionally, if you want to get the value of an input in jquery, you use the .val() functions, and not .value.
Fixed fiddle: http://jsfiddle.net/9kqbue5t/2/

Should element name or id be used to access form elements?

I'm using the jQuery validator plugin http://jqueryvalidation.org/.
I have found that I can access elements in the form using either their ID or their name (at least with Firefox and Chrome). Is one way more correct and browser compatible than the other? Or maybe I should do something else altogether?
http://jsbin.com/daxaju/2/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#myForm").validate({
submitHandler: function(form) {
console.log('using id',form.myElementID.value);
console.log('using name',form.myElementName.value);
}
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="myElementName" id="myElementID" />
<input type="submit" />
</form>
</body>
</html>
Since on an input a name is somehow required (I don't know what the documentation says about this, but if you want to retrieve it later, for example in PHP, you should put a name attribute on it), I think that referencing your element by its name it safer.
As you can see here : http://www.javascript-coder.com/javascript-form/javascript-get-all-form-objects.phtml , native API use the name to reference a form element.
The best way is to put both id and name, id for jquery and name for php.
For browser compatible, id/name all works fine.
Selecting an element by it's Id is the fastest. Id is(should be) unique on the document. It works on all the browsers.

Getting the height of a <DIV> - returns 'undefined'

I have a problem getting the height of a (the one in the code below, with class="post_div"). And I want to return with a document.write whitin the HTML body - maybe later using it as height for other elements, that I want to be equal. I have tried every possible code for getting the height of such an element, but every time it returns 'undefined'. I have also tried setting height=auto for the DIV. I am almost sure my problem not has to do with the way I get the height, but have no other idea for what else it could be! Therefore I have choosen to bother you with the full structure of my coding. The JavaScript is placed in a separate document containing only the following statement:
var result=document.getElementById('postHeight').offsetHeight;
My HTML document looks like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<head>
<title>...</title>
<link rel="stylesheet" type="text/css" media="all" href="C:\Users\Lasse\Desktop\hg2\hg2.css" />
<script src="C:\Users\Lasse\Desktop\hg2\hg2.js"></script>
</head>
<body>
<script>document.write(result)</script>
<div id="postHeight" class="post_div">
...
</div>
</body>
</html>
Hope you can help! Thanks!
There is no element with the ID postHeight. Perhaps you meant
var result=document.getElementById('content').offsetHeight;
Additionally, this calculation must be done after the element you are calculating has been loaded (so either by putting the <script> after the element, or deferring execution with onload or similar).
Since your script tag occurs before the element exists in the DOM, you can't get the height. You could put an event handler waiting for the document to load before getting the height or move that script to the bottom of the page, but your document.write would still be called before the element existed. You need to rethink your design.
Sample code:
<div id=getme>
some text to give it height.
</div>
<script>
document.write(document.getElementById("getme").clientHeight);
</script>

Categories

Resources