javascript radio button value get null - javascript

In the javascript, I have the pointer to get the name of the fruit. But the alert always shows null.
I checked my logic but unable to find the problem. Any suggestions? thanks!
<!DOCTYPE html>
<html>
<head>
<title>My Fruit</title>
<script type="text/javascript">
function checkFruit(){
var fruit_radio_pointers = document.querySelector('[name="fruit"]');
var which_fruit = null;
for(var i=0; i<fruit_radio_pointers.length; i++){
if(fruit_radio_pointers[i].checked){
which_fruit = fruit_radio_pointers[i].value;
break;
}
}
alert(which_fruit);
}
//document.getElementById("my_btn").addEventListener("click", checkFruit, false);
</script>
</head>
<body>
<p>
<input name="fruit" type="radio" value="apple" /> Apple<br />
<input name="fruit" type="radio" value="cherry" /> Cherry
</p>
<p>
<button id="my_btn" onclick="checkFruit()" >Which Fruit?</button>
</p>
</body>
</html>

Use querySelectorAll:
var fruit_radio_pointers = document.querySelectorAll('[name="fruit"]');
querySelector only returns the first found match (not as an array).
It is equal to document.querySelectorAll('[name="fruit"]')[0].
As you may have figured out, querySelectorAll returns all of the found matches as an array.
Example

Related

Why the button object can not use the onclick() function?

I am trying to use javascript to create a web calculator. I hope that users can calculate the result when they click the different buttons. However, there is an error in line16(Uncaught TypeError: Cannot read property 'onclick' of null). I hope someone could help me. These are my codes:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
var btnadd,btnsub,btnmul,btndiv;
btnadd = document.getElementById('btnadd');
btnsub = document.getElementById('btnsub');
btnmul = document.getElementById('btnmul');
btndiv = document.getElementById('btndiv');
btnadd.onclick() = function(){
cal(add());
}
function cal(func){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
parseFloat(num1);
parseFloat(num2);
var result;
result = func(num1,num2);
document.getElementById('result').value = result;
}
function add(num1,num2){
return (num1+num2);
}
function sub(num1,num2){
return (num1-num2);
}
function mul(num1,num2){
return (num1*num2);
}
function div(num1,num2){
return (num1/num2);
}
</script>
</head>
<body>
<form>
num1:<input type="text" id="num1" /><br>
num2:<input type="text" id="num2" /><br>
<input type="button" id="btnadd" value="add" />
<input type="button" id="btnsub" value="sub" />
<input type="button" id="btnmul" value="mul" />
<input type="button" id="btndiv" value="div" /><br>
result:<input type="text" id="result"/>
</form>
</body>
</html>
You need to either add the defer attribute to your script or put it at the end of the body.
Putting JS code in the head means that it will be run before the page is fully parsed. That means that there is no element with the id of btnadd just yet. If you add the defer attribute, then it will wait for the page to be parsed before running the script. Putting at the end of the body has the same effect.
In terms of your code itself, you need to set the onclick property. You cannot assign a function like that. Also, do val2 = parseFloat(val2) rather than parseFloat(val2). (similarly for val1) because here you need to reassign the value
Because you didn't define the onclick correctly
Instead of
btnadd.onclick() = function(){
cal(add());
}
try
btnadd.onclick = function(){
cal(add);
}
Check this codepen : https://codepen.io/zecka/pen/NWrejxO
Note that there are other errors in your code that will prevent you from making it work as you want.

Change the first and second text input value when they don't have an ID

I know how to change the text input value with javascript if they have IDs, but what if they don't have IDs? I need to find and change the value of the first, and second text input on the page. How would I do that?
<input type="text" id="text" value="no value">
<button onclick="myFunction()">Change Values</button>
function myFunction() {
document.getElementById("text").value = "Text is now changed";
}
I need to know how to change the first and second input text's value on the page if they don't have an ID. For example, change "no value 1" to "yes value 1", and "no value 2" to "yes value 2". How would I do that?
<input type="text" value="no value 1">
<input type="text" value="no value 2">
If i understand your question correctly, using document.getElementsByTagName is one answer.
const inputElements = document.getElementsByTagName('input');
inputElements[0].value = "insert input 1";
inputElements[1].value = "insert input 2";
check this jsfiddle (https://jsfiddle.net/hentleman/09tr7bku/1/)
Old school, but still works:
function changeEm() {
document.forms[0][0].value = "yes value 1";
document.forms[0][1].value = "yes value 2";
}
<body onload=changeEm()>
<form>
<input type="text" value="no value 1">
<input type="text" value="no value 2">
</form>
</body>
There are many document elements query methods, one of them is document.getElementsByTagName.
This method returns an HTMLCollection, which is an iterable of HTML objects.
Having this knowledge, let's say you have the following HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Get Inputs</title>
</head>
<body>
<input type="text" value="First" />
<input type="text" value="Second" />
</body>
</html>
You could get all the input elements in your HTML using document's getElementsByTagName as follows:
const inputEls = document.getElementsByTagName("input");
inputEls will contain a HTMLCollection of HTMLInputElement, now we are able to iterate the collection and do something with it.
The final JavaScript must look like the following:
const inputEls = document.getElementsByTagName("input");
for (let input of inputEls) {
// Here you are able to access every input element of te collection
// And consume HTMLInputElement object
console.log(input.value);
}

Input length is undifined

< Why Input Length Is Undifined
Js
function calc() {
var inp = document.getElementById("inp");
var result = document.getElementById("result");
var inpval = inp.value
result.innerHTML = inpval;
alert(inp.length);
}
Html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input id="inp" class="inp" Type="number"/>
<center>
<div id="calc" class="calc" onclick="calc()">Calculate</div>
<br />
<br />
<p id="result"></p>
</center>
</body>
</html>
Please help me with this code I don't know why I am getting this error whenever I click on function it always shows undifined
getElementbyId returns Element and the Element has no length property. This is the reason why that output is undefined. So if you want to get the length of the value of the input element, you have to access input element with value property like inp.value or inpval.
After then, you can get the length of that like inp.value.length or inpval.length.

generate textboxes based on number enter by user

I want when a user enter number in the textbox and click set, textboxes appear based on the number he entered and this what I come up with but it is not working please help
<html>
<head>
<script>
function generate(){
var a=parseInt(document.getElementById("nochapter").value);
for (i=0;i<=a,i++){
document.getElementById("ch").innerHTML="<input type='text' >"}}
</script>
</head>
<body>
<h1> Prepare new assessment</h1>
<form>
No. of Chapter included <input type="text" id="nochapter" >
<input type ="button" value="set" onclick="generate()">
<div id="ch"></div>
Your code should be like this.
Is better append an input element to the div.
<head>
<script>
function generate() {
var a = parseInt(document.getElementById("nochapter").value);
var ch = document.getElementById("ch");
for (i = 0; i < a; i++) {
var input = document.createElement("input");
ch.appendChild(input);
}
}
</script>
</head>
<body>
<h1> Prepare new assessment</h1>
<form>
No. of Chapter included
<input type="text" id="nochapter" />
<input type="button" value="set" onclick="generate()" />
<div id="ch"></div>
</form>
</body>
There is small glitch in your written code
for (i=0;i<=a,i++) --> for (i=0;i<=a;i++)
even if you change that it will generate only one text box because you are replacing innerHTML for every iteration. so prepare the string separately based on no of iteration and assign it to innerrHTML. it should work.

How to get all elements which name starts with some string?

I have an HTML page. I would like to extract all elements whose name starts with "q1_".
How can I achieve this in JavaScript?
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('q1_') == 0) {
eles.push(inputs[i]);
}
}
HTML DOM querySelectorAll() method seems apt here.
W3School Link given here
Syntax (As given in W3School)
document.querySelectorAll(CSS selectors)
So the answer.
document.querySelectorAll("[name^=q1_]")
Fiddle
Edit:
Considering FLX's suggestion adding link to MDN here
You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input name="q1_a" type="text" value="1A"/>
<input name="q1_b" type="text" value="1B"/>
<input name="q1_c" type="text" value="1C"/>
<input name="q2_d" type="text" value="2D"/>
<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for (x = 0 ; x < inputs.length ; x++){
myname = inputs[x].getAttribute("name");
if(myname.indexOf("q1_")==0){
alert(myname);
// do more stuff here
}
}
</script>
</body>
</html>
Demo
Using pure java-script, here is a working code example
<input type="checkbox" name="fruit1" checked/>
<input type="checkbox" name="fruit2" checked />
<input type="checkbox" name="fruit3" checked />
<input type="checkbox" name="other1" checked />
<input type="checkbox" name="other2" checked />
<br>
<input type="button" name="check" value="count checked checkboxes name starts with fruit*" onClick="checkboxes();" />
<script>
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true &&
inputElems[i].name.indexOf('fruit') == 0)
{
count++;
}
}
alert(count);
}
</script>
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.

Categories

Resources