get array data into input fields - javascript

I have asked this question one time but couldn't get any proper answer.So making the question simpler.Im using codeigniter
javascript function in view file
here the abc output looks like this
0:{a:'1',b:'2',c:'35'}
1:{a:'2',b:'3',c:'34'}
2:{a:'5',b:'1',c:'87'}
3:{a:'4',b:'3',c:'90'}
function test()
{
const show_div = document.getElementById('div_show');
const abc =[];
abc.push({a,b,c});
for (const data of abc){
const values = Object.values(data);
for (const value of values){
const input = document.createElement(
'<input type="text" name="a[]" value=" '+ value[0]+ ' " required>' +
'<input type="text" name="b[]" value=" '+ value[1]+ ' " required>' +
'<input type="text" name="c[]" value=" '+ value[2] + ' " required>'
);
input.innerText = value ;
show_div .appendChild(
input
);
}
}
}
I need to get this to the view
<form>
//there are more divs here
<div id='div_show'>
//need output like this
// 1 2 35
// 2 3 34
// 5 1 87
// 4 3 90
</div>
</form>
And then I want to pass a,b,c data to model
How can I get this data.Actually im creating this view output just pass the data in post method because in form submit its passing the data through action url without ajax.

You can try like this. You can add any input field with the array of object data.
I have separated each array item with a div so that you can design it with css or you can remove it if you don't need the div.
const data = [{a:'1',b:'2',c:'35'},
{a:'2',b:'3',c:'34'},
{a:'5',b:'1',c:'87'},
{a:'4',b:'3',c:'90'}];
function show() {
const container = document.getElementById("div_show");
let fields = '';
for(item of data) {
fields += '<div class="field_row">';
Object.keys(item).forEach( key => {
fields += `<input type="text" name="${key}[]" value="${item[key]}" required>`
})
fields += '</div>';
}
container.innerHTML = fields;
}
show()
<form><div id="div_show"></div></form>

Kind of ES6 way
const data = [{a:'1',b:'2',c:'35'},{a:'2',b:'3',c:'34'},{a:'5',b:'1',c:'87'},{a:'4',b:'3',c:'90'}];
function show() {
const fields = data.map((obj) => {
const row = Object.entries(obj)
.map(([key, value]) =>`<input type="text" name="${key}-${value}" value="${value}">`)
.join('');
return `<div>${row}</div>`;
}).join('');
document.getElementById("div_show").innerHTML = fields;
}
show();
<form><div id="div_show"></div></form>

Can you please provide more specific details your exact output?
If you need just 3 input elements in side that div(#div_show), your inner loop is redundant, you can eliminate it and it would give you what you need.

Related

Loop through JSON name/value pair string to populate form input field values for edit mode

I'm trying loop through a json name/value pair string and populate generated input field values. Wanting this logic for edit mode. I feel I'm almost there but I'm only populating two fields. Oh, The input fields are in group of two (Title url and url itself)
// * Edit mode * - Populates input fields with current stored urls
let wrapper = '#wrapper';
let urlJson = '{\"Hello World\": \"www.google.com\"\r\n}'
if (urlJson) {
var result = $.parseJSON(urlJson);
var urlTitle = $('[name="url_title[]"]');
var url = $('[name="url[]"]');
$.each(result, function(key, value) {
console.log('key: ' + key + ' - value: ' + value);
urlTitle.val(key);
url.val(value);
$(wrapper).append(
'<div id="title_and_url_group"><br><hr class="title_and_url"><div class="col-md-9 title_and_url">' +
'{!! Form::text("url_title", old("url_title"), ["class"=>"form-control", "name" => "url_title[]", "placeholder"=>"Title of URL"]) !!}' +
'</div><br><div class="col-md-9 title_and_url">' +
'{!! Form::text("url", old("url"), ["class"=>"form-control", "name" => "url[]", "placeholder"=>"Ex: http or https in url"]) !!}' +
'X</div></div>'
);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="url_title[]" value="Bike"> URL Title<br>
<input type="checkbox" name="url[]" value="Car"> URL<br>
<div id="wrapper"></div>
You are using laravel's form facade in your javascript method, Laravel facade is executed at the server before the processed web page is passed to the client.
Since you're looping through js at client, form facade will be rendered as plain text, no php function will work, you'll need to write down the mark up instead of using Form Facade.
Document.querySelector('#wrapper').innerHTML =
result.forEach((res, index)=>{
`<div id="title_and_url_group">
<br>
<hr class="title_and_url">
<div class="col-md-9 title_and_url">
<input type="text" name="url_title[${index}]" value="${res.url_title}" class="form-control">
</div>
<br>
<div class="col-md-9 title_and_url">
<input type="checkbox" name="url[${index}]" value="${res.url}" class="form-control">
X
</div>`
}
I have this so far. I can't seem to get them into the values into the input fields. Here's the code. When I do a console.log it iterates correctly.
// *** Edit mode *** - Populates url tile and url fields
if (url) {
var result = JSON.parse(url);
var url_title = $('[name="url_title[]"]');
var url = $('[name="url[]"]');
$.each(result, function(key, value) {
console.log('key: ' + key + ' - value: ' + value);
url_title.val(key);
url.val(value);
$(wrapper).append(
'<div id="title_and_url_group"><br><hr class="title_and_url"><div class="col-md-9 title_and_url">' +
'{!! Form::text("url_title", old("url_title"), ["class"=>"form-control", "name" => "url_title[]"]) !!}' +
'</div><br><div class="col-md-9 title_and_url">' +
'{!! Form::text("url", old("url"), ["class"=>"form-control", "name" => "url[]"]) !!}' +
'X</div></div>'
);
});
}

Don't append if string already contains OnChange

I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}

Prettify JSON object alert

I have a JSON object and when i alert it i get this:
and i want to get this:
function getNameById(id){
return usersArray.find(item => item.id === id).name;
}
var usersArray = [
{"id":"135","name":"Jenny"},
{"id":"162","name":"Kelly"}
];
$("#submit").click(function (e) {
var errors = {};
$(".validation").each(function(){
var worker_id = $(this).attr('id').replace(/[^\d]/g, '');
var w_name = getNameById(worker_id);
if(!errors[w_name]) errors[w_name] = [];
if ( $(this).val() == "" ) {
errors[w_name].push( $(this).attr('id').replace(/[^a-zA-Z]/g, '') + " must be filled!");
//errors[w_name].push("second number must be smaller than first");
}
if ( $(this).attr('id') == "second-"+worker_id && ($(this).val() > $('#first-'+worker_id+'').val())) {
errors[w_name].push("second number must be smaller than first");
}
});
alert(JSON.stringify(errors, null, 2));
e.preventDefault();
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
First<input id="first-135" class="validation" name="first" type="text" value="5"><br>
Second<input id="second-135" class="validation" name="second" type="text" value="8"><br>
Signature<input id="signature-135" class="validation" name="signature" type="text"><br>
<input id="submit" type="submit" value="Submit">
</form>
How can i achieve that?
Transform your object to a string like this
let obj = {
"Jenny" : [
"Second number must be smaller than first",
"Signature must be filled !"
]
};
let str = "";
Object.keys(obj).forEach(k => {
str += k + ":\n";
str += obj[k].join(",\n");
});
console.log(str);
Extract the data from the JSON data that you have in errors instead of running JSON.stringify directly. You should be able to get the data like this: errors["Jenny"] to get a list of the errors. Then combine them into a string according to your liking.
I honestly don't think your question has absolutely anything to do with JSON. The only reason why some JSON even shows up is because you're generating it for the alert():
alert(JSON.stringify(errors, null, 2));
// ^^^^^^^^^^^^^^ This generates JSON
If you want to concatenate some array items you can use a combination of the concatenation operator (+) and Array.join():
alert(w_name + ":\n" + errors[w_name].join(",\n"));
Tweak format to your liking.
var w_name = "Jenny";
var errors = {};
errors[w_name] = [];
errors[w_name].push("Second number must be smaller than first");
errors[w_name].push("Signature must be filled!");
alert(w_name + ":\n" + errors[w_name].join(",\n"));

passing/displaying values from JavaScript to HTML page

I have the following JS code which use's local storage to display the 'name' and 'age' entered previously:
This HTML code currently displays the date, time, name and age of a person in a table. how can i pass these values to be displayed in a HTML form as labels instead of in that table?
HTML only bringing back the start time, name and age aren't being displayed:
<div id="history_list"></div>
<div id="name"> </div>
<div id="age"></div>
JS:
function loadHistoryList() {
for(var i = numberOfHistory; i >= 1; i--) {
var historyData = new historyElement(db.getItem(i.toString()));
if(historyData === null) {
console.error('error');
continue;
}
$('#history_list').append(historyData.startTime);
$('#name').append(historyData.name);
$('#age').append(historyData.age);
}
}
instead of
var div = '<div id="history_element"><div id="element_title">' + historyData.startDate + ' ' + historyData.startTime + '</div><table>';
var div = '<div id="name"><tr><td>name: </td><td>' + historyData.name+ '</td></tr>';
var div = '<div id="age"><tr><td>age: </td><td>' + historyData.age+ '</td></tr>';
div += '</table></div>';
$('#history_list').append(div);
$('#name').append(div);
$('#age').append(div);
Do this:
$('#history_list').append(historyData.startTime);
$('#name').append(historyData.name);
$('#age').append(historyData.age);
In short: you can (and should in this case) simply add the desired value to the container (the DIV, Form field, or whatnot)
those three lines starting witn var div (...) are overwriting each previous line, but that is a side note.
Overall, you should read up more on JavaScript and/or JQuery.
To populate the form field First you have to add a form element like input field
HTML
<div id="history_list">
</div>
<input type="text" id="name" name="name">
JS
function loadHistoryList() {
for(var i = numberOfHistory; i >= 1; i--) {
var historyData = new historyElement(db.getItem(i.toString()));
if(historyData === null) {
console.error('error');
continue;
}
$('#name').val(historyData.name);
}
}

Value of checkbox is [object HTMLInputElement]

I have two forms right next to each other.
This right here is Form one
<form>
<input type="radio" id="genderOne" name="genderOne" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
Form 2 is simply the same, with the difference that the IDs of the checkboxes are genderThree and genderFour and the name is genderTwo. The checkbox has also another name "ageCheckTwo".
Now I want, if everything is filled in correctly to open up a php.site with the parameters the user typed in.
Everything works, except for the second form, but only the gender.
This is the JavaScript-code for that part
if(document.getElementById('genderOne').checked || document.getElementById('genderTwo').checked)
{
if(document.getElementById('genderOne').checked)
{
var genderOne = $('#genderOne').val();
urlString += "&genderOne=" + genderOne;
}
if(document.getElementById('genderTwo').checked)
{
var genderTwo = $('#genderTwo').val();
urlString += "&genderOne=" + genderTwo;
}
}
if(document.getElementById('genderThree').checked || document.getElementById('genderFour').checked)
{
if(document.getElementById('genderThree').checked)
{
var genderOne = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderTwo = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
}
And just to be sure, this is the second form
<form>
<input type="radio" id="genderThree" name="genderTwo" value="Mann"><label for="genderThree">Maennlich</label>
<input type="radio" id="genderFour" name="genderTwo" value="Frau"><label for="genderFour">Weiblich</label><br><br>
<input type="checkbox" id="ageCheckTwo" id="ageCheckTwo" name="ageCheckTwo"><label for="ageCheckTwo">Ist er/sie ueber 18?</label>
</form>
But, the URL is now, when I checked all parameters like this:
http://localhost/mojoGerman/questions.php?nameOne=fdgh&nameTwo=hj&genderOne=Mann&genderTwo=[object HTMLInputElement]
While it should display the gender of the second person at the end. What am I doing wrong?
Simple typographic errors here:
if(document.getElementById('genderThree').checked)
{
var genderThree = $('#genderThree').val();
urlString += "&genderThree=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderFour = $('#genderFour').val();
urlString += "&genderFour=" + genderFour;
}
This is why cutting and pasting is a bad idea. Make yourself a simple function:
function addIfChecked(name) {
var val = $('#' + name).val();
return val ? "&" + name + "=" + encodeURIComponent(val) : '';
}
urlString += addIfChecked("genderOne") +
addIfChecked("genderTwo") +
addIfChecked("genderThree") +
addIfChecked("genderFour");
or something like that. Better yet, give the checkboxes a class so that you can find them with a selector and iterate over them via jQuery.
var genderOne = $('#genderThree').val(); // get value in genderThree here
urlString += "&genderTwo=" + genderThree;
Try this -
if(document.getElementById('genderThree').checked) {
var genderThree = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked) {
var genderFour = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
The issue is using the wrong variable names for genderThree and genderFour
But you could simplify the whole thing to
$('input[type="radio"][name^="gender"]:checked').each(function(){
urlString += '&' + this.name + '=' + this.value;
});
I have not understood completely what are you trying to do , but seeing at your code, I think It can be optimised by using different practice
<form>
<input type="radio" id="genderOne" name="genderOne[]" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne[]" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
If you want to have same key on your query string genderOne , you can explicity declare your name as array in the name attribute. On your php script you can get this value using GET method to obtain those values
//php
echo $_GET['genderOne'][0];//returns first checked gender value
echo $_GET['genderOne'][1];//returns 2nd checked gender value
You don't even need the javascript for this if I understood what you are trying to achieve.

Categories