AJAX POST Send Multiple DIV value - ajax

I would like to send my dynamically generated DIV items, but I do not understand how to do it
I create my div dynamically:
$("#clt_forf_ti").click(function(e){
e.preventDefault();
if(x < max_input){
x++;
var addDIV = $('<div id="clt_forf_div'+x+'" class="w-100 form-control" ><label for="clt_forf_num'+x+'">Ligne :</label> <input type="text" class="font-weight-bold border-top-0 border-right-0 border-left-0 mR-10" id="clt_forf_num'+x+'" autocomplete="off" style="width: 100px" > Forfait : <i id="clt_forf_forf_select'+x+'" style="display:none;"></i><input type="text" class="border-top-0 border-right-0 border-left-0" id="clt_forf_forf'+x+'" autocomplete="off" style="width: 180px"><i class="ti-calendar mL-20 mR-5"></i><input type="text" class="border-top-0 border-right-0 border-left-0" id="clt_forf_date_start'+x+'" name="datepicker" placeholder="DĂ©but" style="width: 80px"><i class="ti-calendar mL-20 mR-5"></i><input type="text" class="border-top-0 border-right-0 border-left-0" id="clt_forf_date_end'+x+'" name="datepicker" placeholder="Fin" style="width: 80px"><i id="clt_forf_ti_remove" class="ti-close c-red-500 mL-5" style="cursor: pointer;"></i></div>');
$('#clt_forf_bloc').append(addDIV);
$('#clt_forf_forf'+x, addDIV).autocomplete(autocomp_opt);
$("input[id^='clt_forf_date']", addDIV).datepicker(datepick);
//$('#clt_forf_date_end'+x, addDIV).datepicker(datepick);
}
});
I want to send each value by ajax:
var data = {
op_clt_forf_ref: $("[id^='clt_forf_forf_select']").html(),
op_clt_forf_num: $("[id^='clt_forf_num']").val(),
op_clt_forf_start: $("[id^='clt_forf_date_start']").val(),
op_clt_forf_end: $("[id^='clt_forf_date_end']").val(),
op_clt_forf_nom: $("[id^='clt_forf_forf']").val(),
};
however he only takes me the first div and not the others,
can you help me ?

The Elements that you have created were not present in the DOM earlier. So can't target them directly.
Try doing this:
var data = {
op_clt_forf_ref: $('body #clt_forf_forf_select').html(),
op_clt_forf_num: $('body #clt_forf_num').val(),
op_clt_forf_start: $('body #clt_forf_date_start').val(),
op_clt_forf_end: $('body #clt_forf_date_end').val(),
op_clt_forf_nom: $('body #clt_forf_forf').val(),
};

Related

Select2 clone is working only twice

I'm trying to clone a select2 list and 2 text areas, but it's working only for the first clone, and I don't understand why..any new eye will certainly help !
(the cloning is OK, but the select2 is not applied to the 3rd clone)
HTML part
<fieldset>
<div id="test">
<div>
<label>Tool Name : </label>
<select class="toollist" name="FSR_tool_id[]" style="width: 350px" />
<option></option>
<option value="1" >bla 1</option>
</select>
<input type="Button" value="ADD ANOTHER TOOL" class="AddTool">
<label>Service Scope</label>
<textarea rows="5" style="width:99%" name="FSR_servicescope[]" class="validate[required]" />
</textarea>
</br>
<label>Service Description</label>
<textarea rows="10" style="width:99%" name="FSR_servicedesc[]" class="validate[required]" />
</textarea><hr>
</div>
</div>
<input type="hidden" value="0" id="countertool">
</fieldset>
JS part (I call jquery and select 2 before, of course)
$('#test .toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
$("input[type='button'].AddTool").live('click',
function() {
var index = $(this).closest('div').index();
if (index > 0) {
$(this).closest('div').remove();
} else {
$('#test .toollist').select2('destroy');
//we have to destroy the select2 before cloning
var $div = $(this).closest('div').clone(true);
$div.find('input.AddTool').val("DELETE THIS TOOL");
//to replace the button "add" by another "delete"
var $input = $div.find('input.exp');
var index = $('input#countertool').val();
var id = 'exp' + index;
index++;
$('input#countertool').val(index);
$input.attr('id', id).data('index', index);
$(this).closest('#test').append($div);
//then, we re-apply select2 to the lists
$('#test .toollist').select2({
placeholder: "Search your tool !",
allowClear: true
});
};
});
Any idea of my mistake ?
Thanks a lot in advance !
See this fiddle: http://jsfiddle.net/omugbdm1/3/ it's a bit of a mashup of code but should do the trick.
<div id="test">
<div id="tooltest0" class="tooltest0">
<label>Tool Name :</label>
<select class="toollist" name="FSR_tool_id[]" id="FSR_tool_id0" style="width: 350px" />
<option></option>
<option value="1">bla 1</option>
</select>
</div>
<div id="tool-placeholder"></div>
<div>
<input type="button" value="Add another" />
</div>
</div>
and
$('.toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
$('input[type=button]').click(function () {
$('.toollist').select2("destroy");
var noOfDivs = $('.tooltest0').length;
var clonedDiv = $('.tooltest0').first().clone(true);
clonedDiv.insertBefore("#tool-placeholder");
clonedDiv.attr('id', 'tooltest' + noOfDivs);
$('.toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
});

AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing?

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});
By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

Sort five numbers inserted through user form and send it through AJAX and retrieve the result as JSON on same page

I am a beginner to ajax, jQuery and json. I want to sort five numbers and for that I need to insert data through an user form and send it through ajax and retrieve the result as json on the same page. Can you please help me out here?
(UPDATE)
The HTML code is like this:
<td><input type="number" name="array[]" />
<td><input type="number" name="array[]" />
<td><input type="number" name="array[]" />
<td><input type="number" name="array[]" />
<td><input type="submit" name="submit" value="SUBMIT" id="submit" />
And PHP in another file sort.php goes like this:
$a=$_POST['array'];
sort($a);
$b=count($a);
for($i=0;$i<$b;$i++)
{
echo "$a[$i] <br>";
}
<script type="text/javascript">
var array=[];
function addElement() //this function take the value from the text box and assign the value to an array
{
var number=$("#addvalue").val();
array.push(number);
$("#addvalue").val(' ');
$("#addvalue").focus();
}
function Sort() //this function display the number in desending order
{
for(i=0;i<array.length;i++) {
for(j=i+1;j<array.length;j++) {
if(parseInt(array[j]) > parseInt(array[i])) {
var temp=array[i];
array[i]=array[j];
array[j]=temp;
}}}
$.each(array,function(index) //and this function display the number.
{
var span=document.createElement("span");
span.appendChild(document.createTextNode(array[index]));
var i =document.getElementById("array");
i.appendChild(span);
var br=document.createElement("br");
i.appendChild(br);
});
$("div#array span:first").css("color","green");
};<script>
<body>
<input type="text" id="addvalue"/>
<br/><input type="button" onclick="addElement()" value="Add Number"/> <input type="button" onclick="Greater()" value="Sort">
<div id="array"></div>
</body>

django handle form submit without returning a response

I've tried everything here, and I must be missing something, as my ajax post to Django isn't returning anything. I've got it down to the bare bones at this point, just trying to get it working and no joy.
My view:
def saveProjectEntry(request):
form = ProjectEntryUpdateForm(request.POST)
if form.is_valid():
msg = json.dumps({'msg':'success'})
return HttpResponse(msg, mimetype='application/json')
else:
msg = json.dumps({'msg':'failed'})
return HttpResponse(msg, mimetype='application/json')
My url.py entry:
url(r'^chargeback/savepe/$','chargeback.views.saveProjectEntry'),
My jQuery:
$('#peUpdateForm').submit(function() {
$.ajax({
url:'/chargeback/savepe/',
data: $("#peUpdateForm").serialize(),
type: "POST",
success: function(e) {
alert("success");
},
error: function(e) {
alert("failed");
}
});
return false;
});
I also tried the jQuery post method:
$('#peUpdateForm').submit(function(e){
$.post('/chargeback/savepe/', $('#peUpdateForm').serialize(), function(data){
alert("success");
});
e.preventDefault();
});
I'm not getting anything. Not getting any of my alerts. Not getting any errors from the view (if I just navigate to the view directly I get the expected {'msg':'failed'} displayed in the browser, so the json response is fine. The url calls the correct view. The only thing I can think of is my jQuery code is wrong, but I can't figure out where, and there are no errors in the console. I've tested, in the console, the
$('#peUpdateForm').serialize()
and I get the expected value. Pulling my hair out here... Thanks.
EDIT: Adding HTML as my post method isn't even getting called when I place a breakpoint there, so something may be wrong with how my submit is being set up.
<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable ui-dialog-buttons" style="outline: 0px; z-index: 1002; position: absolute; height: auto; width: 376px; top: 75px; left: 408px; display: block;" tabindex="-1" role="dialog" aria-labelledby="ui-id-8"><div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-id-8" class="ui-dialog-title">Project Entry Update</span><span class="ui-icon ui-icon-closethick">close</span></div>
<div id="addPEForm" style="width: auto; min-height: 0px; height: 365px;" class="ui-dialog-content ui-widget-content" scrolltop="0" scrollleft="0">
<form method="post" id="peUpdateForm" action="">
<div style="display:none">
<input type="hidden" name="csrfmiddlewaretoken" value="wvzwSBl87vC1tbkbdfxsD82GnjtvJCSz"></div>
<p><label for="id_departmentid">Department:</label>
<select id="id_departmentid" class="projEntryControl" name="departmentid">
<option value="" selected="selected">Choose a Department</option>
<option value="1">ABND</option>
<option value="2">ATT</option>
<option value="3">AVI</option>
<option value="4">CCS</option>
<option value="5">PBW</option>
</select></p>
<p><label for="id_projectid">Project:</label>
<select id="id_projectid" class="projEntryControl" name="projectid">
<option value="-1">Choose a Project</option>
<option value="undefined">Bexar Street</option>
<option value="undefined">Chalk Hill</option>
<option value="undefined">Crown Road</option>
</select>
</p>
<p><label for="id_progNumId">Program Number:</label>
<select id="id_progNumId" class="projEntryControl" name="progNumId">
<option value="" selected="selected">Choose a Program Number</option>
<option value="1">31664</option>
<option value="2">DD-7081</option>
</select></p>
<p><label for="id_hoursWorked">Hours Worked:</label>
<input name="hoursWorked" value="0.0" class="projEntryControl" maxlength="5" type="text" id="id_hoursWorked"></p>
<p><label for="id_notes">Notes:</label>
<textarea id="id_notes" rows="10" cols="40" name="notes"></textarea></p>
</form>
</div>
...
AFAIK, Here's the way to do it right, if you want to keep the button outside:
$('#button').on('click', function(){
$.ajax({
data: $('#form').serialize(),
...});
});
This because `$('#form').submit() gets called only if you keep the submit button inside the form tags.

input fields not showing in hide/show div with radio buttons

I have a very basic hide/show div function set up for when people click a certain radio button. In one of the hidden divs I need to create a form however when I add input fields to the hidden div my function stops working.
<div id="tabs">
<div id="nav">
<input type="radio" name="primary_contact_director" value="Yes" class="div1">Yes</input>
<input type="radio" name="primary_contact_director" value="No" class="div2">No</input>
</div>
<div id="div1" class="tab">
<p>this is div 1</p>
</div>
<div id="div2" class="tab">
<p>this is div 2</p>
</div>
</div>
<script type="text/javascript" charset="utf-8">
(function(){
var tabs =document.getElementById('tabs');
var nav = tabs.getElementsByTagName('input');
/*
* Hide all tabs
*/
function hideTabs(){
var tab = tabs.getElementsByTagName('div');
for(var i=0;i<=nav.length;i++){
if(tab[i].className == 'tab'){
tab[i].className = tab[i].className + ' hide';
}
}
}
/*
* Show the clicked tab
*/
function showTab(tab){
document.getElementById(tab).className = 'tab'
}
hideTabs(); /* hide tabs on load */
/*
* Add click events
*/
for(var i=0;i<nav.length;i++){
nav[i].onclick = function(){
hideTabs();
showTab(this.className);
}
}
})();
This code works however when I add
<label class="title">First Name:</label>
<input type="text" name="first_name" class="form">
<label class="title">Last Name:</label>
<input type="text" name="last_name" class="form">
<label class="title">Business Address:</label>
<span class="instructions">Please enter a physical address. P.O. Boxes are not acceptable for filing.<br>
If your business is run out of your home, please list that address.</span><br>
<input type="text" name="business_address" class="form">
<label class="title">City:</label>
<input type="text" name="business_city" class="form">
<label class="title">State</label>
<select name="business_state">
<option value="California">California</option>
</select>
<label class="title">Zip Code:</label>
<input type="text" name="business_zip" class="form">
<label class="title">Business Phone Number:</label>
<input type="text" name="business_phone" class="form"><br>
to my div2 it stops working.
Hopefully this is a clear explanation. Any help is always appreciated!
In your hideTabs() function, you've got two typos.
First, you're iterating through the tab[] array, but you're checking it against the length of the nav[] array. This works because you have the same number of elements in your first example, but that's just a coincidence. If you evaluate it against the tab[] array's length, it will work better. The other problem you have is that your for loop ends at greater-than-or-equal-to length. THe problem is that arrays start counting at zero, so if the length is 3, the items on the list are tab[0], tab[1], and tab[2]. your code was trying to set something for tab[3], which didn't exist.
Here's the working code:
/*
* Hide all tabs
*/
function hideTabs(){
var tab = tabs.getElementsByTagName('div');
for(var i=0;i<tab.length;i++){
if(tab[i].className == 'tab'){
tab[i].className = tab[i].className + ' hide';
}
}
}
In the future, you should look into using the javascript console in Chrome (or any other browser) to check for errors if your scripts stop working—usually there's an error that that will give you hints as to what's happening.

Resources