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

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.

Related

add and remove boxes using javascript

I have two text boxes and two buttons named add and remove. The requirement is to add more boxes along with the current boxes. i somehow managed to add boxes but the requirement of removing the boxes is not working. Please help to why this code is not working and if possible suggest a working solution.
function addFunction(){
var element = document.createElement("input");
var parent = document.getElementById("form1");
parent.appendChild(element);
}
function removeFunction(){
var child = document.getElementsByTagName("input");
var parent = document.getElementById("form1");
for (var i = 0; i > child.length; i++) {
parent.removeChild(child[i]);
};
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form1" style="margin-left: 40%; margin-top: 100px;">
<input type="text" id="one"><br><br><br>
<input type="text" id="two"><br>
<p id ="demo"> </p>
</form>
<button style="margin-left: 40%;" type="button" value="ADD" id="addButton" onclick="addFunction()">ADD</button>
<button style="margin-left:50px;" type="button" value="REMOVE" id="removeButton" onclick="removeFunction()">REMOVE</button>
</body>
</html>
for (var i = 0; i < child.length; i++) {
parent.removeChild(child[i]);
};
You have got wrong condition in your for loop. Your i is always 0 at start, and is lesser then length of array with node elements, so loop just can't start.
P.s. and you don't need var i before it
Your for-Loop is wrong:
for (var i = 0; i > child.length; i++) {
parent.removeChild(child[i]);
};
You need to change ">" to "<"
Replace your > condition in the for loop with <. You want the for loop to be executed until it reach child.length.

Show selected checkbox values using javascript

I have been trying to create checkboxes and show their values.
When you try to select only one of them, it works.
When you try to select more than one, it only shows the highest value selected.
I want to do this only with javascript, no jquery.
How can I show all the values of all selected checkboxes?
Here is the code so far:
Html:
<!doctype html>
<html>
<head>
<title>Javascript checkboxes in real time</title>
<link rel = "stylesheet" href = "css/default.css">
</head>
<body>
<form action = "" method = "post">
<input type="checkbox" id = "1" value = "1">1<br>
<input type="checkbox" id = "2" value = "2">2<br>
<input type="checkbox" id = "3" value = "3">3<br>
<input type="checkbox" id = "4" value = "4">4<br>
<input type="checkbox" id = "5" value = "5">5<br>
</form>
<section></section>
<script src = "js/default.js"></script>
</body>
</html>
Javascript:
var checkbox = document.getElementsByTagName('input');
var section = document.getElementsByTagName('section');
setInterval(function(){
for(var i = 0; i <= checkbox.length - 1; i++){
if(checkbox[i].checked){
section[0].innerHTML = checkbox[i].value;
break;
}
else{
section[0].innerHTML = null;
}
}
}, 10);
There are several things wrong about your code, you are endlessly querying the DOM every 10ms for no good reason. DOM elements fire events when things happen to them.
var section = document.getElementsByTagName('section')[0];
var inputs = document.getElementsByTagName('input');
// Document was changed!
document.addEventListener('change', function(event) {
// Specifically, an input was changed in the document!
if (event.target.tagName === 'INPUT') {
// Update the section
updateCheckboxStatus(section);
}
});
// This function updates an element with the input status
function updateCheckboxStatus(element) {
// Clear the element first
element.textContent = '';
// Loop through each of the inputs
[].forEach.call(inputs, function(input) {
// If checked, add to the element
if (input.checked) { element.textContent += input.value + " "; }
});
}
<form action="" method="post">
<input type="checkbox" id="1" value="1">1
<br>
<input type="checkbox" id="2" value="2">2
<br>
<input type="checkbox" id="3" value="3">3
<br>
<input type="checkbox" id="4" value="4">4
<br>
<input type="checkbox" id="5" value="5">5
<br>
</form>
<section></section>
EDIT: I'm posting the minimal change I found to fix your issue. This is by no means the right approach to the task at hand - as explained perfectly at the (now) accepted answer. This code should serve just so you'll see the diff from your code.
Also - please don't use setInterval (use setTimeout instead and renew it each time from inside the callback):
var checkbox = document.getElementsByTagName('input');
var section = document.getElementsByTagName('section');
setInterval(function(){
section[0].innerHTML = '';
for(var i = 0; i < checkbox.length; i++){
if(checkbox[i].checked){
section[0].innerHTML += checkbox[i].value;
}
}
}, 10);

javascript radio button value get null

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

How to know which radio is checked from a fieldset

I have the following code:
<fieldset id="dificuldade">
<legend>Dificuldade:</legend>
<input type="radio" name="dificuldade" value="facil"> Fácil </input>
<input type="radio" name="dificuldade" value="medio"> Médio </input>
<input type="radio" name="dificuldade" value="dificil"> Difícil </input>
</fieldset>
<fieldset id="tipo">
<legend>Tipo de jogo:</legend>
<input type="radio" name="Tipodejogo" value="somar"> Somar </input>
<input type="radio" name="Tipodejogo" value="subtrair"> Subtrair </input>
<input type="radio" name="Tipodejogo" value="dividir"> Dividir </input>
<input type="radio" name="Tipodejogo" value="multiplicar"> Multiplicar </input>
</fieldset>
<input type="button" value="Começa" id="button" ></input>
</form>
and here is the jsfiddle with both the html and the js http://jsfiddle.net/3bc9m/15/ . I need to store the values of the 2 fieldset so I, depending on the values picked can generate a game, but my javascript isn't returning any of them. What is wrong? I've been told that JQuery is much easier but i can't use it.
Your code on jsFiddle seems to be working fine for the most part. The only thing was that the elements output and output2 don't exist on the page.
So this code that was supposed to display the selected values wasn't working:
document.getElementById('output').innerHTML = curr.value;
document.getElementById('output2').innerHTML = tdj.value;
The part that actually retrieves the selected values is working fine.
Just add those two elements to the page, like this:
<p>Selected Values:</p>
<div id="output"></div>
<div id="output2"></div>
An updated jsFiddle can be found here.
EDIT
If a radio button from only one of the sets is selected, the code fails. You could use this code to find the selected values instead:
document.getElementById('button').onclick = function() {
var dif = document.getElementsByName('dificuldade');
var tip = document.getElementsByName('Tipodejogo');
var difValue;
for (var i = 0; i < dif.length; i++) {
if (dif[i].type === "radio" && dif[i].checked) {
difValue = dif[i].value;
}
}
var tipValue;
for (var i = 0; i < tip.length; i++) {
if (tip[i].type === "radio" && tip[i].checked) {
tipValue = tip[i].value;
}
}
document.getElementById('output').innerHTML = difValue;
document.getElementById('output2').innerHTML = tipValue;
};​
An updated jsFiddle is here.
Consider this post that adresses the issue. It shows a few javascript methods as well as how you would use it in jQuery.
How can I check whether a radio button is selected with JavaScript?
Is there a specific reason you want to break it down by fieldset instead of directly accessing the radio buttons by name?

Simple way to get element by id within a div tag?

Please forgive me if I repeat the question.
I have HTML that all elements inside a div tag has different id, suppose I have already get the reference to the div, is there any simple way to get the element by its id without iterate all elements with that div?
here is my sample html:
<div id="div1" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
<div id="div2" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
You may try something like this.
Sample Markup.
<div id="div1" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
<div id="div2" >
<input type="text" id="edit3" />
<input type="text" id="edit4" />
</div>
JavaScript
function GetElementInsideContainer(containerID, childID) {
var elm = {};
var elms = document.getElementById(containerID).getElementsByTagName("*");
for (var i = 0; i < elms.length; i++) {
if (elms[i].id === childID) {
elm = elms[i];
break;
}
}
return elm;
}
Demo: http://jsfiddle.net/naveen/H8j2A/
A better method as suggested by nnnnnn
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
Demo: http://jsfiddle.net/naveen/4JMgF/
Call it like
var e = GetElementInsideContainer("div1", "edit1");
var x = document.getElementById("parent").querySelector("#child");
// don't forget a #
or
var x = document.querySelector("#parent").querySelector("#child");
or
var x = document.querySelector("#parent #child");
or
var x = document.querySelector("#parent");
var y = x.querySelector("#child");
eg.
var x = document.querySelector("#div1").querySelector("#edit2");
You don't want to do this. It is invalid HTML to have more than one element with the same id. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.
You should be using a class, or just iterating through the inputs and keeping track of an index.
Try something like this:
var div2 = document.getElementById('div2');
for(i = j = 0; i < div2.childNodes.length; i++)
if(div2.childNodes[i].nodeName == 'INPUT'){
j++;
var input = div2.childNodes[i];
alert('This is edit'+j+': '+input);
}
JSFiddle
A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.
You could change your HTML to this:
<div id="div1" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
<div id="div2" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
Then, you could get the first item in div1 with a CSS selector like this:
#div1 .edit1
On in jQuery:
$("#div1 .edit1")
Or, if you want to iterate the items in one of your divs, you can do it like this:
$("#div1 input").each(function(index) {
// do something with one of the input objects
});
If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.
If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.
You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.
A simple way to do what OP desires in core JS.
document.getElementById(parent.id).children[child.id];
In HTML ids should be unique. I suggest you change your code to something like this:
<div id="div1" >
<input type="text" name="edit1" id="edit1" />
<input type="text" name="edit2" id="edit2" />
</div>
<div id="div2" >
<input type="text" name="edit1" id="edit3" />
<input type="text" name="edit2" id="edit4" />
</div>
Sample Html code
<div id="temp">
F1 <input type="text" value="111"/><br/>
F2 <input type="text" value="222"/><br/>
F3 <input type="text" value="333"/><br/>
Type <select>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<input type="button" value="Go" onclick="getVal()">
</div>
Javascript
function getVal()
{
var test = document.getElementById("temp").getElementsByTagName("input");
alert("Number of Input Elements "+test.length);
for(var i=0;i<test.length;i++)
{
if(test[i].type=="text")
{
alert(test[i].value);
}
}
test = document.getElementById("temp").getElementsByTagName("select");
alert("Select box "+test[0].options[test[0].selectedIndex].text);
}
By providing different tag names we can get all the values from the div.
Unfortunately this is invalid HTML. An ID has to be unique in the whole HTML file.
When you use Javascript's document.getElementById() it depends on the browser, which element it will return, mostly it's the first with a given ID.
You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.

Categories

Resources