Loop data fetched from val() - javascript

I am trying to get some data from a hidden element and loop through it and have it in an array.
The element looks like this:
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any""}]'>
Now when I grab this with jquery:
$(document).ready(function () {
var data = $(".test").val();
console.log(data);
//test loop
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
But it loops through every character instead of each {} in [].
What am I missing?
JS Bin for reference: https://jsbin.com/madaquyepa/edit?html,js,console,output

When you retrieve the input element's value, it is a string (a JSON actually). So, you will need to pass it through JSON.parse() first.
Note: there is an extraneous " near the very end of the string, which will cause an error if you try to parse it. Remember to fix it first.
$(document).ready(function() {
var data = JSON.parse($(".test").val());
console.log(data);
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any"}]'>
For an ES6 version that doesn't even use jQuery:
const data = JSON.parse(document.querySelector('.test').value);
console.log(data);
for (let datum of data) {
console.log(datum);
}
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any"}]'>

Related

Set value to input by calling javascript function

I am inserting a list of inputs through php loop.
For each input I need to get the value from database via ajax, For that I need to call a javascript function. I am not sure if it possible.
I am looking for something like this
<input ... value="javascript:getvalue(id)">
<script>
function getvalue(id) {
//set the value fron here
}
</script>
value attr just accepts strings more here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value.
You can use data-attributes or an id to assign the id and then get the value for it after its loaded.
Please check the below snippet
<input data-id="id1">
<input data-id="id2">
<input data-id="id3">
<script>
(function(){
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
inputs[i].value = getvalue(inputs[i].dataset["id"])
}
}())
function getvalue(id) {
return id;
}
</script>
$(document).ready(function(){
for(let i=0; i< $('.frmDatabase').length; i++) {
getvalue($('.frmDatabase').eq(i).attr('id'));
}
})
function getvalue(id) {
//ajax call
//set async false and in success bind value from db to id
$('#' + id).val(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txtTest1" class="frmDatabase">
<input id="txtTest2" class="frmDatabase">

Storing values from HTML Collection in array?

I'm new to all this and I really need help. I've been on this for hours now.
I have these checkboxes. I'm using a cfoutput to generate them and giving them each the value of SID from the query.
<cfoutput query="getvalues">
<div><input type="checkbox" name="chk" id=#getvalues.SID# value=#getvalues.SID# class="chkbxs">
</cfoutput>
<input type="button" name="PrintSelected" value="Print Selected" onclick="printTextArea()">
The only thing I want to do is get the values of these checkboxes and store them in an array. getElementsByClassName returns an html collection. I've been told I need to loop over the html collection and then store the values in a new array which is what I attempted below but this isn't working.
<script type="text/javascript">
function printTextArea() {
var myList = document.getElementsByClassName("chkbxs");
var newList = [];
for (var i = 0; i < myList.length; i++) {
newList.push(myList[i].value);
}
for (var j = 0; j < newList.length j++)
{
alert (newList[j]);
}
}
</script>
Any help would be appreciated.
Why are you setting the array items to console.log(myList[i].value);?
console.log() just returns undefined.
Just change the line to following:
newList[i] = myList[i].value;

javascript <form name="item"> and getElementsByTagName() error

I cannot explain why is this happening:
Uncaught TypeError: form_item.getElementsByTagName is not a function
Code Snippet:
var form_item = document.forms['item'];
var buttons_item = form_item.getElementsByTagName('button');
for (var i = 0; i < buttons_item.length; i++) {
if (buttons_item[i].type === 'submit') {
buttons_item[i].classList.add('someclass');
}
}
<form name="item" action="">
<button type="submit">Button</button>
</form>
If I change the form's name, it works without any errors.
What is wrong? Why?
Thanks
document.forms.item is a function that returns a form.
Your name conflicts with that.
var form_item = document.querySelector('form[name=item]');
var buttons_item = form_item.getElementsByTagName('button');
for (var i = 0; i < buttons_item.length; i++) {
if (buttons_item[i].type === 'submit') {
buttons_item[i].classList.add('someclass');
}
}
<form name="item" action="">
<button type="submit">BUTTON</button>
</form>
You can try it inside your browser's console type and send those commands:
document.forms["item"]
-
document.forms.item
Those commands means the same thing and ask for the document.forms.item() function.
And that's the workaround you need:
document.querySelector('form[name=item]');
The querySelector in JavaScript works like what you may know in JQuery selctors.
MDN: Document.querySelector() Returns the first Element within the document (using depth-first
pre-order traversal of the document's nodes|by first element in
document markup and iterating through sequential nodes by order of
amount of child nodes) that matches the specified group of selectors.
For your HTML markup you could use just use [name='item':
var form_item = document.querySelector('[name=item]');
var buttons_item = form_item.getElementsByTagName('button');
for (var i = 0; i < buttons_item.length; i++) {
if (buttons_item[i].type === 'submit') {
buttons_item[i].classList.add('someclass');
}
}
.someclass {
background: #6600ff;
color: white;
}
<form name="item" action="">
<button type="submit">Button</button>
</form>
The snippet above works as expected, but here is the question, why the item name was not working by the way you were going to access that!?
Because the item is a function for doctument.forms
W3S: item(index) Returns the element from the collection with the
specified index (starts at 0).
You can easily try it, open your web developer console (like Chrome DevTools) and type in: document.forms.item(0), you will get the first form of the document
By the way, this function also can be helpful to understanding better how really forms work
function getFormByName(theName) {
for (var i = 0; i < document.forms.length; i++) {
var form_item = document.forms.item(i);
if (form_item.name == theName) {
return form_item;
}
}
return false;
}
var form_item = getFormByName('item');
if (form_item) {
var buttons_item = form_item.getElementsByTagName('button');
for (var i = 0; i < buttons_item.length; i++) {
if (buttons_item[i].type === 'submit') {
buttons_item[i].classList.add('someclass');
}
}
}
.someclass{
background:gold;
color:red;
border:none;
}
<form name="item" action="">
<button type="submit">Button</button>
</form>

pushing values in array in hidden field

I had a following jquery code where i need to push values in a hidden field using comma if there are multiple items added.
i am using this code for pushing values but i am confused where and how do i add value in the hidden field so i can use the chosen value
jquery code
function initializeAutocomplete(obj){
obj.autocomplete({
source: function (request, response) {
var values = [];
for(var x = 0;x < predifined_cources.length;x++){
if(predifined_cources[x].text.indexOf(request.term)>-1)
values.push({"label":predifined_cources[x].text, "value":predifined_cources[x].id+"~YES"});
}
if(values.length==0){
$.post("customers.cfm",{"term":request.term})
.done(function(data){
try{
var obj = $.parseJSON(data),
values = [];
for(var x = 0; x < obj.length; x++){
values.push({"label":obj[x].text, "value":obj[x].id});
}
response(values);
}catch(e){
}
})
.fail(function(e){
});
}
else
response(values);
},
change: function(event, ui) {
if (!ui.item) {
$(this).next().val('');
}
},
select: function(event, ui) {
$(this).next().val(ui.item.value);
ui.item.value = ui.item.label;
}
});
}
initializeAutocomplete($('[selectCustomer]').first());
html code:
<input selectCustomer name="customer_name" class="form-control" id="customer_name_select" value="" placeholder="Select Customer..." data-rule-required="true" data-msg-required="Choose Customer"/>
<input type="hidden" value=""/>
As soon as the loop is complete that creates the array you would convert the array to string and set the value of the field
You could use JSON to keep array structure
$('#customer_name_select').val( JSON.stringify(array));
Or for comma separated string use Array.prototype.join()
$('#customer_name_select').val( array.join());
You can use the jQuery data-function. It allows you to add objects to DOM - elements without having to convert them manually to a string. It is only sufficient if you need the data only on client - side.

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

Categories