Javascript: Set element value? - javascript

I would like to set a value of a <label>, like so:
<label for="idname">Value here...</label>
with Javascript. I have already done this, for the for attribute:
element.setAttribute("for", "idname");
is there something like element.setValue() that I can use to set the value of the label? Thanks!

jsFiddle Demo
Iterate through the label elements looking for the property for="idname" like this:
var labels = document.getElementsByTagName("label");
for( var i = 0; i < labels.length; i++ ){
if( labels[i].outerHTML.indexOf('for="idname"') > -1){
var UseLabelValue = labels[i].innerHTML;
labels[i].innerHTML = "Replace Value";
}
}

<label for="idname">Value here...</label>
<script>
document.getElementsByTagName('label')[0].innerHTML='new value';
</script>
https://developer.mozilla.org/ru/docs/DOM/element.innerHTML
http://javascript.info/tutorial/searching-elements-dom

A label has no value. If you want to set the text, you may use
element.innerHTML = "some text";

Related

How to get element by name with $key

PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function
function findTotal() {
var arr = document.getElementsByName('qty');
...
document.getElementById('result').value = decimalPlaces(tot, 2);
}
My qty name needs key for post array. How do I get name inside js function to calculate quantities?
You can use
document.querySelector("input['name^='qty']").value
if you don't have jQuery.
This will select an input with name attribute starting with "qty". If you have multiple inputs which match the criteria you can select them all using
document.querySelectorAll("input[name^='qty']")
which will return a NodeList. You can read more about this here.
You can do something like this
var myVar = document.getElementsByTagName("somename");
//do something else
If you are using jquery
value = $( "input[name^='qtd']" ).val();
//it will pick the input wich name starts with 'qtd'
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'qty' 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('qty') == 0) {
eles.push(inputs[i]);
}
}
Don't query the element by the name attribute's value. I'm not sure what's the purpose of the key and why you need it in the findTotal method, but here's an example:
<p>Qty : <input type="number" value="" name="qtyMyKey" onChange="findTotal(event)" /></p>
<script>
function findTotal(e) {
var inputEl = e.target,
inputName = inputEl.getAttribute('name'),
myKey;
if (typeof inputName === 'string') {
myKey = inputName.replace('qty', '');
}
console.log(myKey);
//var arr = document.getElementsByName('qty');
//document.getElementById('result').value = decimalPlaces(inputEl.value(), 2);
}
</script>
Here's the jsFiddle demo.

Can i call another function inside the GetElement in Javascript

I am trying to call another function inside the getElement but it is not working everything when i change my selection. When i select Car, in the textbox my varxumb should populate. Any idea...
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option><option>Force</option><option>Angle</option><option>Area</option></select></td>';
function fillgap() {
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
if (forcxlist == "Force") {
document.getElementById("result1").value = xnumb;
}
}
I don't know how this "Force" value is coming to check.
you can try these solutions.
if (forcxlist == "Force")
instead use
var forcxlistText = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistText == "Force")
or use value technique
<div id ="mycall1">
</div>
<div id ="result1">
</div>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx" onchange="fillgap(this.value)"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
function fillgap(value){
var xnumb = 20;
if (value == "2"){
document.getElementById("result1").innerHTML = xnumb;
}
}
</script>
or use
<div id ="mycall1">
</div>
<input type="text" id="result1" value=""/>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
document.getElementById("forcx").onchange = function (){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].value;
if (forcxlistValue == "2"){
document.getElementById("result1").value = xnumb;
}
}
</script>
The forcxlist variable is an element object, returned by the document.getElementById method. Afterwards, you are checking if this element object is equal to "Force", which is a string (meaning the contents of your if block will never be executed). Did you mean to check if the contents of that object are equal to Force?
Instead of
if (forcxlist == "Force"){
use
if (forcxlist.innerHTML == "Force"){
I hope this helps!
Can't use innerHTML so i changed it to .value
document.getElementById("result1").value = xnumb;
There are a couple issues here.
First, you are expecting forcxlist to be a string, not an element, so you need to use .value to get the selected value of the dropdown.
Second, you should do your comparison with === not ==, as this ensures type equality as well, and is best practice.
I would also recommend building your select using HTML elements. It keeps things cleaner, is more readable, and is easier to maintain.
Since you are using the same id for the select, you would have to change the selector in your fillgap handler to var forcxlist = e.target.value;, this way the event will fire based on only the select that you are interacting with, regardless of how many rows you have in the table.
Updated code is below, and an updated working fiddle here. As per your comment about adding additional rows, the fiddle has this working as well.
<input type="button" value="Add Row" onclick="addDropDown()">
<table id="mycall1"></table>
<script>
function addDropDown() {
var tbl = document.getElementById("mycall1");
var newRow = tbl.insertRow(-1);
var newCell = newRow.insertCell(0);
newCell.appendChild(createDropDown("forcx", fillgap));
}
function createDropDown(id, onchange) {
var dd = document.createElement('select');
dd.id = id;
dd.onchange = onchange;
createOption("Select", dd);
createOption("Force", dd);
createOption("Angle", dd);
createOption("Area", dd);
return dd;
}
function createOption(text, dropdown) {
var opt = document.createElement("option");
opt.text = text;
dropdown.add(opt);
}
function fillgap() {
var xnumb = 20;
var forcxlist = e.target.value;
if (forcxlist === "Force") {
document.getElementById("result1").value = xnumb;
}
}
</script>
<input type="text" id="result1">

How to Get Radio Button Name and Id by its Tag Name when It is Checked?

my code is here where i am counting the all radio button and checked radio button,
var selection=new Array();
var allR = document.getElementsByTagName('input');
var a=0;
var b=0;
for(var i=0; i<allR.length; i++){
if(allR[i].type=='radio') { b++; }
if(allR[i].type=='radio' && allR[i].checked) { a++; }
}
how to get radio button name and its id by its Tag name ???
hopes for your suggestions
So when you have your collection of elements stored in allR, you can get ids and names by getAttribute method, because ids and names are just usual attributes
element.getAttribute('id') element.getAttribute('name')
use it like this
<script>
var rad = document.getElementbyId('rad_id').value;
</script>
<input type="radio" id="rad_id" value="my value">
its result will be
`my value`
Try to put
alert(allR[i].getAttribute('id') + ', ' + allR[i].getAttribute('name'));
inside the loop
Use this to get the name: allR[i].name. You can get the ID in a similar manner: allR[i].id.

Display value of textfield onChange using Javascript

What I want to do is whenever I type a value in the text field, the value typed will be displayed right away.
How do I do it exactly? Is there anyway I could put the value in a variable and use it right away without using onClick?
Here is how I would do it:
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()">
<div id="div1"></div>
I don't think you can do it without any events.
Maybe you can do it with HTML5's <output> tag. I don't know it very well, but try some research.
W3Schools have some good examples.
Hope this can help you
Without using the change event? Why on earth would you want this? The only alternative I can think of would be polling at an interval. Something like:
var theValue = "";
var theTextBox = document.getElementById('myTextBox');
// Run 10 times per second (every 100ms)
setInterval(function() {
// Check if the value has changed
if(theTextBox.value != theValue)
{
theValue = theTextBox.value;
}
}, 100);
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
function changenew(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()" onchange="changenew()">
is it Possible
you can check to see if your input field is in focus, then listen for any key input events and update your display field with the appropriate characters.
html:
​<input type="text" id="myText"/>
<span id="output"></span>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
js:
var myText = document.getElementById("myText");
myText.onkeyup = function(){
var output = document.getElementById("output");
output.innerHTML = this.value;
}
demo : http://jsfiddle.net/seUBJ/
​

Get all div values of similiar id in a particular div

I have a div structure like below
<div id=main">
<input type="hidden" id="people_0_1_0" value="12"/>
<input type="hidden" id="people_0_1_1" value="12"/>
</div>
Now how to add all hidden input values in a variable. Thanks
Using Jquery's map function
var myArray = $('#main input').map(function(){
return $(this).val();
}).get();
It will collect all input's values(12 and 12 in this case) to array variable.
See jsfiddle http://jsfiddle.net/GkXUS/1/
If you want to get sum of values you can do the following
var total = 0;
$.each(myArray,function() {
total += parseInt(this,10);
});
​
var total = 0;
$('#main input[id^="people_"]').each(function(){
total += parseInt(this.value, 10);
});
Note that I am using attribute starts with selector to find all the input elements whose id starts with people_.
total will give you the total of all the input elements value.
I guess you want this:
var hidden_value = new Array();
var hiddens = document.getElementById( "main" ).childNodes;
for( i = 0 ; i < hiddens.length ; i++ ){
hidden_value.push( hiddens[ i ].value );
}
You could try something like this:
var peopleData = $("#main input[type=hidden]").serializeArray();
Putting values in a variable does not make sense. You can insert the values in a Array and perform your required operation
Using Plain Javascript
var els=document.getElementById('main').childNodes;
var a​llVal​=​​​​​​​​[];
for(i=0; i<els.length-1; i++)
{
if(els[i].nodeType != 3 && els[i].type=="hidden") allVal.push(els[i].value);
}
console.log(allVal); // the array
console.log(allVal[0]); // first value
An example is here.

Categories

Resources