I have inputs where user can enter numbers and whenever user puts comma between numbers I want to make new Object.
For example, user insert "23, 24, 25" and presses enter, I want to get 3 objects(23, 24, 25) and push them in array.
I am not sure if this is what you want, but you could use a html form to trigger a function like this:
var myArray = [];
function createObject(id) {
return {
id: id
}
}
function pushToObjArray() {
document.getElementById("objectIds").value
.split(",").forEach(function(id) {
var myObj = createObject(id);
myArray.push(myObj);
});
console.log(myArray);
}
<form action="javascript: pushToObjArray()">
<input type="text" id="objectIds" />
<input type="submit" value="GO!">
</form>
Fiddle: https://jsfiddle.net/qydkpmrw/
Reference Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
str.split(separator) will return array for you.
let input = "23,24,25";
let data = input.split(",");
console.log(data);
Related
Every time a user types something into a search field, I want it to be added to an empty array I've created. For some reason, my current code only adds an empty string to the array but not the string itself:
Javascript
var myArray=[];
var submit = document.getElementById("submit");
var result = document.getElementById("result").value;
submit.addEventListener("click", function() {
myArray.push(result);
})
HTML
<input id="result" type="text"><button id="submit">Submit</button>
I'm using this autofill function which grabs a value from the input descricaoItem(description), send it to a query and fill the other input field with the codigo(code) value, from the database. The code is below:
$(document).ready(function() {
$('#descricaoItem0').change(function () {
$.post('mandaDescricao.php',
{
descricao: document.getElementById('descricaoItem0').value
},
function(data){
var obj = $.parseJSON(data);
$('#codigoItem0').val(obj.codigo);
});
});
});
This one works fine, but I want to create those inputs dynamically, when the user presses a button. Already have this function, and the inputs are created with different ID's (descricaoItem0, descricaoItem1, and so on...) which are related with (codigoItem0, codigoItem1,...). But, with these inputs dynamically created I can't find a way to use the above function.
Could you please, help me? I don't want to copy and paste this function 'till descricaoItem20.
Wrap your event assigner in a function!
Every time a new input is added, fire this function and pass the correct id number.
function assignOnChangeToInput(id) {
$('#descricaoItem' + id).change(function() {
$.post('mandaDescricao.php', {
descricao: document.getElementById('descricaoItem' + id).value
},
function(data) {
var obj = $.parseJSON(data);
$('#codigoItem' + id).val(obj.codigo);
});
});
});
}
Create a JSON object that consists of an Array of Input Objects.
[ {id: '#codigoItem0'}, {id: '#codigoItem1'}, {id: '#codigoItem2'} ]
Use a forEach loop to apply the change event listener to each individual node.
var JSONObj = [ {id: '#codigoItem0'}, {id: '#codigoItem1'}, {id: '#codigoItem2'} ]
JSONObj.forEach(function(input) {
var id = input.id;
$(id).change(function(e) {
$.post('mandaDescricao.php',
{
descricao: document.getElementById(id).value
},
function(data){
var obj = $.parseJSON(data);
$(id).val(obj.codigo);
});
});
})
})
Might be worth making a more detailed JSON Array of inputs where an input-Object might look like :
{
id: 'inputID',
name: 'inputName'
val: 'Foo',
placeholder: 'Bar',
callback: '_aCallbackMethod()'
}
And then you can create input elements based on an Array of those detailed inputs and handle them as Objects rather than needing to query the DOM so much with $(blah). :-)
You don't need to use the ID (which will help with your dynamic problem) You can add the event to all inputs with a class and then use this inside the input change event for the input the user is interacting with, for example
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
$(document).ready(function() {
$('.descricaoItem').on("input", function() {
var descricaoValue = $(this).val();
var self = this; // save context of this
$.post('mandaDescricao.php', {
descricao: descricaoValue
},
function(data) {
var obj = $.parseJSON(data);
$(self).val(obj.codigo);
});
});
});
Here is a minimal example (without the POST request)
$(document).ready(function() {
$('.descricaoItem').on("input", function() {
var descricaoValue = $(this).val();
var self = this; // save context of this
$(self).val("codigo obj: " + Math.floor(Math.random() * 100) + 1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
Sample code.
<script>
var app = (function () {
var config = {
X:345,
Y:543,
Z: [
[1,3],
[2,4],
[3,6]
]
};
}());
</script>
Here I want to pass values into Z dynamically from input field. How can i do it? How to access such kind of an object from html using onclick event.
please provide any fiddle example or sample html and js code if you can. Thanks.
I've created an example where values are added to Z based on what you type in an input field. I hope this answers your question, if anything is unclear just ask.
var app = (function () {
var config = {
X:345,
Y:543,
Z: [
[1,3],
[2,4],
[3,6]
]
};
function onFormSubmitted(event) {
// Prevent the browser from actually submitting the form.
event.preventDefault();
const
input = document.getElementById('input');
// Make sure the input was found and it has a value in it.
if (input === null || input.value === '') {
return;
}
// Push the value in the input into Z.
config.Z.push(input.value);
// Reset the form.
event.target.reset();
}
function logConfig() {
console.log(config);
}
function init() {
const
form = document.getElementById('form');
if (form !== null) {
// Listen for the submit event to add the value in the input to Z.
form.addEventListener('submit', onFormSubmitted);
}
}
init();
// Return the logConfig method so it can be called from outside.
return {
logConfig
}
}());
const
logButton = document.getElementById('log');
// Whenever the log button is clicked, log the current app config.
logButton.addEventListener('click', event => {
app.logConfig();
});
<form id="form">
<input type="number" id="input"/>
<button>Add number</button>
</form>
<button id="log" type="button">log config</button>
I'm familiar with JavaScript, but not familiar with using it in the DOM. I'm trying to make a form that will accept an item name + properties and store it like I'm writing out the object below:
var grocery_list = {
"Banana": { category: "produce", price: 5.99 },
"Chocolate": { category: "candy", price: 2.75 },
"Wheat Bread": { category: "grains and breads", price: 2.99 }
}
Here is the sample HTML Form I have:
<form>
<input name="item"><br>
<input name="category"><br>
<input name="price"><br>
<input type="submit" value="do stuff">
</form>
How can I use JavaScript take the input above and push it to an Object (like above)?
Add a listener to the form, collect the values, build an object and add it to the grocery_list, e.g.
<script>
var grocery_list = {}
function addGroceryItem(form) {
grocery_list[form.item.value] = {category: form.category.value, price: form.price.value};
return false;
}
</script>
<form onsubmit="return addGroceryItem(this)">
<input name="item"><br>
<input name="category"><br>
<input name="price"><br>
<input type="submit" value="Add item">
<input type="button" value="Show list" onclick="console.log(grocery_list)">
</form>
Though I'd be tempted to use a plain button, not a submit button, and put the listener on the button's onclick handler.
This could be easily done with jQuery:
var objects = [];
$('form').on('submit', function(e){
var item = $('#item').val(), category = $('#category').val(), price = $('#price').val();
objects.push({item:{'category':category, 'price':parseFloat(price)}});
console.log(JSON.stringify(objects));
e.preventDefault();
});
By listenting to a submit event on the form, populating the object and pushing it to an object array. about reading the values from DOM, see the $('#input_id').val() which takes these values.
Assuming you though about pure JS, this could also be done:
var objects = [];
var form = document.getElementById('form');
form.onsubmit = function(e){
var item = document.getElementById('item').value, category =document.getElementById('category').value, price = document.getElementById('price').value;
objects.push({item:{'category':category, 'price':parseFloat(price)}});
console.log(JSON.stringify(objects));
e.preventDefault();
}
http://jsfiddle.net/70fnct9c/
UPDATE
as robg noted, storing the objects in an object instead of array could also be done easily:
var objects = {}
................
................
objects[item] = {'category':category, 'price':parseFloat(price)}
http://jsfiddle.net/70fnct9c/2/
I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"