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'
Related
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);
}
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>
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">
I have a form. Within this form, I have an input field. I want to change some input field in the text area. I receive this form from an external source, so I can't change the html. How make this in js/jquery?
This is an example:
<label for="MMERGE12" class="MMERGE12-label"><span class="MMERGE12-label">categorie trattate</span>
<input id="yikes-easy-mc-form-1-MMERGE12" name="MMERGE12" placeholder="" class="yikes-easy-mc-text" type="text" value="">
<!-- description -->
<p class="form-field-description"><small></small></p>
</label>
SOLVED WITH THIS CODE :
var input = document.getElementById('yikes-easy-mc-form-1-MMERGE12'),
textarea = document.createElement('textarea');
textarea.id = input.id;
textarea.cols = 40;
textarea.rows = 5;
textarea.value = input.value;
textarea.name = input.name;
input.parentNode.replaceChild(textarea, input);
//Create a new textarea
var textarea = jQuery("<textarea></textarea>");
//Select the input
var input = jQuery("#yikes-easy-mc-form-1-MMERGE12");
//Asign the value, id, name from the input to the textarea
textarea.val(input.val());
textarea.attr('id', input.attr('id'));
textarea.attr('name', input.attr('name'));
//You can copy any other attribute you like here
//Finally do the replacement
input.reaplceWith(textarea);
you will probably need to wrap this in ready wrapper jQuery(document).ready(function() { /* code here */ }) if you do it on load or if you load it with ajax just execute this code after the data has been attached to the DOM
Try this
$(document).ready(function () {
var input = $("#yikes-easy-mc-form-1-MMERGE12");
var textArea = $("<textarea></textarea>").attr({
id: input.attr("id"),
name: input.attr("name"),
value: input.val()
});
// class is set separately because "class" is a reserved word ...
textArea.attr("class", input.attr("class"));
//insert textarea right after original input, and remove input
input.after(textArea).remove();
});
I have an empty form that needs to be filled with what I'd like to call mini-forms dynamically based on a condition. For example,this can be a form that asks for the names and locations of restaurants. Now, based on the number of restaurants(let's say 'm'), I'd like to add to the big form 'm' mini-forms that asks for the name and location. How can I use jQuery to create each of these mini-forms, that take in the name and the location of the restaurant and append them each to the big form. The html would look something like this. But I need to create this dynamically based on how many forms the user would need, and if he would need any.
Edit - I have learned that we cannot nest forms. I have renamed the inner 'form' elements to 'div'.
<form>
<div id = 1>
Name: <input type = "text" name = "name">
Location: <input type = "text" name ="location>
</div>
<div id = 2>
Name: <input type = "text" name = "name">
Location: <input type = "text" name ="location>
</div>
...
</form>
First you need to look for changes to the input where the user enters the number of restaurants:
$('#noofrestaurants').change(function(){
Then you need to loop through the number inputted and create new inputs each time:
var restaurants = $('#noofrestaurants').val();
for (var i = 0; i < restaurants; i++){
$('#miniformcontainer').append('<input type="text" name="rest_name[]"/><input type="text" name="rest_loc[]"/>');
}
});
You could try something like this:
<script>
function addMiniForms(n)
{
for (i=0; i<n ; i++)
{
var $div = $("<div id='" + i + "'></div>");
var $labelName = $("<label for='name" + i + "'>Name</label>");
var $inputName = $("<input type='text' id='name" + i +' />");
var $labelLocation = $("<label for='location" + i + "'>Location</label>");
var $inputLocation = $("<input type='text' id='location" + i +' />");
$div.append($labelName);
$div.append($inputName);
$div.append($labelLocation);
$div.append($inputLocation);
$("#containerid").append($div);
};
};
</script>
I have not tested this code, so it might need some tweaking.
You can't nest forms. If you want to have repeated inputs in a form, give them array-style names:
<div id = 1>
Name: <input type = "text" name = "name[]">
Location: <input type = "text" name ="location[]">
</div>
The back-end should convert these into arrays. For instance, PHP will fill in $_POST['name'] with an array of all the Name inputs.
The jQuery looks like:
divnum++;
$("form").append("<div id='"+divnum+"'>Name: <input type='text' name='name[]'">Location: <input type='text' name='location[]'></div>");