I am trying to send the value of a radio button to a javascript function. Eventually the function will do more but my testing it has come to a dead end because I keep getting a returned value of undefined. Here is what I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<SCRIPT TYPE="text/javascript">
<!--
function jobWindow(){
var target;
for( i = 0; i < document.jobView.sales.length; i++ ){
if( document.jobView.sales[i].checked == true )
target = document.jobView.sales[i].value;
break;
}
alert( "val = " + target );
//var load = window.open('target','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
}
// -->
</script>
</head>
<body>
<form name="jobView">
<input name ="sales" value="all" type="radio" />All
<input name="sales" value="darell" type="radio" />Darell
<input name="sales" value="kevin" type="radio" />Kevin
<input name="sales" value="brad" type="radio" />Brad
<input name="sales" value="chongo" type="radio" />Chongo
<input type="button" value="View Records" onclick="jobWindow()"/>
<input type="button" value="View Calendar" />
</form>
</body>
</html>
The access path you actually want is:
var el = document.forms["jobView"].elements["sales"];
The straight dot chain (document.jobView.sales) makes an implicit call to the "all" collection, which will only work in IE. (Yes, I know that Firefox returns an identical-looking string in its error console when things go wrong, but you can't actually use it in your own code.) getELementsByTagName() and getElementsByName() will work just fine, but then you need to ensure that the elements in the returned collection are the ones you actually want. (Assume that a time will come when you want to create more than one form on the page, and that field names will collide. It will never happen, of course, unless you fail to make that assumption out of the gate, whereupon another developer will immediately add a second form to the page you just committed.)
Try with document.getElementsByTagName like this:
function jobWindow(){
var myvalue;
var el = document.getElementsByTagName('input');
for( i = 0; i < el.length; i++ ){
if (document.forms['jobView'].el[i].type === 'radio' && document.forms['jobView'].el[i].name === 'sales')
{
if(document.forms['jobView'].el[i].checked == true )
{
myvalue = document.forms['jobView'].el[i].value;
break;
}
}
}
alert( "val = " + myvalue );
}
Note also that your break line never executed because you were missing curly brackets:
if( document.jobView.sales[i].checked == true )
{
target = document.jobView.sales[i].value;
break;
}
change document.jobView.sales to document.getElementsByName('sales')
throw some debugging in there. for example put an alert() inside the for() statement to make sure it is getting a definition for document.jobView.sales.length.
If it doesn't make the alert, you can almost bet document.jobView.sales.length is undefined.
You can then do try { var length = document.jobView.sales.length; } catch(e) { alert(e); } to verify this.
If you verify that document.jobView.sales.length isn't being defined, you may have to use document.getElementsByTagName, and loop through them instead of document.jobView
Related
i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
I am trying to set the length of an accepted input in the input box by using radio buttons. However every time I try to do this I get 'Uncaught TypeError: Cannot read property 'checked' of null'. After searching I have realised this is because JavaScript elements are loading before the whole HTML code can run. Though I cannot not find any code that is able to load the whole page then run the JavaScript that works for me.
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
<script src= 'card.js'></script>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<button type = 'button' id = 'confirm' onclick = 'proceed()'> Click to proceed </button>
</body>
</html>
I have tried windows.onload but it hasn't worked for me. It is highly likely I wasn't using it right.
var cardLength = 0;
if (document.getElementById('visa').checked || document.getElementById('mastercard').checked) {
cardLength = 16;
} else if (document.getElementById('americanexpress').checked) {
cardLength = 15;
}
function proceed() {
var check = document.getElementById('proceed').value;
if (check == cardLength) {
alert('Proceed')
} else {
alert('Card length invalid')
}
}
You are trying to get element by id 'visa', 'mastercard' and 'americanexpress', but there isn't elements with this id's.
Add id's to your input fields like in the code below.
Also try to include js files at the end of <body> tag.
HTML
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa' id='visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard' id='mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress' id='americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<script src= 'card.js'></script>
</body>
</html>
You have multiple issues affecting this.
1) You are correct in that the JS is being loaded before the rest of the HTML. You mentioned that you attempted to use window.onload? Can you please specify how? The following code works:
window.onload = function() {
alert(document.querySelector('[name="card"]:checked').value)
}
Otherwise, I would highly recommend placing your script tag at the bottom of the html, just before the closing </body> tag instead. This has a couple benefits: It loads as you had intended, and it doesn't block the HTML, so to the user, depending on the size of you final script, it loads slightly faster.
2) As lanokvova said, you have no elements with the id of 'visa', 'mastercard', or 'americanexpress'. You can add the ids, or you can use document.querySelector('[name="card"]:checked'), as seen above.
3) You're only running this once on startup. If the user selects a different card, it's not going to update. I would recommend using jQuery for this, as it's significantly cleaner, but it can be done in vanilla JS like so:
document.querySelectorAll('[name="card"]').forEach(function(a) {
a.addEventListener('change', function() {
var selected = this.value;
if(selected === 'visa' || selected === 'mastercard') {
cardLength = 16;
} else if(selected === 'americanexpress') {
cardLength = 15;
}
});
});
A working demo can be found on this Fiddle. You'll just need to update your script to the JS block, and move the tag to the end of the HTML.
Btw, you don't need to close <input> tags, and that <h2> should go inside the body, not the head.
In the following program, for some reason, the for loop runs through once, and then does not repeat. I believe the error is with the bold code. Help is very much appreciated. This is a program used to change a text box to caps, title case, etc. Title case being the first letter of each word capitalized. Thank you.
<html>
<head>
<script type="text/javascript">
function titlize(){
tLength=tBox.box.value.length
character=new Array()
for(i=1; i<tLength+1; i++){
**character[i]=tBox.box.value.slice(i-1,i)**
document.write(character[i])
if(i==1){
character[i]=character[i].toUpperCase()
}else if(character[i-1]==" "){
character[i]=character[i].toUpperCase()
}else{
character[i]=character[i].toLowerCase()
}
document.write(i)
document.write(character[i])
}
}
function upperC (){
toUpperCase(tBox.box.value)
}
function verify (){
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
if(tBox.lowercase.checked){
tBox.box.value=tBox.box.value.toLowerCase()
}
if(tBox.titlecase.checked){
titlize()
}
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
}
</script>
</head>
<body>
<form name="tBox">
<input type="text" name="box" value=""><br>
<input type="checkbox" name="uppercase" onClick=verify(this.form)>Uppercase<br>
<input type="checkbox" name="lowercase" onClick=verify(this.form)>Lowercase<br>
<input type="checkbox" name="titlecase" onClick=verify(this.form)>Titlecase<br>
</form>
</body>
</html>
tBox is your form not your textbox, so trying to get it's value and then the length of that value is not valid. The code needs to access your textbox, so it should be:
// Scan for the first textbox. Give that textbox a unique id to be
// able to write a more specific query.
tLength= document.querySelector("input[type='text']").value.length;
character=new Array()
// Not sure why you were writing: i < tLength +1 as that will
// cause your loop to go one character too far. Remember,
// arrays start from 0 and length starts from 1.
for(i=1; i < tLength; i++){
Lastly, avoid document.write() because if you use it on a document that has finished being parsed, it will cause the entire existing document to be thrown out.
Based on the code above. You have document.write statements in your function, which is causing issues in overwriting your DOM. I've removed those, and that will allow it to function normally. Also, I added tBox.box.value = character.join("") to put the text back into the text box.
https://plnkr.co/edit/qOPIxwH16hJUlj0RFBhv?p=preview
function titlize() {
tLength=tBox.box.value.length;
character=new Array();
for(i=1; i < tLength + 1; i++){
console.log('print')
character[i]= tBox.box.value.slice(i - 1,i)
//document.write(character[i])
if(i==1) {
character[i]=character[i].toUpperCase()
} else if(character[i-1]==" ") {
character[i] = character[i].toUpperCase()
} else {
character[i]=character[i].toLowerCase()
}
console.log(i)
console.log(character[i])
}
tBox.box.value = character.join("")
}
I got two hidden input HTML that I want to compare with javascript onclick submit button. But it won't work even though it seems simple and straightforward.
The function is:
function check() {
if ((parseFloat(document.getElementById("price_sell").value) < (parseFloat(document.getElementById("price").value)*0.95)) OR (parseFloat(document.getElementById("price_sell").value) > (parseFloat(document.getElementById("price").value)*1.05)) ){
alert("too high/low!");
}
}
And the input text is as follow:
<input type="hidden" id="price" name="price" value="<?php echo $prc ?>" />
<input type="hidden" id="price_sell" name="price_sell" />
I have check the hidden input value and even though the 'price_sell' is twice as big/small as the 'price', the alert won't fire. What is wrong with it?
Change the operator OR to ||.
This code, if was JS code, doesn't work because syntax error.
First as #Rakesh_Kumar mentioned set value to price_sell input field and try below code.
function check() {
var price_sell = parseFloat(document.getElementById("price_sell").value);
var price = parseFloat(document.getElementById("price").value);
if ( (price_sell < ( price *0.95 ) ) || (price_sell > (price*1.05) ) ) {
alert("too high/low!");
}
}
Storing the price_sell and price value in JS variables for better reading purpose . FYI there were some syntax error due missing brackets and usage of OR which i have replaced with ||.
You must change the OR by || and add a value to price_sell
Test with this example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="estilos/estilos.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Test</title>
<script type="text/javascript">
function check() {
var price_sell = parseFloat(document.getElementById("price_sell").value);
var price = parseFloat(document.getElementById("price").value);
if ((price_sell < (price * 0.95)) || (price_sell > (price * 1.05))) {
alert("too high/low!");
}
}
</script>
</head>
<body>
<input type="hidden" id="price" name="price" value="2" />
<input type="hidden" id="price_sell" name="price_sell" value="4"/>
<input type="button"
onclick="check()"
value="Check">
</body>
</html>
Use Number(variable) to convert text to number and then do your comparing maths.
Example:-
var price = Number(document.getElementById(price).value);
var price_sell = Number(document.getElementById(price_sell).value);
var compare = price_sell - price;
Or you can check the variable type, using typeof
If value is null or undefined then Number function will convert it to 0 (zero).
Even though the 'price_sell' is twice as big/small as the 'price'-
Updated Answer 2:
/*
Errors - price = '10 $'; means remove currency symbols
or characters from price_sell and price variable
Use trim() to remove whitespace.
I recheck my code, and found brackets missing, and posted again.
*/
price_sell = Number(price_sell.trim());
price = Number(price.trim());
if ((price_sell > (price/0.80)) && (price_sell < (price*1.30))) {
// good
} else {
// bad
}
Regards
i m trying to get a list of outputs which doesn't divide evenly by number which are smaller than the input value.For example if the input value is 10,the list should be 10,9,8,7,6,4,3,1. below is my code and doesn't give me any output nor any error message.I m new to javascript and i need to know what i m doing wrong.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>An example of using "for" and "while" in PHP</title>
<script type="text/javascript">
function displayResult()
{
if(text_form.numberfield.value){
var number=document.getElementsByName("numberfield").value;
var div=document.getElementsByName("numberfield").value;
while (div>0)
{
if(number%div==0 && div!=number && div!=1)
{
div--;
continue;
}
if (div == 0)
{
break;
}
document.write(div--);
document.write(",");
}
}
else
{
document.write("Enter a number");
}
}
</script>
</head>
<body>
<H1>An example of using "for" and "while" in PHP</H1>
<form name="text_form">
Please input a number: <input type="text" name="numberfield"> </label>
<input type="submit" value="Submit" onclick="displayResult()" />
</form>
<p> Result is shown as below.</p>
</body>
</HTML>
getElementsByName returns an array, not an element.
Try:
var number=document.getElementsByName("numberfield")[0].value;
var div=document.getElementsByName("numberfield")[0].value;
Notice the [0]. You also have to modify a bit to make it work.
DEMO
the getElementsByName returns a list of elements having the specified name not a single element. You can access each element using loop:
var elems=document.getElementsByName("name")
for(var i=0;i<elems.length;i++){
var elem=elems[i]
//access each element using iterator
}
Also the getElementsByTagName returns a list of elements having the specified tag name.