Create a label and it's associated element without using ID - javascript

I'm gonna create a label element and it's associated input element together using JavaScript. This can be achieved if I use id and for attributes:
// Create input element:
let newInput = document.createElement('Input');
newInput.setAttribute('type', 'radio');
newInput.setAttribute('value', 'y');
newInput.setAttribute('id', 'myInput2');
newInput.setAttribute('name', 'opt');
document.body.appendChild(newInput);
// Create label for new Input:
let newlabel = document.createElement('Label');
newlabel.setAttribute('for', 'myInput2');
newlabel.textContent = 'Option 2:';
document.body.appendChild(newlabel);
<input type='radio' value='x' id='myInput1' name='opt'>
<label for='myInput1'>Option 1:</label>
The problem is: I have so many forms and so many inputs too, so this solution(which Chooses id for any input) looks like to be a nightmare rather than an option. In other hand, it seems ridiculous to create ID for an element just for binding it to a label (Of course it's my opinion)!
Fortunately there is an option in HTML to get rid of these kind of IDs:
// I couldn't find any way to create a new label and it's bounded element without using ID!
<label>
Option 1:
<input type='radio' value='x' name='opt'>
</label>
But I couldn't find it's JavaScript equivalent:(
So my question is: How can I create a label element in JavaScript and bind it to an input element without specifying ID?

you should append input to label, like this:
for (const i of [1, 2]) {
// Create input element:
let newInput = document.createElement('Input');
newInput.setAttribute('type', 'radio');
newInput.setAttribute('value', 'y');
newInput.setAttribute('name', 'opt');
// Create label for new Input:
let newlabel = document.createElement('Label');
newlabel.textContent = `Option ${i}:`;
newlabel.appendChild(newInput);
document.body.appendChild(newlabel);
}

Related

Get value of input type=date as a string

I want to extract the value from date field, but it doesn't work. I add the input this way:
var question0 = "<div id='0'><p>Please, enter the date: </p><br>"
+ "<input type=\"date\" id=\'contractdate\'></input><br></div>";
Here is how I tried to receive the value:
var text_Contract_Date = document.getElementById('contractdate').value;
//tried the code below, but didn't work
// var text_Contract_Date = document.getElementById('contractdate').valueAsDate;
// var text_Contract_Date = new Date(document.getElementById('contractdate').valueAsDate);
So, I want to get the value from input as a string, using pure JavaScript, because then it will be used to fill in the document.
Try this
var dateEntered = new Date(text_Contract_Date);
There is not enough information to resolve the issue, so I can only guess that you are probably inserting your variable into the DOM the wrong way.
If I call document.body.append(question0), only text is shown and not the tags.
Try moving content of question0 variable to your html file, then add onchange handler to your input, and also modify your .js file like below
function handleChange(event){
// here you can do whatever you want with the value of the input
alert(event.target.value)
}
<input type="date" id='contractdate' onchange="handleChange(event)"></input>
If you desperately want to create your HTML inside of Javascript, you have to do this like this:
// create div and assign id to it
const myDiv = document.createElement("div")
myDiv.id = '0'
// create p and set its contents
const myP = document.createElement("p")
p.textContent = "Please, enter the date: "
// create input, assign id to it and set its type to date
const myInput = document.createElement("input")
myInput.id = 'contractdate'
myInput.type = "date"
// put everything in your document
myDiv.appendChild(myP)
myDiv.appendChild(myInput)
document.body.appendChild(myDiv)

Setting a value to a input inside of var

I'm curios is it possible to access and modify data inside of javascript var, so far i tried it with pure javascript as well as with jquery. So both versions are fine for me.
var data = {
'name': 'Jhone',
'category': 'Human',
'type': 'good one',
},
form = `<input type='text' name='name' id='name'>
<input type='text' name='category' id='category'>
<input type='text' name='type' id='type'>`;
JQuery version (not working)
$.each(data, function( key, value ) {
if ($.type(value) === 'string' && value !== '')
$(form).find('#'+key).val(value)
});
JavaScript version (not working) (sorry don't know how to make foreach in pure js but the problem is with accessing element)
$.each(data, function( key, value ) {
if ($.type(value) === 'string' && value !== '')
form.getElementById(key).value = value ;
});
The main point is that i want to create js forms dynamically and avoid setting data like :
var form = `<input type='text' name='name' id='name' value='`+ value +`'>`;
Since it's a string, you would have to parse it first to be able to use operations like setting the value.
var form = `<input type='text' name='name' id='name'>`
form = $(form).attr('value', 'myvalue').prop('outerHTML');
console.log(form);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use ES6 Template Literals(Strings) and do something like this:
var id = "This_is_a_test_id"
var form = `<input type='text' name='name' id='${id}'>`;
console.log(form)
A vanilla javascript version using document.createElement and Element#setAttribute:
const input = document.createElement('input'),
attributes = {type: 'text', name: 'name', value: 'Jhone'};
for (let attr in attributes) input.setAttribute(attr, attributes[attr]);
document.body.appendChild(input);
Or if you want to write your input with HTML:
// First, append your <input>'s HTML into your DOM.
const inputHtml = '<input type="text" name="name">';
document.body.innerHTML += inputHtml;
// Then, get it and set its [value] attribute.
document.querySelector('input').value = 'Johne';
Revision after OP edit
// Create form element
const form = document.createElement('form'),
data = {
'name': 'Jhone',
'category': 'Human',
'type': 'good one',
};
for (let prop in data) {
// Create DOM element
let input = document.createElement('input');
// Set input attributes
input.setAttribute('type', 'text');
input.setAttribute('name', prop);
input.setAttribute('id', prop);
input.setAttribute('value', data[prop]);
// Append input to form
form.appendChild(input);
}
// Append form to document (for snippet purposes)
document.getElementById('form').appendChild(form)
<html>
<body>
<div id="form"></div>
</body>
</html>
Before OP edit
Yes, but you're doing it wrong.
First of all, var form = `<input type='text' name='name' id='name'>`; is a string, not a DOM element. You'd need to create a DOM element to manipulate it in the way you intended. Something like:
var form = document.createElement('form');
var input = document.createElement('input');
input.type = 'text';
input.name = 'name';
input.id = 'name';
form.appendChild(input);
You can now look for elements inside of form, but not using getElementById. Use querySelector or querySelectorAll for this.
var nameInput = form.querySelector('#name');
You can now manipulate this DOM Element the way you intended
nameInput.value = 'Head over to https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model to level up your DOM manipulation skills'

Changing a label's text by the FOR attribute

I would like to set the text of the label. Unfortunately the number 36 will change on each page refresh.
<label for="rn_TextInput_36_Incident.CustomFields.c.other_action_taken" id="rn_TextInput_36_Label" class="rn_Label">TEXT HERE</label>
<input type="text" id="rn_TextInput_36_Incident.CustomFields.c.other_action_taken" name="Incident.CustomFields.c.other_action_taken" class="rn_Text" maxlength="50" required="">
I can get the ID by using:
var id = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0].getAttribute('id');
How can I then use this to set the label text i.e. target the label by the value of the for attribute in JavaScript - not jQuery
So as mentioned, the number will change each time so I can't use the ID value of rn_TextInput_36_Label that the label currently has
Your element has the class rn_Label, so you can select by that.
var el = documment.querySelector(".rn_Label");
If you need to get more specific, you can include the tag name and part of the for attribute.
var el = documment.querySelector("label.rn_Label[for^=rn_TextInput_][for$=_Incident.CustomFields.c.other_action_taken]");
So this last selector selects the first element that:
has tag name label
has class name rn_Label
has a for attribute that starts with rn_TextInput_
has a for attribute that ends with _Incident.CustomFields.c.other_action_taken
And of course you can use querySelectorAll to select all elements on the page that meet that criteria.
you can work same as this code:
var input = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0];
if(input.labels.length > 0) {
var labelID = input.labels[0].id;
document.getElementById(labelID ).innerHTML = 'New Text for this lable';
}
else {
alert('there is no label for this input');
}
https://jsfiddle.net/SETha/75/
var id = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0].getAttribute('id');
document.querySelector("label[for='"+id+"']").innerText = 'new text';
It gets the ID and then uses querySelector to get the related label and sets the innertext

How do I add an input field after an element was created with javascript?

I am trying to add an input field to a created element. This is my code.
var Images_to_beuploaded_cont = document.getElementById("Images_to_beuploaded_cont");
var carCont = document.createElement('div');
carCont.className += "multipleImageAdding";
Images_to_beuploaded_cont.insertBefore(carCont, Images_to_beuploaded_cont.firstChild);
So, the code above adds the following
<div id="multipleImageAdding"></div>
What I want to do is the code below.
<div id="multipleImageAdding">
<input type="text" name="fname">
</div>
Is this even possible? to add an element to another after it was created?
Is this even possible? to add an element to another after it was created?
Yes, you could add the input element before or after appending the parent container element.
After creating the input element and adding the desired type and name attributes, just use the appendChild() method:
var input = document.createElement('input');
input.type = 'text';
input.name = 'fname';
carCont.appendChild(input);
Snippet:
var Images_to_beuploaded_cont = document.getElementById("Images_to_beuploaded_cont");
var carCont = document.createElement('div');
carCont.className += "multipleImageAdding";
var input = document.createElement('input');
input.type = 'text';
input.name = 'fname';
carCont.appendChild(input);
Images_to_beuploaded_cont.insertBefore(carCont, Images_to_beuploaded_cont.firstChild);
<div id="Images_to_beuploaded_cont"></div>

Change value of <input> to include a superscript, using Javascript

The following code works correctly for me, in HTML.
<input type = "text" name = "var_1" id = "i_var_1" value = "x&sup8">
The following, using Javascript, also works:
<p id = "p1"><input type = "text" name = "var_1" id = "i_var_1" value = "0"></p>
<script....>
q1 = document.getElementById("p1");
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = "x&sup8">';
</script>
However I need to add in the superscript when a button is pressed. So I have something like:
<p id = "p1"><input type = "text" name = "var_1" id = "i_var_1" value = "0"></p>
<input type = "button" id = "i_button" value = "Add the superscript" onclick="Add_Superscript()";>
<script.....>
function Add_Superscript()
{
q1 = document.getElementById("p1");
b1 = document.getElementById("i_var_1");
c1 = b1.value.toString() + "&sup8";
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = c1.value>';
}
</script>
The above code does not reproduce the superscript properly.
Anyone any ideas? Thanks in advance for comments.
Not sure this is what you want, but it adds &sup8 to whatever is in the input box.
function Add_Superscript() {
q1 = document.getElementById("p1");
b1 = document.getElementById("i_var_1");
c1 = b1.value.toString() + "&sup8";
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = "' + c1 + '">';
}
<p id="p1">
<input type="text" name="var_1" id="i_var_1" value="0">
</p>
<input type="button" id="i_button" value="Add the superscript" onclick="Add_Superscript()" ;>
I don't know what you're trying to do but maybe it's because of the c1.value ! Try:
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value =' + c1 + '>';
You have several typos in your code and a lot of unnecessary code as well. You just need to set up a click event handler on the button that populates the value of the pre-existing input. No need to create a new input.
A few notes:
When you were trying to create the new input element (which it turns out you don't need to do in the first place), you had the entire thing as a string. You need to inject the dynamic value into that string, by terminating the string, concatenating the new value in and then concatenating the closing of the string, like this:
q1.innerHTML = '<input type="text" name="var_1a" id="i_var_1a" value=' + c1.value + '>';
Next, it's best to use good naming conventions for elements and variables. Prefix an id and name with something that describes the "type" of thing the element is. Use btn (button), txt (textbox), chk (checkbox), rad (radio button), etc. And don't use _ (that's a very old convention). Instead use "camelCase". Further, with form elements, you need to give them a name for form submission purposes, but it is also a good idea to give them and id for CSS and JavaScript purposes. Use the same id that you used for name so that you don't have two different names for the same thing.
Lastly, don't configure your HTML elements to event handlers via HTML attributes (onclick, onmouseover, etc.). Doing this creates global anonymous functions that alter the this binding in the callback function, it creates "spaghetti code" that is hard to scale and debug and it doesn't follow the W3C DOM Event specification. Instead, do all the work in JavaScript and use .addEventListener() to connect functions to events.
// Get references to the relevant DOM elements
var btn = document.getElementById("btnGo");
var input = document.getElementById("txtInput");
// Set up a click event handling function
btn.addEventListener("click", add_Superscript);
function add_Superscript(){
// Create a new value that is the old value plus a "superscript" value
var newVal = input.value + "&sup8";
// Update the input with the new value:
input.value = newVal;
}
<p>
<input type="text" name="txtInput" id="txtInput" value="0">
</p>
<input type = "button" id="btnGo" value="Add the superscript">

Categories