get selected value in label using JavaScript dynamically - javascript

I have to print 10 values dynamically in javascript using for loop. Here I take label for printing.
Now when I click on particular text on label I can show one alert with that text name,
Any One help me How to do this.
<html>
<head>
<script type = "text/javascript">
var x = "";
function checkCookie(){
var arr = new Array("One","Two","Three");
for(var i=0; i<arr.length; i++) {
x = x + arr[i] + "<br>" + "<br>";
document.getElementById("idval").innerHTML = x;
}
}
function getItem(){
// here i want to display the selected label item
}
</script>
</head>
<body onload = "checkCookie()">
<label id = "idval" onclick = "getItem()"> </label>
</body>
</html>

Not at all clear from your question description what it is you need. If what you're wanting is to dynamically create labels, and have access to their onclick events; have a look at the Javascript functions appendChild and setAttribute. I've created a JSfiddle which demonstrates what you might need:
function createLabels() {
for(var i=0; i<10; i++) {
var label = document.createElement('label');
label.innerHTML = "item " + i;
label.onclick = onClick;
document.body.appendChild(label);
}
}
function onClick(e){
alert(e.srcElement.innerHTML)
}
http://jsfiddle.net/R4abH/2/
Edit 1 : Adding onclick attributes is considered bad practise. Reworked answer using event listeners instead.
Edit 2 : As per Benjamin Gruenbaum's comment below, AddEventListener does not seem to be supported by IE (please see MSIE and addEventListener Problem in Javascript?). Reworked jsfiddle to use onclick instead, as per dystroy's suggestion.

Related

Dynamically display html elements via loop

I am working with javascript and jquery. I want to be able to display a buttom, some text, and/or really any html elements or components as many times as the loop allows. I am able to loop through and print alert statements
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++)
{ alert("count: " + i); }
}
Simple enough. This would give me 5 alert statements, but instead of using alert statements, I want to be able to display a button or some text or any other html elements. So I would get five buttons displayed on an html page. Is this possible? I'm actually using a .foreach function but for ease of use, a regular for loop would suffice for now. I want to be able to do this on button click (i.e., the function that has the loop starts running once I click a button) also. I'm just not sure really how to accomplish this. Any help would be greatly appreciated. Thanks in advance.
With vanilla Javascript (without using jQuery):
You can use document.createElement to create any type of element you want on the page. Here's the above loop creating <INPUT TYPE='BUTTON'> elements in a <div> with an id of test:
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++) {
var v = document.createElement('input');
v.type="button";
v.value="Button " +i;
document.getElementById('test').appendChild(v);
}
}
(In general, using document.write has been considered a bad practice for a while now.)
With jQuery, you can do:
for (i=0;i<5;i++) {
var btn = $("<button/>");
btn.text('Button '+i);
$('#test').append(btn);
}
You can use innerHTML field to add any html content into container on you page.
<script>
function LoopTest()
{
var i=0;
var stop=5;
for (i=0;i<5;i++)
{
document.getElementById("container").innerHTML += "<button>button</button>"
}
}
</script>
...
<div id="container"></div>
Refer: document.write(), Javascript events
<html>
<head>
<script>
function LoopTest() {
var i=0;
var stop = 5;
for (i=0;i<5;i++)
{
document.write('<p>' + i + '</p>'); // This writes the number in a paragraph
}
}
</script>
</head>
<body>
<!--
Here onclick event is used to recognize the click event,
which is fired when the user clicks the button,
this calls the LoopTest() function which generates 5 paragraphs with numbers
-->
<button onclick="LoopTest()">Click to generate content!</button>
</body>
</html>
This is a solution : http://jsfiddle.net/leojavier/gbuLykdj/
<div class="container">
<button class="trigger">Trigger</button>
</div>
JS
$('.trigger').on('click', function(){
LoopTest();
});
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++){
$('body').append('<button class="trigger">Trigger No. ' + i + '</button>')
}
}

Input box value vanishes when adding a new one

I'm working on a web app where I need to add a number of input boxes one after the other in order to get commands from the user. I add them using JavaScript to a div with a unique ID to each. The problem I have is once I press enter and the JavaScript function is called to add the next one, the previous input box empties out, and I don't know why.
Here is sample code:
var i = 0;
add_input();
function add_input() {
i++;
document.getElementById('main').innerHTML += "<p>> <input type='text' style='width:90%' id='input" + i + "' onkeypress='press_key(event, this)'></p>";
document.getElementById('input' + i).focus();
}
function press_key(e, t) {
if (e.keyCode == 13) {
add_input();
}
}
<div id='main'></div>
innerHTML will override all existing content and replace them with new ones. You should create a new input element and use insertNode instead.
The addition assignment operator will add the right hand value to the left hand value and then assign the resultant value to the left hand side.
For a quick example:
x += y;
// is equivalent to
x = x + y;
In your code you are basically taking the existing HTML, adding a new chunk of HTML and then assigning that new HTML to the original element replacing the existing HTML. Since the value is not set in the HTML but stored in the DOM it is lost as soon as you assign new HTML to the element (which is when the browser renders it to the DOM replacing the previous DOM).
You could use insertNode as mentioned above or set the HTML attribute to store the value first as the below example shows. However note that this solution is purely to show why the values are disappearing. Doing it this way has an issue that if any of the previous input values are changed only the original value for those inputs would be preserved.
var i = 0;
add_input();
function add_input() {
var curInput = document.getElementById('input' + i);
if (curInput) {
curInput.setAttribute('value', curInput.value);
}
++i;
document.getElementById('main').innerHTML += "<p>> <input type='text' style='width:90%' id='input" + i + "' onkeypress='press_key(event, this)'></p>";
document.getElementById('input' + i).focus();
}
function press_key(e, t) {
if (e.keyCode == 13) {
add_input();
}
}
<div id='main'></div>
innerHTML overwrites all html from the selected element including any user/javascript actions performed on the given html. Thus your input values will be erased with the new html. You are going to want to create an element and then use appendChild. This will maintain the state of your current html elements.
var i = 0;
function add_input()
{
i++;
var input = document.createElement('input');
input.onkeypress=press_key;
input.id = 'input' + i;
document.body.appendChild(input);
input.focus();
}
function press_key(e)
{
//`t` argument is no longer used. Use `this` instead.
if (e.keyCode == 13)
{
add_input();
}
}
<html>
<head>
<script>
</script>
</head>
<body onload='add_input()'>
<div id='main'>
</div>
</body>
</html>
As stated above, your other values disappear due to the inner workings of "innerHTML". In fact, when you do string.innerHTML += string it will replace the HTML for it (meaning what was there before is totally gone and is de-facto replaced with fresh new HTML).
What you want to use is probably appendChild().
With little rewriting I have managed to make your code work:
http://jsfiddle.net/gs1s0fsx/
var i = 0;
function add_input() {
i++;
var main = document.getElementById('main'),
p = document.createElement("p"),
arrow = document.createTextNode('>'),
el = document.createElement('input');
el.type = "text";
el.style = "width:90%";
el.id = "input" + i;
el.addEventListener("keypress", press_key);
main.appendChild(p);
main.appendChild(arrow);
main.appendChild(el);
el.focus();
}
function press_key(e, t) {
if (e.keyCode == 13) {
add_input();
}
}
add
<div id='main'></div>
Hope this helps.

JavaScript: get custom button's text value

I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))

Give Each Word In An <input> A Random Colour

How can I Give Each Word In An <input> A Random Colour
You cannot change the Text colors inside an <input> field. You can however create a DIV under it or overlay it as suggested in a previous answer.
Here's an example that does that using Plain Old Javascript.
<html>
<head>
<title>Random Colors</title>
<script>
window.onload = function(){
var mytextbox = document.getElementById("mytext");
mytextbox.onblur = function(){
var words = mytextbox.value.split(' ');
var myDiv = document.getElementById("divText");
myDiv.innerHTML = '';
for(i = 0, len = words.length; i<len;i++){
myDiv.innerHTML += '<span>' + words[i] + '</span> ';
}
var spans = myDiv.getElementsByTagName('span');
for(i = 0, len = spans.length; i<len; i++){
spans[i].style.color = random_color();
}
}
}
function random_color()
{
var rint = Math.round(0xffffff * Math.random());
return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
}
</script>
</head>
<body>
<input type="text" id="mytext" />
<div id="divText"></div>
</body>
</html>
Random Color Function Source
I don't think that's possible.
You could overlay text on top of it, but you're getting into thedailywtf territory there.
You could use a div instead of an input.
Then give it CSS properties that makes it look an input.
And use the contentEditable property to edit it(an HTML5 thing that is supported by modern browsers and IE) if your browser audience allows it.
But then I guess you'll have to build something like a rich text editor "a la" google docs to allow your users to change the colors, which will guarantee you some funny working hours ;)
Use something like YUI Editor or FCKEditor

Find html label associated with a given input

Let's say I have an html form. Each input/select/textarea will have a corresponding <label> with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label.
Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?
If you are using jQuery you can do something like this
$('label[for="foo"]').hide ();
If you aren't using jQuery you'll have to search for the label. Here is a function that takes the element as an argument and returns the associated label
function findLableForControl(el) {
var idVal = el.id;
labels = document.getElementsByTagName('label');
for( var i = 0; i < labels.length; i++ ) {
if (labels[i].htmlFor == idVal)
return labels[i];
}
}
First, scan the page for labels, and assign a reference to the label from the actual form element:
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}
Then, you can simply go:
document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';
No need for a lookup array :)
There is a labels property in the HTML5 standard which points to labels which are associated to an input element.
So you could use something like this (support for native labels property but with a fallback for retrieving labels in case the browser doesn't support it)...
var getLabelsForInputElement = function(element) {
var labels = [];
var id = element.id;
if (element.labels) {
return element.labels;
}
id && Array.prototype.push
.apply(labels, document.querySelector("label[for='" + id + "']"));
while (element = element.parentNode) {
if (element.tagName.toLowerCase() == "label") {
labels.push(element);
}
}
return labels;
};
// ES6
var getLabelsForInputElement = (element) => {
let labels;
let id = element.id;
if (element.labels) {
return element.labels;
}
if (id) {
labels = Array.from(document.querySelector(`label[for='${id}']`)));
}
while (element = element.parentNode) {
if (element.tagName.toLowerCase() == "label") {
labels.push(element);
}
}
return labels;
};
Even easier if you're using jQuery...
var getLabelsForInputElement = function(element) {
var labels = $();
var id = element.id;
if (element.labels) {
return element.labels;
}
id && (labels = $("label[for='" + id + "']")));
labels = labels.add($(element).parents("label"));
return labels;
};
document.querySelector("label[for=" + vHtmlInputElement.id + "]");
This answers the question in the simplest and leanest manner.
This uses vanilla javascript and works on all main-stream proper browsers.
I am a bit surprised that nobody seems to know that you're perfectly allowed to do:
<label>Put your stuff here: <input value="Stuff"></label>
Which won't get picked up by any of the suggested answers, but will label the input correctly.
Here's some code that does take this case into account:
$.fn.getLabels = function() {
return this.map(function() {
var labels = $(this).parents('label');
if (this.id) {
labels.add('label[for="' + this.id + '"]');
}
return labels.get();
});
};
Usage:
$('#myfancyinput').getLabels();
Some notes:
The code was written for clarity, not for performance. More performant alternatives may be available.
This code supports getting the labels of multiple items in one go. If that's not what you want, adapt as necessary.
This still doesn't take care of things like aria-labelledby if you were to use that (left as an exercise to the reader).
Using multiple labels is a tricky business when it comes to support in different user agents and assistive technologies, so test well and use at your own risk, etc. etc.
Yes, you could also implement this without using jQuery. :-)
Earlier...
var labels = document.getElementsByTagName("LABEL"),
lookup = {},
i, label;
for (i = 0; i < labels.length; i++) {
label = labels[i];
if (document.getElementById(label.htmlFor)) {
lookup[label.htmlFor] = label;
}
}
Later...
var myLabel = lookup[myInput.id];
Snarky comment: Yes, you can also do it with JQuery. :-)
All the other answers are extremely outdated!!
All you have to do is:
input.labels
HTML5 has been supported by all of the major browsers for many years already. There is absolutely no reason that you should have to make this from scratch on your own or polyfill it! Literally just use input.labels and it solves all of your problems.
with jquery you could do something like
var nameOfLabel = someInput.attr('id');
var label = $("label[for='" + nameOfLabel + "']");
If you're willing to use querySelector (and you can, even down to IE9 and sometimes IE8!), another method becomes viable.
If your form field has an ID, and you use the label's for attribute, this becomes pretty simple in modern JavaScript:
var form = document.querySelector('.sample-form');
var formFields = form.querySelectorAll('.form-field');
[].forEach.call(formFields, function (formField) {
var inputId = formField.id;
var label = form.querySelector('label[for=' + inputId + ']');
console.log(label.textContent);
});
Some have noted about multiple labels; if they all use the same value for the for attribute, just use querySelectorAll instead of querySelector and loop through to get everything you need.
Solution One <label>: One <input>
Using HTML 5.2 reference
Considering the <label> pointing to <input> using for=, the labels element will be a non empty array, and act as a link to the <label> element, accessing all properties of it, including its id=.
function myFunction() {
document.getElementById("p1").innerHTML = "The first label associated with input: <b>" + document.getElementById("input4").labels[0].id + "</b>";
}
<form>
<label id="theLabel" for="input4">my id is "theLabel"</label>
<input name="name1" id="input4" value="my id is input4">
<br>
</form>
<p>Click the "click me" button to see the label properties</p>
<button onclick="myFunction()">click me</button>
<p id="p1"></p>
Solution Many <label>: One <input>
With more than one <label> using for=, you can make a loop to show all of them, like this:
function myFunction2() {
var x = document.getElementById("input7").labels;
let text = "";
for (let i = 0; i < x.length; i++) {
text += x[i].id + "<br>";
}
document.getElementById("p7").innerHTML = text;
}
<b>Three labels for one input</b><br>
<br>
<form>
<label id="theLabel2" for="input7">my id is "theLabel2</label><br>
<label id="theLabel3" for="input7">my id is "theLabel3</label><br>
<label id="theLabel4" for="input7">my id is "theLabel4</label><br>
<input name="name1" id="input7" value="my id is input7">
<br>
</form>
<p>Click the "click me" button to see the label properties</p>
<button onclick="myFunction2()">click me2</button>
<p id="p7"></p>
$("label[for='inputId']").text()
This helped me to get the label of an input element using its ID.
Answer from Gijs was most valuable for me, but unfortunately the extension does not work.
Here's a rewritten extension that works, it may help someone:
jQuery.fn.getLabels = function () {
return this.map(function () {
var parentLabels = $(this).parents('label').get();
var associatedLabels = this.id ? associatedLabels = $("label[for='" + this.id + "']").get() : [];
return parentLabels.concat(associatedLabels);
});
};
A really concise solution using ES6 features like destructuring and implicit returns to turn it into a handy one liner would be:
const getLabels = ({ labels, id }) => labels || document.querySelectorAll(`label[for=${id}]`)
Or to simply get one label, not a NodeList:
const getFirstLabel = ({ labels, id }) => labels && labels[0] || document.querySelector(`label[for=${id}]`)
It is actually far easier to add an id to the label in the form itself, for example:
<label for="firstName" id="firstNameLabel">FirstName:</label>
<input type="text" id="firstName" name="firstName" class="input_Field"
pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
title="Alphabetic, Space, Dash Only, 2-25 Characters Long"
autocomplete="on" required
/>
Then, you can simply use something like this:
if (myvariableforpagelang == 'es') {
// set field label to spanish
document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
// set field tooltip (title to spanish
document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
}
The javascript does have to be in a body onload function to work.
Just a thought, works beautifully for me.
As it has been already mentionned, the (currently) top-rated answer does not take into account the possibility to embed an input inside a label.
Since nobody has posted a JQuery-free answer, here is mine :
var labels = form.getElementsByTagName ('label');
var input_label = {};
for (var i = 0 ; i != labels.length ; i++)
{
var label = labels[i];
var input = label.htmlFor
? document.getElementById(label.htmlFor)
: label.getElementsByTagName('input')[0];
input_label[input.outerHTML] =
(label.innerText || label.textContent); // innerText for IE8-
}
In this example, for the sake of simplicity, the lookup table is directly indexed by the input HTML elements. This is hardly efficient and you can adapt it however you like.
You can use a form as base element, or the whole document if you want to get labels for multiple forms at once.
No checks are made for incorrect HTML (multiple or missing inputs inside labels, missing input with corresponding htmlFor id, etc), but feel free to add them.
You might want to trim the label texts, since trailing spaces are often present when the input is embedded in the label.
The best answer works perfectly fine but in most cases, it is overkill and inefficient to loop through all the label elements.
Here is an efficent function to get the label that goes with the input element:
function getLabelForInput(id)
{
var el = document.getElementById(id);
if (!el)
return null;
var elPrev = el.previousElementSibling;
var elNext = el.nextElementSibling;
while (elPrev || elNext)
{
if (elPrev)
{
if (elPrev.htmlFor === id)
return elPrev;
elPrev = elPrev.previousElementSibling;
}
if (elNext)
{
if (elNext.htmlFor === id)
return elNext;
elNext = elNext.nextElementSibling;
}
}
return null;
}
For me, this one line of code was sufficient:
el = document.getElementById(id).previousElementSibling;
In most cases, the label will be very close or next to the input, which means the loop in the above function only needs to iterate a very small number of times.
Use a JQuery selector:
$("label[for="+inputElement.id+"]")
For future searchers... The following is a jQuery-ified version of FlySwat's accepted answer:
var labels = $("label");
for (var i = 0; i < labels.length; i++) {
var fieldId = labels[i].htmlFor;
if (fieldId != "") {
var elem = $("#" + fieldId);
if (elem.length != 0) {
elem.data("label", $(labels[i]));
}
}
}
Using:
$("#myFormElemId").data("label").css("border","3px solid red");
I know this is old, but I had trouble with some solutions and pieced this together. I have tested this on Windows (Chrome, Firefox and MSIE) and OS X (Chrome and Safari) and believe this is the simplest solution. It works with these three style of attaching a label.
<label><input type="checkbox" class="c123" id="cb1" name="item1">item1</label>
<input type="checkbox" class="c123" id="cb2" name="item2">item2</input>
<input type="checkbox" class="c123" id="cb3" name="item3"><label for="cb3">item3</label>
Using jQuery:
$(".c123").click(function() {
$cb = $(this);
$lb = $(this).parent();
alert( $cb.attr('id') + ' = ' + $lb.text() );
});
My JSFiddle: http://jsfiddle.net/pnosko/6PQCw/
I have made for my own need, can be useful for somebody: JSFIDDLE
$("input").each(function () {
if ($.trim($(this).prev('label').text()) != "") {
console.log("\nprev>children:");
console.log($.trim($(this).prev('label').text()));
} else {
if ($.trim($(this).parent('label').text()) != "") {
console.log("\nparent>children:");
console.log($.trim($(this).parent('label').text()));
} else {
if ($.trim($(this).parent().prev('label').text()) != "") {
console.log("\nparent>prev>children:");
console.log($.trim($(this).parent().prev('label').text()));
} else {
console.log("NOTFOUND! So set your own condition now");
}
}
}
});
I am bit surprised no one is suggesting to use the CSS relationship method?
in a style sheet you can reference a label from the element selector:
<style>
//for input element with class 'YYY'
input.YYY + label {}
</style>
if the checkbox has an id of 'XXX'
then the label would be found through jQuery by:
$('#XXX + label');
You can also apply .find('+ label') to return the label from a jQuery checkbox element, ie useful when looping:
$('input[type=checkbox]').each( function(){
$(this).find('+ label');
});
If you use the for attribute, you can use querySelector(...) to get
the associated label.
HTML/JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<label for="myCheckbox">Log Report to Console?</label>
<input name="myCheckbox" type="checkbox" oninput="doSomething(event)" />
<script type="text/javascript">
function doSomething(e) {
const query = `label[for="${e.target.name}"]`; // This is string interpolation NOT JQuery
const label = document.querySelector(query);
}
</script>
</body>
</html>
Plain JavaScript
function doSomething(e) {
// const query = `label[for="${e.target.name}"]`; // This is string interpolation NOT JQuery
// Maybe it is safer to use ".getAttribute"
const query = `label[for="${e.target.getAttribute("name")}"]`;
const label = document.querySelector(query);
// Do what you want with the label here...
debugger; // You're welcome
console.log(label);
}

Categories