Previous fields text disappears when adding new one with select2 ajax - javascript

I was using select2 plugin on my input box to search items from the database using AJAX based on what the user type on it. It was working fine, I can search Items on it and select it when its available, but my problem is whenever I add new rows on my table the previous item fields "text" will be gone, I'm making a table where you can add/remove rows dynamically so here is my HTML:
<td><input name='product[0][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>
and my javascript:
function addRow(){
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
rowArrayId = rowArrayId + 1;
};
$(".itemSearch").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
here are some screenshots:
1st state:
2nd state: when searching item on the input box
3rd state: after adding new row on my table
What can be the issue?

The same id value is used for the input elements as rows get added.
It is best to have unique id within the page.

I would guess that every time you call .select2(), that all the selects get reset to the original state. You could only call the constructor on the new box by limiting the scope.
To update only the new select2s you should change the following.
See this example (untested, please adjust):
var newHtml = $("<h1>Code to be appended here</h1>");
newHtml.appendTo('#tblItemList tbody');
$('.itemSearch', newHtml).select2(/* ... */)
As an alternative you could try "freezing" the state by applying the "selected" attribute to all boxes before you call the constructor.
See this example (untested, please adjust)
$('.itemSearch').each(function(){
var val = $(this).val();
$(this).find('option[value='+val+']').attr('selected', 'selected');
})

Related

unable to add select element in html table using jquery

I was populating my tabular data from server through ajax using json. I want to create my HTML table row dynamically using jquery and every row must contain html elements like input type='text' and select dropdowns. I was able to create textboxes in columns, but I was not able create select dropdowns in columns. Here is my js code:
function loadFunction(){
$.ajax({
type : "GET",
url : "s3.do",
data : "",
success : function(data){
alert("success");
for(var i=0;i<data.length;i++){
var ispSelect = $("<select></select>");
var idProofSelect = $("<select></select>");
var dataArr = data[i];
var id = dataArr.id;
var name = dataArr.name;
var address = dataArr.address;
var isp = dataArr.lsIsp;
var idproof = dataArr.lsIdProof;
$.each(isp,function(index,product){
$("<option>").val(product.id).text(product.name).appendTo(ispSelect);
});
$.each(idproof,function(index,product){
$("<option>").val(product.id).text(product.name).appendTo(idProofSelect);
});
$("#tab tr:last").after("<tr><td><input type='checkbox' value='"+id+"'/></td><td><input type='text' value='"+name+"'/></td>"
+"<td><input type='text' value='"+address+"' /></td>"
+"<td>"+ispSelect+"</td>"
+"<td>"+idProofSelect+"</td>"
+"</tr>");
}
},
error : function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
}
the above code created below HTML table structure where under ISP and ID-Proof columns I am getting [Object Object], whereas I expected it to create <select> options for me. How can I resolve this issue. I am not that fluent with Jquery concepts. Is it the right way of what I am trying to do.
You add jQuery object to string - this wrong. Try:
$("#tab tr:last").after("<tr><td><input type='checkbox' value='"+id+"'/></td><td><input type='text' value='"+name+"'/></td>"
+"<td><input type='text' value='"+address+"' /></td>"
+"<td>"+ispSelect[0].outerHTML+"</td>"
+"<td>"+idProofSelect[0].outerHTML+"</td>"
+"</tr>");
}
When you do "some string" + Object - Object is being converted to String, that's why you get [object Object]
You need to add ids to each <td>, and then append the select boxes:
$("#tab tr:last").after("<tr><td><input type='checkbox' value='"+id+"'/></td><td><input type='text' value='"+name+"'/></td>"
+"<td><input type='text' value='"+address+"' /></td>"
+"<td id='ispSelect_'" + i + "></td>"
+"<td id='idProofSelect_'" + i + "></td>"
+"</tr>");
$("#ispSelect_" + i).append(ispSelect);
$("#idProofSelect_" + i).append(idProofSelect);

How to get a cell value in a row of table use javascript?

I want to get all the cell value in a row of a table. but what i wrote here is just to get the first row's cell in my table. I want to get the cell value by the row that selected. Thank you and please help.
var updateUser = function(e) {
var nRow = $(this).parents('tr')[1];
var jqTds = $('input', nRow);
var id = jqTds[1].value;
var name = jqTds[2].value;
var address = jqTds[3].value;
var username = jqTds[4].value;
var password = jqTds[5].value;
var role = jqTds[6].value;
}
And i also used jquery and ajax for it.
$.ajax({
url: 'http:/localhost/api/semuaorang',
dataType: 'text',
method: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(response){
obj = JSON.parse(response);
for (var i = 0; i < obj.message.length; i++) {\
tu = $('<tr/>');
tu.append("<td><input type='text' name='name' class='foo' readonly value='"+obj.message[i].Id+"'></td>");
tu.append("<td><input type='text' name='name' value='"+obj.message[i].Nama+"'></td>");
tu.append("<td><input type='text' name='name' value='"+obj.message[i].Alamat+"'></td>");
tu.append("<td><input type='text' name='name' value='"+obj.message[i].Username+"'></td>");
tu.append("<td><input type='text' name='name' value='"+obj.message[i].Password+"'></td>");
tu.append("<td><input type='text' name='name' readonly value='"+obj.message[i].role+"'></td>");
tu.append("<td> <a href=''><i class='fa fa-check' onclick='updateUser()'></i></a></td>")
$('#bodyTableUpdate').append(tu);
}
},
error: function(xhr, status, error){
alert(error);
},
complete: function(){
}
});
As you have attached the event handler using the onclick attribute the this keyword in the updateUser() function will reference the window, not the element which raised the event. To achieve what you require you would be better of using an unobtrusive delegated event handler. In jQuery, you can use on() to do this:
// in the $.ajax settings:
success: function(response) {
// Note JSON.parse is not required here - jQuery does it for you automatically
for (var i = 0; i < obj.message.length; i++) {
tu = $("<tr/>");
tu.append('<td><input type="text" name="id" value="' + obj.message[i].Id + '" readonly="true"></td>');
tu.append('<td><input type="text" name="name" value="' + obj.message[i].Nama + '"></td>');
tu.append('<td><input type="text" name="address" value="' + obj.message[i].Alamat + '"></td>');
tu.append('<td><input type="text" name="username" value="' + obj.message[i].Username + '"></td>');
tu.append('<td><input type="text" name="password" value="' + obj.message[i].Password + '"></td>');
tu.append('<td><input type="text" name="role" value="' + obj.message[i].role + '" readonly="true"></td>');
tu.append('<td><i class="fa fa-check"></i></td>')
$('#bodyTableUpdate').append(tu);
}
},
// new click handler:
$('#bodyTableUpdate').on('click', '.update-user', function(e) {
e.preventDefault();
var $row = $(this).closest('tr');
var id = $row.find('input[name="id"]').val();
var name = $row.find('input[name="name"]').val();
var address = $row.find('input[name="address"]').val();
var username = $row.find('input[name="username"]').val();
var password = $row.find('input[name="password"]').val();
var role = $row.find('input[name="role"]').val();
// use the values as required here...
});
What you're missing is an index to reference the clicked row. You already have an index provided by the for loop, so just insert that into your onclick.
tu.append("<td> <a href=''><i class='fa fa-check' onclick='updateUser(" + i + ")'></i></a></td>")
And in your updateUser function, use the rowIndex to get the row:
var updateUser = function(rowIndex) {
var nRow = $('#bodyTableUpdate').find('tr')[rowIndex];
...
This is the simplest solution to your issue, but Rory's answer is a good explanation of how this works, what you're doing wrong, and good direction on how to do things right.

Ajax serialize() doesn't include data from dynamically created divs

I have a form and I add divs here dynamically using append(). It is successful in creating the divs, and that divs have input fields inside. But the problem is, after serializing the the data from the form, it doesnt include the data from the dynamically created divs.
This is my createDiv function:
function createDiv() {
var count = 5;
for (var i = 0; i < count; i++) {
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
"<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>");
}
};
Is there a problem in creating my div? Why does serialize doesnt include the data from my created div?
Thanks in advance!
Here is where is serialize the data. When the form is submitted:
$('#explorer_form').submit(function(e){
var serializedData = $('#explorer_form').serialize();
alert(serializedData);
$.ajax({
url : url + api,
type : method,
data : serializedData,
success : function(response){
$('#response').val(JSON.stringify(response));
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
And the form:
<form id='explorer_form'>
<input id='uname' name='uname' type='text'/>
<div id='userQues'></div>
<button type='submit'>Submit</submit>
</form>
And now, the alerted data is only the data from the input 'uname' only. It doesn't serialize the data from the created div.
Make sure your userQues is a form and that you do the serialize AFTER you added the inputs. Your code works, here: http://jsfiddle.net/9v3khbts/
HTML
<form id="userQues">
</form>
<button id="doSer">Serialize</button>
JS
$(document).ready(function(){
function createDiv() {
var count = 5;
for (var i = 0; i < count; i++) {
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
"<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>");
}
};
createDiv();
$('#doSer').click(function(){
alert($('#userQues').serialize())
})
});
<html>
<body>
<form id='explorer_form'>
<input id='uname' name='uname' type='text'/>
<div id='userQues'></div>
<button type='submit'>Submit</button>
</form>
<div class="output"></div>
<script src="jquery.js"></script>
<script>
function createDiv () {
var count = 5;
for(var i=0; i<count; i++){
$('#userQues').append("<div class='col-md-4'> <div class='form-group'> " +
"<label class='control-label' for ='data[" + i + "][questiona]'> Question A </label>" +
// "<input id='data[" + i + "][questiona]' name='data[" + i + "][questiona]' type='text' placeholder='' class='form-control input-md'/>" +
"<input id=data["+ i +"][questiona] name=data"+i+" type='text' placeholder='' class='form-control input-md'/>" +
"</div> </div>"
);
}
};
createDiv();
$('#explorer_form').submit(function(e){
e.preventDefault();
$(".output").text($("#explorer_form").serialize());
});
</script>
</body>
</html>
This works fine for me.
Don't use [] in ID or name.
Output will be -
You can use .appendTo() https://api.jquery.com/appendTo/ instead of .append()

duplicate-able checkboxes only returns value for orginal not duplicates

Hi this was actually orginally in another question (HERE) that had two parts. The first part was solved by #epascarello - thanks again, now just this part remaining, and i don't seem to get it.
I'm creating a duplicate-able div's containing checkboxes, on submit it only returns one value for the original input in the console, but no value for any duplicates.
Any help greatly appreciated.
JS Fiddle: http://jsfiddle.net/dawidvdh/EEd7c/
jQuery:
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var relation_input_groups = ["relation-group-1"];
//General Variables
//Generate variables
var relation_fields=[0];
var relation_input ="<label>Spouse</label>"+
"<input type='checkbox' value='spouse' class='relationship' name='relationship' />" +
"<label>own child</label>"+
"<input type='checkbox' value='ownchild' class='relationship' name='relationship' />" +
"<label>adopted</label>"+
"<input type='checkbox' value='adopted' class='relationship' name='relationship' />" +
"<label>stepchild</label>"+
"<input type='checkbox' value='stepchild' class='relationship' name='relationship' />" +
"<label>parent</label>"+
"<input type='checkbox' value='parent' class='relationship' name='relationship' />" +
"<label>inlaw</label>"+
"<input type='checkbox' value='inlaw' class='relationship' name='relationship' />" +
"<label>brother</label>"+
"<input type='checkbox' value='brother' class='relationship' name='relationship' />" +
"<label>other</label>"+
"<input type='checkbox' value='other' class='relationship' name='relationship' />";
//Generate variables
jQuery(document).ready(function(e) {
//populate jquery generated fields
jQuery(relation_fields).each(function() {
jQuery(relation_input).appendTo('#relation-group-1');
});
//populate jquery generated fields
//Cloning Function
jQuery('#clone').click(function() {
clone_dependant();
});
function clone_dependant() {
// Store the value of the previous Id to insert the cloned div..
var oldId = g_counter;
g_counter++;
currentdep ='dependant-'+g_counter;
// Clone the Dependant Div and set a new id
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var relation_newDiv = 'relation-group-'+ g_counter;
// Find div's inside the cloned object and set a new id's
$clonedDiv.find('#relation-group-1').attr('id',"relation-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input').val('');
$clonedDiv.find('input:checkbox').removeAttr('checked');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
relation_input_groups.push(relation_newDiv);
}
//Cloning Function
//Validation
//submit function
$(document).on("click", 'input[type="checkbox"]', function() {
jQuery(this).siblings(":checked").removeAttr('checked');
});
var result = {};
var dependants;
var dep_counter = 0;
jQuery('#submit').click(function(){
jQuery('.dependant').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['relationship'] = $(v).find('.relationship:checked').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
});
and the HTML:
<div id="dependant-1" class="dependant">
<div id="label">relationship:</div> <div id="relation-group-1"></div>
</div>
<button id="clone">clone</button>
<button id="submit">submit</button>
See this updated fiddle : http://jsfiddle.net/EEd7c/7/
Comment this line : $clonedDiv.find('input').val('');
Also set dep_counter = 0; on submit button click..
Your cloned check boxes do not have any values assigned to it. Ensure that when its cloned the values are set in the net set of checkboxes
It is simply because those checkboxes have the same name attribute. When the submit button is pressed, it serializes the values of all the form controls (text boxes, radio boxes, check boxes, etc) and send them. The name property should be unique for all those controls.
In your code, all those checkboxes have the same name property (relationship) which makes them indistinguishable. A fix to this problem is to give different names to those check boxes.

jquery incrementing number in html name=""

I want the variable inputname to go up by 1 every time a new <input /> is added
e.g.
<input name="1" />
<input name="2" />
<input name="3" />
---html---
<p class="add">Add</p>
<div class="added"></div>
---jQuery/javascript---
$(document).ready(function() {
$("p.add").click(function() {
var inputname = somevar;
var added = "<input type=\"text\" name=\""+inputname+"\" />";
$("div.added").append(added);
});
});
here it is on jsfiddle.net if it helps -> http://jsfiddle.net/gamepreneur/54kzw/
Set inputname like this:
var inputname = $('.added input').length + 1;
This gets the total number of added inputs and increments by one, resulting in the new name.
Change the variable scope
Use this:
// declare your variable here so it exists throughout every call, instead of being
// delcared new with every call.
var inputname = somevar;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type=\"text\" name=\""+(inputname++)+"\" />";
$("div.added").append(added);
});
});
Alternatives:
Grab the number of inputs ($('div.added input').length) and use that for a counter.
Grab the id of the last item $('div.added input:last').prop('name')) and increment it.
You need to declare inputname in the global scope so that it lasts longer than just the duration of the click function and then you need to increment it each time you use it.
I modified your fiddle to this: http://jsfiddle.net/jfriend00/54kzw/2/
var inputname = 1;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type='text' name='" + inputname++ + "' />";
$("div.added").append(added);
});
});
Try
$(document).ready(function() {
$("p.add").click(function() {
var inputname = $('input', $("div.added")).length + 1;
var added = "<input type=\"text\" name=\"" + inputname + "\" />";
$("div.added").append(added);
});
});
Consider adding some other selectors to choose those inputs (like a class selector)

Categories

Resources