pushing values in array in hidden field - javascript

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.

Related

Loop data fetched from val()

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"}]'>

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">

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

check two input element's names are different or not using javascript

I have an array in which the values of check boxes gets stored on user click. Now I need to use an if loop for a particular logic in my code to give a condition whether the elements inside the array have same name (group check box name) or different names. How can I do it in javascript or jquery?
var Array = ['bob','bob','smith','smith','john','john'];
var UniqueArray = new Array();
var obj = {};
$.each(Array , function(i,value) {
if(!obj[value]) {
obj[value] = true;
UniqueArray.push(value)
}
})
Are you expecting something like this.
$(function() {
// create an array.
var elements = [];
// click event for all input of type checkbox.
$('[type="checkbox"]').on("click", function() {
// restrict no. of items to be inserted into the array to 2
if (elements.length <= 2) {
// push each element to array.
elements.push($(this));
}
// compare name attribute of 1st and 2nd element in array.
if (elements.length == 2) {
if (elements[0].attr('name') == elements[1].attr('name')) {
alert('elements with same name');
} else {
alert('elements with differnt name');
}
//clear all elements from array.
elements = [];
//clear all checkbox.
$('input:checkbox').removeAttr('checked');
}
// if you want to iterate through array use $.each
/*$.each(elements,function(index,data){
alert(data.attr('name'));
});
*/
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
first checkbox - :"myCheckBox":
<input type="checkbox" name=myCheckBox id="cbxCustom1" />
<br>second checkbox - :"myCheckBox":
<input type="checkbox" name=myCheckBox id="cbxCustom2" />
<br>third checkbox - :"myCheckBoxNew":
<input type="checkbox" name=myCheckBoxNew id="cbxCustom3" />

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