I have a webpage with lots of inputs. They are all in this format, with the input tag before the label.
<input type='checkbox' id='myinput'>
<label for='myinput'>My Text</label>
Using javascript, if I didn't want to type type='checkbox' each time, I could do this, and each input would become a checkbox...
for (i=0;i<document.getElementsByTagName('input').length;i++) {
document.getElementsByTagName('input')[i].setAttribute('type', 'checkbox')}
I'd like to do the same thing with the label element. I don't want to use for='myinputsID' for every label. I realize I can nest the inputs inside the label like this to eliminate the for,
<label>My Text
<input type="checkbox" id="myinput">
</label>
but lets just say I don't want to do that. I need to keep the html in the same format with the input first and then the label... I would need to find a way to apply the htmlFor attribute to each label and assign it the ID of the input immediately preceding it. Is that possible?
Basically you have to use document.getElementsByTagName("input") to get a collection of all the input html elements on your page. Afterwards loop over this list to see which of those are actually checkboxes. If we found a checkbox, we can get the next html element using element.nextElementSibling. Finally just set the htmlFor attribute for those to the id of the input element.
var elements = document.getElementsByTagName("input");
for (var a = 0; a < elements.length; a++) {
if (elements[a].type == "checkbox") {
elements[a].nextElementSibling.htmlFor = elements[a].id;
}
}
<input type='checkbox' id='myinput1'>
<label>My Text</label>
<input type='checkbox' id='myinput2'>
<label>My Text</label>
<input type='checkbox' id='myinput3'>
<label>My Text</label>
I think this should work
var inputs = document.getElementsByTagName('input');
var input;
for (i=0;i<inputs.length;i++) {
input = inputs[i];
input.setAttribute('type', 'checkbox');
input.nextElementSibling.setAttribute('for', input.id);
}
Related
I'm a novice in JS and trying to put some text dynamicly as a optionvalue for the radio button. But I can't seem to make the text appear. What am I doing wrong?
HTML
<form id="formulier">
<label for="a">
<input type="radio" id="a" name="a">
<!--here I want to show a value from an array ic answer[0]-->
<!--tried also this: <script>document.write(answer[0]);</script> -->
</label>
</form>
JS
var answer = <?php echo json_encode($antwoorden); ?>;
const a = document.getElementById("a");
// Ive tried:
a.value = answer[0];
a.innerHTML = answer[0];
a.innerText = answer[0];
None of them shows up. How can I make the text show up in HTML?
You can't output text by setting it as a value of radio buttons.
Instead you could set it as the textual content of the related label element.
To be able to select the associated label easily with JavaScript, assign the same class as the ìd of the <input type="radio"> element to it.
HTMl & JS Snippet
var answer = 'Dynamically inserted Message';
const a = document.getElementsByClassName("a")[0];
a.innerHTML = answer;
<form id="formulier">
<input type="radio" id="a" name="a">
<label for="a" class="a"></label>
</form>
I have the following HTML:
<div class="control-group">
<label class="control-label-sub">Description/Pack Size</label>
<div class="controls">
<input type="text" name="packetSize" class="wfinput required form_error" id="packetSize" />
<label id="packetSize-error" class="form_error" for="packetSize">
This field is required.
</label>
</div>
</div>
Is there a way to select the <label> element that is the child of .control-group (ie, the one with "Description/Pack Size" text), from the <input /> text field in my HTML?
To select the <label> element that is above the <input/> element, you could:
first use .closest() to select the first .control-group above the <input/> element and then
select the first child label of that .control-group
This can be achieved via the following jQuery script:
const input = $('input[name="packetSize"]');
const controlGroup = input.closest('.control-group');
const label = $('label', controlGroup);
It's possible to condense this into a single line but I've broken it into steps for clarity. Hope that helps.
If you want to get all label that class was named "control-label-sub".
var element = $("label.control-label-sub")
And If you want to get only that label I prefer following
var element = $("input#packetSize").parent().prev()
I am supposed to have the same HTML code segment repeated multiple times on the same page. I have an external JavaScript file whose functionality is meant to be invoked whenever a user interacts with one of the repeated segments. However, only the first of the three code segments is impacted upon interaction. When interacting with the other two, nothing happens, meaning, the JavaScript does not get invoked.
I would assume that if all HTML code segments have the same IDs and classes (aside from the fact that unique IDs should be assigned), then at the least the content in all 3 HTML segments would change if changes are made in any of the other instances of these segments.
Here is an example of this issue:
<input id="my-id" type="text" />
<input id="my-id" type="text" />
<input id="my-id" type="text" />
<script>
var textbox = document.getElementById("my-id");
textbox.onkeyup = function() {
alert("ok");
}
</script>
Here, only interaction with the first instance of my-id creates the alert box, the other 2, don't. How can I make my code so that it applies to all 3 textboxes?
you should not use same id for multiple elements. The selector will return only first matched element in case of multiple elements with same id. It would be better if you use class instead of id. something like this will work:
<input class="my-id" type="text" />
<input class="my-id" type="text" />
<input class="my-id" type="text" />
<script>
var textboxes = document.getElementsByClassName("my-id");
for (var i = 0; i < textboxes.length; i++) {
textboxes[i].onkeyup = function(){
alert("ok");
};
}
</script>
You cannot have same id to all div's, ID's should be unique. Please change the ID to class in order to work.
Calling Javascript functions on a specific ID when there are multiple instances of the ID (which is a big no-no) will only work on the first instance in the DOM. Try calling your function on either the inputs or assign a class to each input and call it on the class.
You cannot use ID names in multiple times.. Change ID to CLASS.. It will work....
ID's must be unique!
In order to use the same javacsript functions for multiple div, assign a common class for all the divs and invoke the js function for the class!
Ids have to be unique, see: Can multiple different HTML elements have the same ID if they're different elements?. beside that getElementById returns only one element. Take a look at Adding event listeners to multiple elements
var textboxes = document.getElementsByClassName("my-class");
function keyUpListener() {
console.log("ok");
}
for (var i = 0; i < textboxes.length; i++) {
textboxes[i].addEventListener('keyup', keyUpListener, false);
}
<input class="my-class" type="text" />
<input class="my-class" type="text" />
<input class="my-class" type="text" />
Or use event delegation:
function keyUpListener(event) {
if( event.target.getAttribute('class').split(' ').indexOf('my-class') !== -1 ) {
console.log( 'ok' );
}
}
document.addEventListener('keyup', keyUpListener, false);
<input class="my-class" type="text" />
<input class="my-class" type="text" />
<input class="my-class" type="text" />
Because element ID must be unique, this attribute cannot be utilized to bind click event.
HTML5 support CSS Selector, a powerful mechanism to identify element that has similar characteristic.
Your code can be re-written with CSS Selector like below:
<input type="text" data-item="Text box 1"/>
<input type="text" data-item="Text box 2"/>
<input type="text" data-item="Text box 3"/>
<script>
function keyUpListener() {
var itemId = this.getAttribute('data-item');
alert(itemId);
}
var textboxes = document.querySelectorAll('input');
for (var i = 0; i < textboxes.length; i++) {
textboxes[i].addEventListener('keydown', keyUpListener, false);
}
</script>
I have a form with a bunch of inputs. Sometimes the form will have 1 input and sometimes up to 10 inputs. When someone fills out each input I want a tag field at the bottom to be populated also. Right now I have it working but only with a set number of inputs. (3 at the moment).
Im trying to figure out how to make it work regardless of how many inputs there are on the page.
HTML
Input1 <input id="input1" name="input1" type="text" value="" />
<br/>
Input2 <input id="input2" name="input2" type="text" value="" />
<br/>
Input3 <input id="input3" name="input3" type="text" value="" />
<br/>
<p>List of inputed text</p>
<span id="allInputs"></span>
Jquery
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#allInputs").text(inputArray.join(' '));
});
A nice to have also would be putting them into another input instead of a span and adding a comma after each one except for the last one.
I know Im probably missing something very simple here.
In your example you are only allowing for 3 inputs as you have 3 input boxes, when any of those input boxes change your tags are then being transferred to the span.
Now it sounds like you wish to allow for multiple entries regardless of how many inputs. You could try something simple such as the below fiddle.
http://jsfiddle.net/K2g4z/
Html:
<div>
<strong>Enter your tag and click add</strong>
<br/>
<input type="text" id="tagEntry" />
<button id="tagAdd">Add</button>
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
Javascript:
var tags = [];
$(function() {
$('#tagAdd').click(function(){
//get the tag value and trim the spaces
var tVal = $('#tagEntry').val().trim();
if(tVal == '')
return;
//reset the entry box
$('#tagEntry').val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
UPDATE:
The JSFiddle link http://jsfiddle.net/K2g4z/1/ now supports using multiple inputs of as many as you need. To achieve this instead of selecting on element ID we bind to a class name. Given the following Html.
<div>
<strong>Enter your tag and click add</strong>
<br/>
<strong>Tag 1</strong>
<input type="text" id="tagEntry" class="tagEntry" />
<br/>
<strong>Tag 2</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 3</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 4</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 5</strong>
<input type="text" class="tagEntry" />
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
All the tag input boxes have a class of tagEntry now this class will become our selector. With the following JS we can bind the blur event to every tag that has a class of tagEntry. This will now update the tags box every time any of the inputs changed.
var tags = [];
$(function() {
$('.tagEntry').blur(function(){
//get the tag value and trim the spaces
var tVal = $(this).val().trim();
if(tVal == '')
return;
//reset the entry box
$(this).val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
As you can see our handler binds to all the inputs, as any of the inputs receives the blur event the method of extracting the tags is executed.
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#masterinput").val(inputArray.join(' '));
});
You probably want to narrow the selector so it isn't selecting all text inputs on the page.
var inputs$ = $("input:text").change(function () {
var inputArray = [];
$.each(inputs$, function(i, v) {
inputArray.push($(v).val());
}
$("#allInputs").text(inputArray.join(' '));
});
Here you go:
var str = "";
$("input[type=text]").change(function () {
$("input[type=text]").each(function(){
str += $(this).val()+",";
};
});
$("#allInputs").html(str);
...
<td id="mycell">
<input type="text" name="year" onmouseout="do_something(this.value,...);" />
<input type="text" name="month" onmouseout="do_something(this.value,...);" />
</td>
...
i need to get value of neighbouring input element when submitting function on other element.
Thing is there are 10 of them and i cannot use id, names are same as well.
So i need to somehow get parent <td> and then address its child e.g. i submit year then onmouseout="do_something(this.value, this.parent.td.month.value");"
If you have a reference to one of the input elements, then:
var td = input.parentNode;
And you can then select all child input elements using:
var inputs = td.getElementsByTagName('input');
And to get a particular one:
var input0 = inputs[0];
and so on. To get an adjacent input, find the current input in the inputs collection, then grab the next or previous (if there is one) as required.
use the .next and .previous selector:
$(this).previous('input').val();
$(this).next('input').val();