Multidimensional Form & Ajax-JQuery - javascript

$(document).ready(function () {
$("#addrow").click(function () {
var strToAdd = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" class="price form-control" placeholder="price" name="price[]"><td></tr>';
$('#itemrow').append(strToAdd);
$('.item_code').keyup(function () {
var dataString = $('.item_code').val();
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code: dataString },
dataType: "html"
});
request.done(function (msg) {
$(".price").val(msg);
});
});
});
});
<table id="itemrow">
<tr>
<td>
<input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]">
</td>
<td>
<input type="text" class="price form-control" placeholder="price" name="price[]">
<td>
</tr>
<tr>
<td>
<input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]">
</td>
<td>
<input type="text" class="price form-control" placeholder="price" name="price[]">
<td>
</tr>
</table>
HTML Code is added through another javascript using append function. When I enter Item Code for both the fields it only displays data of first one.

It happends, because you use multiple instances of classes "item_code" and "price". Try this code.
$('.item_code').keyup(function() {
var dataString = $(this).val();
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code : dataString },
dataType: "html"
});
request.done(function(msg) {
$(this).parent().find('.price').val(msg);
});
});
});
});

Try this:
$(document).ready(function () {
$("#addrow").on('click',function () {
var strToAdd = '<tr><td><input type="text" class="invoice_id form-control" placeholder="Item Code" name="invoice_id[]"></td><td><input type="text" class="txtHint form-control" placeholder="Item Code" name="txtHint[]"><td></tr>';
$('#itemrow').append(strToAdd);
});
$('.item_code').on('keyup',function () {
var item = $(this);
var dataString = item.val();
})
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code: dataString },
dataType: "html"
});
request.done(function (msg) {
item.parentsUntil('tr').find('.price').attr('value',msg);
});
});
});

Thanks to everyone who helped me. Was able to correct the mistake by adding context: this, in the ajax request. Below is full code.
$(document).ready(function () {
$("#addrow").click(function () {
var strToAdd = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" class="price form-control" placeholder="price" name="price[]"><td></tr>';
$('#itemrow').append(strToAdd);
$('.item_code').keypress(function () {
var dataString = $(this).closest('tr').find('.item_code').val();
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code : dataString },
context: this,
dataType: "html"
});
request.done(function (msg) {
$(this).closest('tr').find('.price').val(msg);
});
});
});
});

Related

Multiple checkbox submit php form with 1 click

Is there a way to improve this? Can't find a way to improve..
var $submit = $('#submit-form');
$submit.off('click').on('click', function(e) {
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$.each(checkedBOX, function(k, v) {
var v = $(v);
servers.push(v.val());
v.prop("checked", false);
});
var doneCount = 0;
$.each(servers, function(key, server) {
$.ajax({
type: "POST",
url: window.location.href,
data: $('#form').serialize() + '&server=' + server + '&submit=',
success: function (data) {
doneCount++;
if (doneCount >= servers.length) {
window.location.reload();
}
}
})
});
});
Can't figure it out what is the best way to make it faster..
Could anyone help me out here?
try this way , remove loop
$(document).on('submit','#submit-form',function(e){
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$("input:checkbox[name=checkbox]:checked").each(function(){
servers.push($(this).val());
});
console.log(servers);
$.ajax({
type: "POST",
url: window.location.href,
data: $('#submit-form').serialize() + '&server=' + servers + '&submit=',
success:function(data){
window.location.reload();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" id="submit-form">
<input type="text" name="name" placeholder="NAME"/>
<br/>
<input type="text" name="email" placeholder="EMAIL"/>
<br/>
<input type="checkbox" name="checkbox" value="1" />
<input type="checkbox" name="checkbox" value="2" />
<input type="checkbox" name="checkbox" value="3" />
<input type="checkbox" name="checkbox" value="4" />
<br/>
<button type="submit">SUBMIT</button>
</form>

Why my javascript is calling a postback and i don't have error?

When I press on my edit button I call a webservice function and it return a list of question parameter and it's working the function return the right value for each edit button but after returning the value I have a post back and all my html input that I fill in this function they are clear again, why?
JavaScript and jQuery:
$(document).ready(function () {
$('.divPreview').on("click", ".editbtn", function () {
var idQ = 0;
idQ = $(this).val();
var Did = { 'Qid': idQ };
alert(idQ);
$.ajax({
type: "POST",
async: false,
url: "/WebService.asmx/GetQuestion",
data: JSON.stringify(Did),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
function OnSuccess(response) {
var question = response.d;
$(".dropdown_fields").html('<select id="dplQuestionType" class="dropdown_selector"><option value="radio">Radio Button</option> <option value="checkbox">Check Box</option></select>');
$(".input_field").html('<p>Q1:<input id="txtQuestion" type="text" /></p> <p> Answer Choices:</p><div><input id="hdnC1" type="hidden" value="0" /><input id="txtC1"type="text" name="mytext[]" /><input id="cbActive1" type="checkbox" /></div><div><input id="hdnC2" type="hidden" value="0" /><input id="txtC2" type="text" name="mytext[]" /><input id="cbActive2" type="checkbox" /></div>');
$(".OtherOption").html('<input id="btnAddField" class="btnAddField" type="button" value="Add Choices"/><br>Page Number<input id="txtPageNumber" type="text" /> Question Order: <input id="txtOrder" type="text" /><br/><p><input id="cbCommonField" type="checkbox" />Add a Common Field</p><br/>Is Required<input id="cbIsRequire" type="checkbox" />Is Active<input id="cbIsActive" type="checkbox" /><br/>Hint:<textarea id="txtaHint" rows="2" cols="20"></textarea> ');
$(".ButtonField").html('<p><input id="btnSave" type="button" value="Save" onclick="GetQuestionInfo()" /> <input id="btnCancel" class="btnCancel" type="button" value="Cancel" /></p>');
document.getElementById("btnAddQuest").style.visibility = 'hidden';
document.getElementById("txtOrder").value = question.qst_Order;
document.getElementById("txtPageNumber").value = question.qst_PageNumber;
document.getElementById("cbIsRequire").value = question.qst_Order;
document.getElementById("cbIsActive").value = question.qst_Order;
document.getElementById("txtaHint").value = question.qst_Hint;
document.getElementById("dplQuestionType").value = question.qst_Type;
document.getElementById("hdnQuestionID").value = question.qst_Id;
alert(question.qst_txt);
}
});
});
You aren't actually doing a ajax request you are simply doing a normal post request from a form, to do a ajax request prevent the default submit using e.preventDefault();
$('.divPreview').on("click", ".editbtn", function (e) {
e.preventDefault();

How can i get into the value inside of an html <tr> object

So i have this code. I want to send the data inside of my html inputs to the controllers parameters. In my jquery i have a line that looks like this
var currentRow = $(this).closest("tr");
But i have no clue how to get into the values of each input inside the currentRow Object how can i do that or do you maybe know a better way to do this?
// my html
#foreach (var discount in Model.DiscountList)
{
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
#if (discount.isTwoForThree == true)
{
<td><input type="tel" value="Ta 3 betala för 2" readonly /></td>
}
else
{
<td><input type="number" value="#discount.PercentOffPrice"/></td>
}
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
}
//my jquery
$(".fa-update").on("click", function () {
var currentRow = $(this).closest("tr");
console.log(currentRow.children("#freeShippingCheckBox").val());
if (confirm("Are you sure you want to edit this discount code?"))
{
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: "freeShipping=..........???????????",
success: function (data) {
if (data) {
}
location.reload();
}
});
location.reload();
alert("Deleted");
})
}
});
//my controller
[HttpPost]
public void UpdateDiscount(int id, bool freeShipping, int percentOfPrice, bool active)
{
Service.DiscountService.UpdateDiscount(id, freeShipping, percentOfPrice, active);
}
My proposal is:
$(function () {
$(".fa-update").on("click", function (e) {
var data = {};
var currentRowParams = $(this).closest("tr").find('input').each(function(index, element) {
var name = element.name ? element.name : 'undefined' + index;
data[name] = element.value || '';
});
var x = JSON.stringify(data);
console.log(x);
//
// If instead you want the params in a traditional GET
//
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<table>
<tbody>
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
<td><input type="tel" value="Ta 3 betala for 2" readonly /></td>
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
</tbody>
</table>
You can access a value via .html(). As Vijai said, you can use serialize to make it a POST array like (&=, etc) format assuming you have a structured form. Or, to stay similar to your original code, you can just pass as usual JSON. like
data:{shippingInfo: "value", moreInfo: "blahblah"}
It is recommended to use a <form id="formID" ...> tag around yours inputs and use $("#formID").serialize() in the Ajax method if you are not doing processing of the input value in the View. Refer this sample link : Submit form using AJAX and jQuery
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: $("#formID").serialize(),
success: function (data) {
if (data) {
}
location.reload();
}
});

Jquery .post() not calling script

I am trying to pass the data from a form to an insertion script without having the form data cleared. I am using this function to act on the press of the submit button but I get nothing. It is even set to throw an error if the form is missing data but it doesn't even get that far. I can only assume I am not calling it properly.
$(function() {
$(".submit").click(function() {
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (facility == '' || riskclient == '' || riskdate == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
<div class="body">
<div align='center'>
<div class="tablebackground">
<form method ="post" name= "form" id="form">
<table border='1' >
<tr>
<td>Facility</>
<td><input type="text" name= "riskFacility" id="facility"></td>
<td rowspan='4'><input type="submit" name="submit" value="New Client" class="submit"/</td>
</tr>
<tr>
<td>Client</td>
<td><input required type="text" name="riskClientId" id="riskclient" value="<?php echo htmlspecialchars($_POST['riskClientId']); ?>"></td>
</tr>
<tr>
<td>Audit Date</td><td> <input required type="text" id="datepicker" name="riskauddate" id="riskdate"></td>
</tr>
</table>
</form>
It is definitely not passing anything to the insertion script. So again, I think I am calling it incorrectly.
I see your html tags are not closed properly
<div class="body">
<form method="post" name="form" id="form">
<table border='1'>
<tr>
<td>Facility</td>
<td>
<input type="text" name="riskFacility" id="facility">
</td>
<td rowspan='4'>
<input type="submit" name="submit" value="New Client" class="submit" /> </td>
</tr>
<tr>
<td>Client</td>
<td>
<input required type="text" name="riskClientId" id="riskclient" value="">
</td>
</tr>
<tr>
<td>Audit Date</td>
<td>
<input required type="text" id="datepicker" name="riskauddate" id="riskdate">
</td>
</tr>
</table>
</form>
and check if it comes to error call back
I think it's useful..
$(document).ready(function () {
$('#submit').on('click', function (event) {
event.preventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity='+ facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
or
// var datastring = $("#form").serialize();
if(facility=='' || riskclient=='' || riskdate=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function (msg) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
})
event.preventDefault used to stop submit and page reload.
datastring = $("#form").serialize(); used to submit all data values so no need to take each and every variable assign value.
You can refactor a little the code like this, revise your html tags. You have a double id property in an input, and missing clousure tags.
$(document).ready(function() {
$(".submit").click(function(event) {
event.PreventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (!facility || !riskclient || !riskdate) {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
//send ajax post
}
});
});

JQuery - Edit table, get data through serialize instead?

Here is my java code. I'd like to find a cleaner way to do this. How can I access the same data via serialize? I plan to have multiple forms on a single page that need processing. I'm looking to DRY up the code and not have to specifically name each field.
Thanks!
HTML:
ItemAmountDescription
<tr class="edit_tr" id="3">
<td class="edit_td">
<span class="text" id="name_3">Salary</span>
<input type="text" value="Salary" class="editbox" id="name_input_3"/>
</td> <td class="edit_td">
<span class="text" id="amount_3">100.00</span>
<input type="text" value="100.00" class="editbox" id="amount_input_3"/>
</td> <td class="edit_td">
<span class="text" id="description_3">Salary</span>
<input type="text" value="Salary" class="editbox" id="description_input_3"/>
</td> </tr>
</tbody>
</table>
Java code:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#name_"+ID).hide();
$("#amount_"+ID).hide();
$("#description_"+ID).hide();
$("#description_input_"+ID).show();
$("#name_input_"+ID).show();
$("#amount_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var name=$("#name_input_"+ID).val();
var amount=$("#amount_input_"+ID).val();
var description=$("#description_input_"+ID).val();
var dataString = 'id='+ ID +'&name='+name+'&amount='+amount+'&description='+description;
$("#name_"+ID).html('<img src="load.gif" />'); // Loading image
if(name.length>0 && amount.length>0)
{
$.ajax({
type: "POST",
url: "{{url('budget/edit-income')}}",
data: dataString,
cache: false,
success: function(html)
{
$("#name_"+ID).html(name);
$("#amount_"+ID).html(amount);
$("#description_"+ID).html(description);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
You mentioned serialize... use $('form').serialize(); to create a string ready for the ajax data

Categories