Multiple fileUpload Problem for different indexes - javascript

I am having problem with my jquery code
I am dynamically adding multiple <input type='file' multiple> each of them name parameter is change means 1st one is
color_images_1 <input type='file' multiple name='color_images_1'>
and will dynamically increase this 1 okay so every color has multiple images of its own color.
So basically I want to achieve this and I am using jS new FormData for it so here's my problem I am appending multiple files to formdata.
$(function() {
let $i = 1;
$(document).on('click', '.btn_color', function() {
$i++;
$('.color_wrapper').append("<div class='form-group'><label for='color_name" + $i + "'>Color Name</label><input type='text' name='color_name" + $i + "' id='color_name" + $i + "' class='form-control'></div><div class='form-group'><label for='sku" + $i + "'>Sku</label><input type=text class='form-control' id='sku" + $i + "' name='sku" + $i + "'></div><div class='form-group'><button type='button' class='btn btn-link pull-right btn_color'>Add more colors</button><label for='color_images" + $i + "'>Color Images</label><input type='file' name='color_images" + $i + "' multiple id='color_images" + $i + "' class='form-control'></div>");
});
$("#product_form").on('submit', function(e) {
e.preventDefault();
let files = '';
let form = document.getElementById('product_form');
let formData = new FormData(form);
files = $("#color_images" + $i).get(0).files;
$(files).each(function(index, file){
formData.append("color_images_" + [$i],file);
});
formData.append('variable', $i);
$.ajax({
url: 'product_ajax.php',
method: 'post',
data: formData,
success: function(data) {
console.log(data);
},
contentType: false,
cache: false,
processData: false
});
});
});
Now I am getting just only one file if I give index so I am getting multiple files otherwise not
[color_images_1] => Array
(
[name] => dht_feed.dat
[type] => application/octet-stream
[tmp_name] => D:\xampp\tmp\php4E11.tmp
[error] => 0
[size] => 2
)
)
what I want
color_images_1 its all multiple files
color_images_2 its all multiple files
html Code:
<form id="product_form" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="product_name">Product Name</label>
<input type="text" class="form-control" name="product_name" id="product_name">
</div>
<div class="form-group">
<label for="product_slug">Product Slug</label>
<input type="text" class="form-control" name="product_slug" id="product_slug">
</div>
<div class="form-group">
<label for="product_price">Product Price</label>
<input type="text" class="form-control" name="product_price" id="product_price">
</div>
<div class="form-group">
<label for="product_description">Product Description</label>
<textarea class="form-control" name="product_description" id="product_description"></textarea>
</div>
<div class="form-group">
<label for="color_name1">Color Name</label>
<input type="text" name="color_name1" id="color_name1" class="form-control">
</div>
<div class="form-group">
<label for="sku1">Stock Keeping Unit</label>
<input type="text" name="sku1" id="sku1" class="form-control">
</div>
<div class="form-group">
<button class="btn btn-link pull-right btn_color" type="button">Add more colors</button>
<label for="color_images1">Color Images</label>
<input type="file" name="color_images1" multiple id="color_images1" class="form-control">
</div>
<div class="color_wrapper">
</div>
<button class="btn btn-primary btn-block" type="submit">Add Product</button>
</form>

You need to iterate i as well.
Please replace below code
files = $("#color_images" + $i).get(0).files;
$(files).each(function(index, file){
formData.append("color_images_" + [$i],file);
});
formData.append('variable', $i);
With this one
for (var j = 1; j <= $i; j++) {
files = $("#color_images" + j).get(0).files;
$(files).each(function(index, file) {
formData.append("color_images_" + [j], file);
});
formData.append("variable", j);
}

Related

Finding which is selected without Javascript radio button value

Codepen https://codepen.io/mehmetmasa-the-selector/pen/RwBQbOr
When I click the button, I add a new field. One of the added fields (radio button) needs to be selected. But since the user can add/delete, I can't give the value value.
HTML Code
<div id="answer">
<div class="form-group d-flex">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap </label>
</div>
<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">
<button class="btn btn-primary ml-3 col-md-1" type="button" id="addAnswer">Yeni Cevap</button>
</div>
</div>
JS Code
$('#addAnswer').on('click', function() {
$('<div class="form-group d-flex">' +
'<div class="form-check">' +
'<label class="form-check-label">' +
'<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap' +
'</label>' +
'</div>' +
'<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">' +
'<button class="btn btn-danger ml-3 col-md-1 deleteAnswer" type="button" >Cevabı Sil</button>' +
'</div>').appendTo('#answer');
});
$('#addQuestion').on('click', function() {
let answer = [];
$('#answer .form-group').map(function(i, val) {
if ($(val).find('.answer').val().length > 0)
answer.push({
name: $(val).find('.answer').val(),
trueAnswer: $(val).find('.trueAnswer').val()
});
});
let categoryID = $('#category').val();
let question = $('#question').val();
let questionNo = $('#questionNo').val();
let colorpicker = $('#colorpicker').val();
let formData = new FormData();
formData.append("categoryID", categoryID);
formData.append("question", question);
formData.append("questionNo", questionNo);
formData.append("colorpicker", colorpicker);
for (var i = 0; i < answer.length; i++) {
formData.append('answer' + [i], answer[i].name);
formData.append('answer' + [i], answer[i].trueAnswer);
}
How can I find which answer the user chose?

Use data-attribute values to select form fields and autofill from MySQL

I am trying to succeed with populating dynamically generated form fields from a database via xmlhttp. First row is "static" and when I type in the SKU-field the name[] field gets the data correct from the database. When I click the "#addrow" button a new row is added and here I want to be able to type in the SKU-field and have the name[] field get data from the database. Right now what happens is that the row above gets updated when I type in the SKU-field.
I have added data-attributes for the SKU-field and name-field and also a counter so I somehow could select the field data-names and from this be able to parse the value to the right name-field in the right row?
I have tried to add a variable and see if I can get this to parse the database value to the right name-field, but it does not work:
var field = "name" + $(this).attr("data-dynid");
field.value = myObj[0];
I just need to figure out how to have the code recognize which SKU-field I am typing in (with the data-attribute counter) and from the counter select the name-field with the same counter value.
*** UPDATE ****
So I found a way to locate a form field from data-attribute and assign a value to it. Now I need to figure out how to have the code recognize the SKU field I am typing in, in order to retreive the SKU data-attribute number and use this dynamically to locate the form field to parse the data to.
var elements = document.querySelectorAll('[data-dynname="name-1"]');
elements[0].value = myObj[0];
HTML
<form method="post" action="">
<div class="row">
<div class="col-lg-12">
<div id="inputFormRow">
<div class="row">
<div class="form-group col-md-2">
<label class="form-control-label" for="sku">Varenummer</label>
<input type="text" class="form-control searchInput" name="sku[]" placeholder="Varenummer" autocomplete="off" onkeyup="GetDetail(this.value)" value="">
</div>
<div class="form-group col-md-4">
<label class="form-control-label" for="name">Navn</label>
<input type="text" class="form-control name" name="name[]" placeholder="Navn" autocomplete="off">
</div>
<div class="form-group col-md-2">
<label class="form-control-label" for="content">Tekst</label>
<input type="text" class="form-control" name="text[]" placeholder="Tekst" autocomplete="off">
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="normalprice">Normalpris</label>
<input type="text" class="form-control" name="beforeprice[]" placeholder="Normalpris" autocomplete="off">
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="offerprice">Tilbudspris</label>
<input type="text" class="form-control" name="offerprice[]" placeholder="Tilbudspris" autocomplete="off">
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="size">Størrelse</label>
<select class="form-control" name="size[]" placeholder="Størrelse" autocomplete="off">
<option value="A4" selected="">A4</option>
<option value="A5">A5</option>
<option value="A10">A10</option>
</select>
</div>
<div class="form-group col-md-1">
<label class="form-control-label" for="removeRow"> </label>
<button id="removeRow" type="button" class="form-control btn btn-danger">Fjern</button>
</div>
</div>
</div>
<div id="newRow"></div>
<button id="addRow" type="button" class="btn btn-info">Add Row</button>
</div>
</div>
</form>
Javascript
<script type="text/javascript">
// add row
var counter = 1;
$("#addRow").click(function () {
var html = '';
html += '<div id="inputFormRow">';
html += '<div class="row">';
html += '<div class="form-group col-md-2">';
html += '<input type="text" class="form-control searchInput" data-dynid ="' + counter + '" name="sku[]" placeholder="Varenummer" autocomplete="off" onkeyup="GetDetail(this.value)">';
html += '</div>';
html += '<div class="form-group col-md-4">';
html += '<input type="text" class="form-control name" data-dynname ="name-' + counter + '" name="name[]" placeholder="Navn" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-2">';
html += '<input type="text" class="form-control" name="text[]" placeholder="Tekst" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<input type="text" class="form-control" name="beforeprice[]" placeholder="Normalpris" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<input type="text" class="form-control" name="offerprice[]" placeholder="Tilbudspris" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<input type="text" class="form-control" name="size[]" placeholder="Størrelse" autocomplete="off">';
html += '</div>';
html += '<div class="form-group col-md-1">';
html += '<button type="button" class="form-control btn btn-danger removeRow">Fjern</button>';
html += '</div>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
counter++;
console.log(counter);
});
// remove row
$(document).on('click', '.removeRow', function () {
$(this).closest('#inputFormRow').remove();
});
</script>
<script>
// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(str) {
if (str.length == 0) {
document.getElementsByName("first_name")[0].value = "";
return;
}
else {
// Creates a new XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
// Defines a function to be called when
// the readyState property changes
if (this.readyState == 4 &&
this.status == 200) {
// Typical action to be performed
// when the document is ready
var myObj = JSON.parse(this.responseText);
// Returns the response data as a
// string and store this array in
// a variable assign the value
// received to first name input field
//var el = document.getElementsByName('name[]')[0];
//var el = document.getElementsByClassName("name");
//var r2 = console.log(el).closest("name[]");
document.getElementsByName("name[]")[0].value = myObj[0];
//r2.value = myObj[0];
}
};
// xhttp.open("GET", "filename", true);
xmlhttp.open("GET", "pages/actions/load-products.php?user_id=" + str, true);
// Sends the request to the server
xmlhttp.send();
}
}
</script>

how fill the dynamically created dropdownlist with data from database using ajax and web service in asp.net c#

var index = 0;
function newitem() {
index++;
var objTo = document.getElementById('newitem')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass" + index);
var rdiv = 'removeclass' + index;
divtest.innerHTML = '<div class="col-sm-3 nopadding"><div class="form-group">
<select class="form-control" id="ddlitem' + index + '"name="ddlitem"><option
value="">--select--</select> </div></div><div class="col-sm-3
nopadding"><div class="form-group"> <input type="text"
class="form-control" id="txtquantity' + index + '"
name="txtquantity" value=""></div></div><div class="col-sm-3
nopadding"><div class="form-group"> <input type="text"
class="form-control" id="txtprice' + index + ' "name="txtprice"
disabled="disabled" value="" ></div></div><div class="col-sm-3
nopadding"><div class="form-group"><div class="input-group"> <input
type="text" class="form-control" id="txttotal' + index + '"
name="txttotal" disabled="disabled" value="" ><div
class="input-group-btn"> <button class="btn btn-danger"
type="button" onclick="remove_created_item(' + index + ');"> <span
class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button></div></div></div></div><div class="clear"></div>';
objTo.appendChild(divtest);
};
function remove_created_item(idOfCreatedItem) {
$('.removeclass' + idOfCreatedItem).remove();
}
It's messy, but I think I understand what you are doing.
After the objTo.appendChild(divtest); which inserts your select dropdown into the page, do your Ajax call to the API:
var copyOfIndex = index;
$.get( "/api/whatever", function( data ) {
$( "#ddlitem" + copyOfIndex ).html( data ); // data => can be the html containing all the <options>
alert( "Load was performed." );
});
not sure how your code is initialized above, but you should use a copy of your index (copyOfIndex here) to make sure the ajax call doesn't use an outdated value for index when the ajax call completes.
Also, looks like you need to close your before you insert the element in the DOM via objTo.appendChild(divtest);

Javascript I can't reach result variables in function

I called my datas with ajax then created variables in result but I cannot reach my variables in other function. How can I reach variables or create as a public function ? $("#btBilgileriAktar") is my new function .I want to take variables in this function.
Thank you for your helps.
$.ajax({
type: 'POST',
data: {
data: gripin
},
datatype: 'html',
url: '<?php echo site_url('
servis / bring_Cari '); ?>',
success: function(result) {
var obj = $.parseJSON(result);
// console.log(obj);
$.each(obj, function(key, value) {
// console.log(value);
$("table#cariler tbody").append("<tr class=\"cariKayit\"><td class=\"tdCariAdi\">" + obj[key].CARI_ISIM + "</td><td class=\"tdVergiNo\">" + ((obj[key].VERGI_NUMARASI == null) ? "" : obj[key].VERGI_NUMARASI) + "</td><td class=\"tdVergiDairesi\">" + ((obj[key].VERGI_DAIRESI == null) ? "" : obj[key].VERGI_DAIRESI) + "</td><td class=\"tdCariAdres\">" + ((obj[key].CARI_ADRES == null) ? "" : obj[key].CARI_ADRES) + "</td><td class=\"tdCariTel\">" + ((obj[key].CARI_TEL == null) ? "" : obj[key].CARI_TEL) + "</td><td class=\"tdCariIlce\">" + ((obj[key].CARI_ILCE == null) ? "" : obj[key].CARI_ILCE) + "</td><td class=\"tdCariIl\">" + ((obj[key].CARI_IL == null) ? "" : obj[key].CARI_IL) + "</td><td><input type=\"checkbox\" id=\"checks\"/></td></tr>");
});
$('#checks').on("click", function() { //Çalışıyor
var nAdi = $(this).parent().parent().find(".tdCariAdi").text();
var nVno = $(this).parent().parent().find(".tdVergiNo").text();
var nVdairesi = $(this).parent().parent().find(".tdVergiDairesi").text();
var nAdres = $(this).parent().parent().find(".tdCariAdres").text();
var nTel = $(this).parent().parent().find(".tdCariTel").text();
var nIlce = $(this).parent().parent().find(".tdCariIlce").text();
var nIl = $(this).parent().parent().find(".tdCariIl").text();
});
$('#btBilgileriAktar').on('click', function() { //Buda seçimi çekiyor ama burada sıkıntı var verileri almıyor.
var tcLength = nVno.toString();
if (tcLength.length == 11) {
$("#spTc").val(tcLength);
} else if (tcLength.length == 10) {
$("#spVno").val(tcLength);
} else {
$("#spTc").val("");
$("#spVno").val("");
}
$("#spCariAdi").val(nAdi);
$("#spVergiDairesi").val(nVdairesi);
$("#spAdres").val(nAdres);
$("#spTel").val(nTel);
$("#spIlce").val(nIlce);
$("#spIl").val(nIl);
});
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="tab-pane fade active in" id="musteri">
<div class="form-group">
<label class="control-label" for="focusedInput">Müşteri Adı</label>
<input class="form-control" id="spCariAdi" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Adres</label>
<input class="form-control" id="spAdres" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">İlçe</label>
<input class="form-control" id="spIlce" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">İl</label>
<input class="form-control" id="spIl" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Tel</label>
<input class="form-control" id="spTel" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Vergi Dairesi</label>
<input class="form-control" id="spVergiDairesi" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">TC Kimlik No</label>
<input class="form-control" id="spTc" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Vergi No</label>
<input class="form-control" id="spVno" type="text" value="">
</div>
</div>
Because you are declaring variables in another function. You need global variables for accessing them from different function.
var nAdi = ''; //global var declaration
$('#checks').on("click", function() { //Çalışıyor
nAdi = $(this).parent().parent().find(".tdCariAdi").text(); //assigning value
});
$('#btBilgileriAktar').on('click', function() {
$("#spCariAdi").val(nAdi); // retrieving value
});

Clearing an input field on blur

I'm attempting to clear all inputs with the class "new" on blur, but for some reason it just won't work. I've bashed my head at the this for three hours now, which obvious point am I missing? Relevant code below.
UPDATE 2
I tried changing out the switch-case block with corresponding if blocks, and they give the expected result. This eliminates the current problem, but I don't find it to be a viable answer to the original question which is why my origianl code with switch-case doesn't work.
UPDATE 1
After some research and experimenting I've discovered that I can clear all inputs with the class "new" as long as they're not inside my switch-case block. The selector I'm testing with is $('.new'), once inside the switch-case block this gives no visible effect.
#{
ViewBag.Title = "Viser infrastruktur";
Layout = "~/Views/Shared/_SuperOfficeLayout.cshtml";
}
<table class="table table-striped compact hover row-border">
<thead>
<tr>
<th>Produsent</th>
<th>Modell</th>
<th>Serienummer</th>
<th>Firmware</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="manufacturer" placeholder="Produsent" value="" />
<input type="hidden" class="autosave new" name="id" value="" />
<input type="hidden" class="autosave new" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="model" placeholder="Modell" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="serialNumber" placeholder="Serienummer" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave new" name="firmware" placeholder="Firmware" />
</div>
</td>
</tr>
#foreach (var infrastructure in Model.Infrastructures)
{
<tr>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="manufacturer" placeholder="Produsent" value="#infrastructure.Manufacturer" />
<input type="hidden" class="autosave" name="id" value="#infrastructure.Id" />
<input type="hidden" class="autosave" name="superOfficeCustomerId" value="#Model.SuperOfficeCustomerId" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="model" placeholder="Modell" value="#infrastructure.Model" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="serialNumber" placeholder="Serienummer" value="#infrastructure.SerialNumber" />
</div>
</td>
<td>
<div class="control-group">
<input type="text" class="col-md-12 form-control autosave" name="firmware" placeholder="Firmware" value="#infrastructure.Firmware" />
</div>
</td>
</tr>
}
</tbody>
#section SpecializedScripts
{
<script type="text/javascript">
function saveSettings(element, ajaxUrl, ajaxType) {
var fields = $(element).closest('tr').children('td').children('div').children('.autosave');
var abort = false;
var ajaxData = {};
$(fields).each(function () {
abort = ($(this).val() == '' || $(this).val() == null);
backgroundColor = abort == true ? '#d9534f' : '#f9f598';
$(this).css('background-color', backgroundColor).css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
ajaxData[$(this).prop('name')] = $(this).val();
});
if (abort == true) {
return false;
}
$.ajax({
url: ajaxUrl,
type: ajaxType,
data: ajaxData
}).success(function (data, textStatus, jqXHR) {
$(fields).each(function() {
$(this).css('background-color', '#5cb85c').css('color', '#ffffff').stop().animate({ 'background-color': '#ffffff', 'color': '#000000' }, 1500);
});
switch(data.status)
{
case 'Deleted':
$(element).closest('tr').remove();
break;
case 'Added':
var tableBody = $('tbody');
var html = '<tr>';
for (var field in data.result) {
if (field == 'id' || field == 'superOfficeCustomerId')
{
html += '<input type="hidden" class="autosave" name="' + field + '" value="' + data.result[field] + '" />';
}
else {
html += '<td>'
+ '<div class="control-group">'
+ '<input type="text" class="col-md-12 autosave form-control" name="' + field + '" value="' + data.result[field] + '" />'
+ '</div>'
+ '</td>';
$('input.new[name=' + field + ']').val('');
}
}
html += '</tr>';
$(tableBody).append(html);
case 'Modified':
$(fields).each(function () {
$(this).val(data.result[$(this).prop('name')]);
});
break;
}
}).fail(function () {
});
}
$(document).on('blur', 'input.autosave', function () {
saveSettings($(this), '/Link/SaveInfrastructure', 'POST');
});
$(document).on('change', 'input.new', function () {
});
</script>
}
Something like this should work:
$('input.new').on('blur', function() { $(this).val(''); $(this).text(''); });
just make sure the input exists when you bind the event otherwise you can do:
$(document).on('blur', 'input.new', function() { $(this).val(''); $(this).text(''); });
For vanilla JavaScript, you can use
<input onBlur={(event) => { event.target.value = ''; }} />

Categories