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

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()

Related

jQuery Mobile dynamic content -cannot select tag

I'm working with jQuery Mobile in a google web app and just having some issues selecting a tag. More specifically, I have content that is loaded from an external source so need to have a loading page initially. Once the external source is available I then update the page with the content using jQuery. Included in this content is an input tag. The issue is when I update the page, I cannot then cannot find the value of this input tag.
Here is my code below:
(intial html - Before content is loaded)
<div class="ui-body ui-body-a">
<div id="googleList" >
<fieldset data-role="controlgroup" data-mini="true" >
<input type="checkbox" name="checkbox-v-6a" id="checkbox-1-a">
<label for="checkbox-v-6a">Loading . . . </label>
</fieldset>
</div>
</div>
Here is my jQuery to update the code above when the new content comes in:
function showTaskList(tasks)
{
//Generate HTML
var htmlToInsert = "<fieldset data-role=\"controlgroup\" data-mini=\"true\" >";
for(var i = 0; i < tasks.length; i++)
{
htmlToInsert += "<input type=\"checkbox\" data-id=\"" + tasks[i][1] + "\" name=\"checkbox-" + i + "-a\" id=\"checkbox-" + i + "-a\" class=\"custom taskCheckBox\" ";
if(tasks[i][2] != undefined)
htmlToInsert += "checked=\"checked\"";
htmlToInsert += " />";
htmlToInsert += "<input id=\"currency-controlgroup1\" data-id=\"" + tasks[i][1] + "\" type=\"text\" value=\"" + tasks[i][0] + "\" data-wrapper-class=\"controlgroup-textinput ui-btn\" class=\"taskinputBox\">";
}
//Insert HTML into site
$("#googleList").html(htmlToInsert + "</fieldset>");
//Refresh List
$("#googleList").trigger("create");
}
Here is my code to get the input tag value
$(document).ready(function(){
function processTaskList()
{
console.log("Test");
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("data-id");
console.log("CheckBox:" + checkBoxId );
});
}
});
CheckBoxId keeps coming back undefined when I click on one of the checkboxes. I want to be able to read the data-id value. I'm not sure how to fix this? Any help is appreciated.
I tested the code below again, and it works - Thanks for your help
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("id");
console.log("CheckBox:" + checkBoxId );
});

Previous fields text disappears when adding new one with select2 ajax

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');
})

join two html block variables in javascript

I am trying to join two blocks of html code with javascript and call a dialog afterwards. I have done some research and tried concat and + but that doesnt work. Here is a simplified version of my code:
var html =
"<div class=\"dialog-form\" title=\"Edit\">" +
"<form class=\"insertaplato\" method=\"POST\" action=\"edit.php\">" +
"<fieldset>" +
"<label>Plate: </label> <input type=\"text\" value=\"" + plate + "\" >" +
"<label>Price: </label><input type=\"text\" value=\""+ price +"\" >";
"Spicy: <br> ";
if (spicy==1)
{var varP=
"<label> Yes </label><input value= \"yes\" type=\"radio\" checked>"+
"<label> No </label><input value=\"no\"><br><br>";
} else {
var varP=
"<label> Yes </label><input value=\"yes\" type=\"radio\">"+
"<label> No </label><input value=\"no\" checked type=\"radio\"><br><br>";
}
var html2 = "<br>"+
"<br><input id=\"insert\" type=\"submit\" value=\"Edit\" name=\"send\"> " +
"</fieldset>"+
"</form>"+
"</div>";
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
As it is right now the dialog doesnt come up. If I do this with only the first html variable it come up Ok but when I try to add or concatenate the others nothing happens. I am evidently not using these variables as I should. Any ideas?
Concatenate the strings and not the jQuery objects
var div = $(html + varP + html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
Remove the $ where you're appending the pieces together. You want to append the strings into a single object.
var div = $(html + varP + html2);
intead of
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
try this:
var div = html+varP+html2;
$('.dialog-form').dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});

Insert Input Box Using .innerHTML property of jQuery

I am using jQuery for the first time. I've been searching a lot but have not gotten the answer.
I want to insert an input Type at id="star" and with value="score Star" but I'm not able to do that. Score returns the numeric value. I think the problem is in the value attribute, but I don't know where. Thanks In Advance.
Here's the code:
<script type="text/javascript">
$(function() {
$('#click').raty({
click: function(score) {
document.getElementById('star').innerHTML="<input type='text' name='type' value='"score+ "' Star >";
//alert( 'score: ' + score);
}
});
});
</script>
<label>Deal Type:</label>
<div id="click"></div><span id="star"></span></div>
You're not writing the code correctly
.innerHTML="<input type='text' name='type' value='"score+ "' Star >";
It should be
.innerHTML="<input type='text' name='type' value='"+score+" Star' >";
You're not concatenating the string, or quoting the value correctly
.innerHTML="<input type='text' name='type' value='"score+ "' Star >";
should be
.innerHTML="<input type='text' name='type' value='" + score + " Star' >";
<script type="text/javascript">
$(function() {
$('#click').raty({
click: function(score) {
document.getElementById('star').innerHTML="<input type='text' name='type' value='"+score+ " Star'>";
//alert( 'score: ' + score);
}
});
});
</script>
<label>Deal Type:</label>
<div id="click"></div><span id="star"></span></div>
A better approach is to actually create an input DOM object and append it:
$('#star').append($('<input/>').attr({
type: "text",
name: "type",
value: score + " Star"
}));

How can I conduct a post via Javascript from jQuery?

I want to conduct a POST request via jQuery.
Say I have four Javascript variables: var1,var2,var3,var4 and a endpoint of URL.
How would I POST via jQuery (I would rather not be using Ajax for the sake of this example).
Put these variables into the form via hidden labels, and submit it.
If you can place a div in the html with id="myDivContent", you could add them there
var myStr = '<input name="var1" type="hidden" value="' + var1 + '" />';
myStr += '<input name="var2" type="hidden" value="' + var2 + '" />';
myStr += '<input name="var3" type="hidden" value="' + var3 + '" />';
$('#myDivContent').innerHTML = myStr;
$('form#myForm').submit();
If you just want to create a form on the fly, put these vars in there and make a POST request, then I need to update my answer.
jquery:
// var1, var2 ..., my_url must be given
$('input:hidden[name=var1]').val(var1);
$('input:hidden[name=var2]').val(var2);
...
$('#my_form').attr('action', my_url);
$('#my_form').submit();
html:
<form id="my_form">
<input type="hidden" name="var1">
<input type="hidden" name="var2">
...
</form>
No AJAX. This code actually submit your form as a normal submit action triggered by the user.
You don't need jQuery for this use-case.
I would rather create a form element(DOM) and set the variables of the form and then submit the form.
This can be done in javascript.
Here is an example.
value1 = 1234;
value2 = 5678;
value3 = 9012;
value4 = 3456;
var f = document.createElement("form")
f.method= "post"
f.action = "enpoint.url"
f.innerHTML = f.innerHTML + "<input type='text' name='var1' value='"+value1+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var2' value='"+value2+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var3' value='"+value3+"'/>"
f.innerHTML = f.innerHTML + "<input type='text' name='var4' value='"+value4+"'/>"
f.submit()

Categories

Resources