Oleksandr Pobuta
Oleksandr Pobuta

Reputation: 405

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 +`'>`;

Upvotes: 0

Views: 129

Answers (4)

Alen Androsevic
Alen Androsevic

Reputation: 97

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'

Upvotes: 0

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

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';

Upvotes: 1

Ricardo Rocha
Ricardo Rocha

Reputation: 16216

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)

Upvotes: 3

Taplar
Taplar

Reputation: 24965

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>

Upvotes: 3

Related Questions