How pass the checked checkbox value to the next page using javascript - javascript

I am retrieving value from database and showing it in html table with check boxes.i am also having button, when user check the check box and it pass the rowid and redirect next page .if user not check the check box and check the button it will not pass the rowid and it will not redirect.
my problem is when first row in html table is checked and button pressed its working but if i am checking the second row in html table and click the button it not performing any action
below is my code
<tbody id="fbody" class="fbody" style="width:1452px" >
<?php
$clientid=$_GET['clientid'];
if($clientid!=""){
$sql = mysql_query("SELECT * FROM billingdatainputandexport WHERE clientid = '$clientid'");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo '<td style="width:118px" class="edit clientid '.$rows["id"].'">'.$rows["clientid"].'</td>
<td id="CPH_GridView1_clientname" style="width:164px" class="edit clientname '.$rows["id"].'">'.$rows["clientname"].'</td>
<td id="CPH_GridView1_billingyear" style="width:168px" class="edit billingyear '.$rows["id"].'">'.$rows["billingyear"].'</td>
<td id="CPH_GridView1_billingmonth " style="width:169px" class="edit billingmonth '.$rows["id"].'">'.$rows["billingmonth"].'</td>
<td style="width:167px" class=" '.$rows["id"].'">
<input name="nochk" value=" '.$rows["id"].'" type="submit" style="margin:0 0 0 49px;background-image: url(/image/export.png);background-repeat: no-repeat;cursor:pointer;color:#C0C0C0;" ></td>
<td style="width:69px"><input type="checkbox" id="chk1" name="chk1" value=" '.$rows["id"].'"/></td>
</tr>';
}
}
?>
</tbody>
<input type="image" name="yousendit" id="yousendit" src="/image/export.png" style="margin:-5px 23px -28px 822px;cursor:pointer;" >
javascript
<script>
$(document).ready(function() {
$("#yousendit").click(function() {
if(document.getElementById('chk1').checked){
var ms = document.getElementById('chk1').value;
$.ajax({
type:"post",
data:"ms="+ms,
success:function(data) {
window.location = 'billingdatainputandexport/billingdatainputandexportdetailedreport.php?ms='+ms+''
$.post("billingdatainputandexport/billingdatainputandexportdetailedreport.php", { "test": ms } );
$("#result").html(data);
}
});
}
});
});
</script>

You can change this:
id="chk1"
name="chk1"
<input type="checkbox" id="chk1" name="chk1" value=" '.$rows["id"].'"/>
to this:
class="chk"
name="chk"'.$rows["id"].'
'<input type="checkbox" id="chk1" name="chk"'.$rows["id"].'" value=" '.$rows["id"].'"/>'
and update the jQuery code:
$("#yousendit").click(function() {
var $check = $('.chk:checked');
$.ajax({ //<-------------here you havn't mentioned the url
type:"post",
data:$check.serialize(),
success:function(data){
............
}
});
});

HTML page should have only 1 element with specified ID, in your case as code is running in loop and you are assigning id
<td style="width:69px"><input type="checkbox" id="chk1" name="chk1" value=" '.$rows["id"].'"/></td>
all the checkbox will have the same ID. Now once you try to get checked status by selector
if(document.getElementById('chk1').checked){
it will return true if only first checkbox is selected and ignore all the other instances.
You should use class selector and loop through elements to get comma-separated values and make ajax call.
First change id to class in HTML
<input type="checkbox" class="chk1" name="chk1" value=" '.$rows["id"].'"/>
and change JavaScript to process selected checkbox array
$(document).ready(function () {
$("#yousendit").click(function () {
var id_list = [];
$.each($(".chk1:checked"), function (index, element) {
var tmpVal = $(element).val();
id_list.push(tmpVal);
});
if (id_list.length > 0) {
var ms = id_list.join();
$.ajax({
type: "post",
data: "ms=" + ms,
success: function (data) {
window.location = 'billingdatainputandexport/billingdatainputandexportdetailedreport.php?ms=' + ms + ''
$.post("billingdatainputandexport/billingdatainputandexportdetailedreport.php", {
"test": ms
});
$("#result").html(data);
}
});
}
});
});

Related

appended select option is viewable in HTML but not detectable

I have a button that will update my select. Here is the code:
$("#add_row").on('click', function(){
var table = $("#ingredients_info_table");
var count_table_tbody_tr = $("#ingredients_info_table tbody tr").length;
var row_id = count_table_tbody_tr + (Math.floor(Math.random()*1000));
var html = '<tr id="row_'+row_id+'"><td><select class="form-control" data-row-id="row_'+row_id+'" id="ingredient_'+row_id+'" name="ingredient[]" onchange="getIngredientAmount(\''+row_id+'\')" style="width:100%;" required><option value="" selected disabled hidden></option>'
html += '</select>'+'</td><td><label for="amount"><i id="amount_unit_'+row_id+'" >Amount Unit</i> x</label><input type="number" name="amount[]" id="amount_'+row_id+'" class="form-control" required style="display: inline-block;"></td>'+
'<td><button type="button" class="btn btn-primary" onclick="removeRow(\''+row_id+'\')"><i class="fa fa-times"></i></button></td>'+
'</tr>';
$.ajax({
url: "../api/ajax/getInventory.php",
type: "post",
dataType: "json",
success: function(response2){
// console.log(response2["data"]);
// console.log(Object.keys(response2["data"][0]).length);
for (var i = 0; i < response2["data"].length; i++) {
$("select#ingredient_"+row_id).append('<option value="'+response2['data'][i][0]+'">'+response2['data'][i][1]+'</option>');
$("select#ingredient_"+row_id).trigger('chosen:updated').change();
}
}
});
if(count_table_tbody_tr >= 1) {
$("#ingredients_info_table tbody tr:last").after(html);
}
else {
$("#ingredients_info_table tbody").html(html);
}
});
It is working properly. The dropdown list is updated.
The problem here is whenever I tried to console.log() the selector for the option, it appears as if the selector is empty, but based on the link, the dropdown menu is updated.
Here is the console.log():
console.log($('#ingredients_info_table tbody tr[id^="row_"]:last td select').html());
And here is the output for the console.log():
<option value="" selected="" disabled="" hidden=""></option>
//this empty option is statically inserted, not dynamic.
My question is, how should I display or find the updated set of options after it is dynamically updated (after the .append() is used) so that I could use those updated elements.
The reason it is empty because you are calling it before the data is populated through ajax. You have to get your html inside success callback then call the other ajax block.
Also you don't have to count the number of rows before insertion. You can use .append() which will always insert after all children.
See this example:
$("#add_row").on('click', function() {
var table = $("#ingredients_info_table");
var count_table_tbody_tr = $("#ingredients_info_table tbody tr").length;
var row_id = count_table_tbody_tr + (Math.floor(Math.random() * 1000));
var html = `
<tr id="row_${row_id}">
<td><select class="form-control" data-row-id="row_${row_id}" id="ingredient_${row_id}" name="ingredient[]" onchange="getIngredientAmount(${row_id})" style="width:100%;" required>
<option value="" selected disabled hidden></option>
</select>
</td>
<td>
<label for="amount"><i id="amount_unit_${row_id}">Amount Unit</i> x</label>
<input type="number" name="amount[]" id="amount_${row_id}" class="form-control" required style="display: inline-block;">
</td>
<td>
<button type="button" class="btn btn-primary" onclick="removeRow(${row_id})"><i class="fa fa-times"></i></button>
</td>
</tr>
`;
$("#ingredients_info_table tbody").append(html);
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/",
type: "get",
dataType: "json",
success: function(response2) {
console.log(response2.length);
// console.log(response2["data"]);
// console.log(Object.keys(response2["data"][0]).length);
for (var i = 0; i < response2.length; i++) {
$("select#ingredient_" + row_id).append('<option value="' + response2[i]['id'] + '">' + response2[i]['title'] + '</option>');
//$("select#ingredient_" + row_id).trigger('chosen:updated').change();
}
console.log($('#ingredients_info_table tbody tr[id^="row_"]:last td select').html());
}
});
// no need for this code
/* if (count_table_tbody_tr >= 1) {
$("#ingredients_info_table tbody tr:last").after(html);
} else {
$("#ingredients_info_table tbody").html(html);
}*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='ingredients_info_table'>
<tbody></tbody>
</table>
<div id='add_row'>
Add Row
</div>

Retrieveing the values from database selecting or deselecting the checkboxes JQuery

There is a problem in my jQuery. I want to retrieve the data from the database using AJAX.How I select and pass to the php file these values and get the multiple values.
For Example- when I select the checkbox the ajax will return the value of the selected checkbox. If I unselect the same checkbox then the value will be removed.
here the checkboxes are:
checkboxes.php
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="deep cleaning"/>Deep Cleaning</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="dishes"/>Dishes</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="move in/out"/>Move in/out</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside cabinets"/>Inside Cabinets</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside fridge" />Inside Fridge</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside oven" />Inside Oven</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="interior windows" />Interior windows</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="laundry + folding" />Laundry + Folding</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="green cleaning" />Green Cleaning</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="organization" />Organization</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="wipe window blinds" />Wipe Window Blinds</label>
</div>
</div>
<span id="cost"></span>
</div>
here the jQuery:
$(document).ready(function() {
var check=[];
$('input[type=checkbox]').on('change', function() {
var check=$(this).val();
console.log($(this).val());
$.ajax({
type:'POST',
data:{ "extra" : check},
dataType : "JSON",
url : "login.php",
success:function(response){
if(response){
totalCost=10+response;
$('#cost').text(totalCost);
}
}
});
});
});
here the php code-
if (isset($_POST['extra'])) {
$query=mysqli_query($con,"select price from extras where name_of_extra ='$_POST[extra]'");
while ($row = mysqli_fetch_array($query)) {
echo json_encode($row['price'],JSON_NUMERIC_CHECK);
}
}
database image-
I want to check the multiples and recieve multiple values through ajax and when i unselect the checkboxes then the value will remove from the span total. if there is any mistake then i m sorry. i am a bigner. i hope you all will support me do better thnku in advance.
HTML
<label>Total amount : </label>
<span id="totalCost">0</span>
JS
$(document).ready(function () {
var check = [];
$('input[type=checkbox]').on('change', function () {
var checked = 0; // assigning ZERO for unchecked
if ($(this).prop('checked') == true) { // checking checkbox status
checked = 1; // ONE for checked
}
var totalCost = $("#totalCost").text(); // getting previous totalcost
var check = $(this).val();
// two parameters
// data json object
// callback function
getData({"extra": check}, function (response) {
var content = '';
if (response) { //response is json object
if (checked) { // if checkbox is checked
content = '<div id="' + response['id'] + '">' + response['price'] + '</div>';
//create another variable which have div with price and id
totalCost = parseInt(totalCost) + response['price'];
// add new price in previous price
} else {
$('#' + response['id']).remove();
// remove price div targeting with id
totalCost = parseInt(totalCost) - response['price'];
// subtract price from previous price
}
$("#cost").prepend(content); // prepend new content
$("#totalCost").html(totalCost);
}
});
});
function getData(data, callback) {
$.ajax({
type: 'POST',
data: data,
dataType: "JSON",
url: "login.php",
success: callback
});
}
});
Changes in php code
if (isset($_POST['extra'])) {
$query=mysqli_query($con,"select * from extras where name_of_extra ='$_POST[extra]'");
while ($row = mysqli_fetch_array($query)) {
echo json_encode($row,JSON_NUMERIC_CHECK);
}
}

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 $this clicked element

I have the following script that sends an image URL to an input field on click (from a modal window). I am also sending that same url, imgurl to a <div class="preview-image> to show it on insertion.
var BusiPress_Configuration = {
init : function() {
this.files();
},
files : function() {
if ( $( '.busipress_upload_image_button' ).length > 0 ) {
window.formfield = '';
$('.busipress_upload_image_button').on('click', function(e) {
e.preventDefault();
window.formfield = $(this).parent().prev();
window.tbframe_interval = setInterval(function() {
jQuery('#TB_iframeContent').contents().find('.savesend .button').val(busipress_vars.use_this_file).end().find('#insert-gallery, .wp-post-thumbnail').hide();
}, 2000);
if (busipress_vars.post_id != null ) {
var post_id = 'post_id=' + busipress_vars.post_id + '&';
}
tb_show(busipress_vars.add_new_file, 'media-upload.php?' + post_id +'TB_iframe=true');
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function (html) {
if (window.formfield) {
imgurl = $('a', '<div>' + html + '</div>').attr('href');
window.formfield.val(imgurl);
window.clearInterval(window.tbframe_interval);
tb_remove();
$('.preview-image img').attr('src',imgurl);
} else {
window.original_send_to_editor(html);
}
window.formfield = '';
window.imagefield = false;
}
}
}
}
BusiPress_Configuration.init();
Sending the image URL to the editor and the div are working fine, but it is doing it for every instance of that div on the page. I've been playing around with $(this) and closest() to see if I could localize the insertion to the specific div near the input, but haven't had any luck. Any help would be greatly appreciated. Thanks!
Default markup
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row">Default Map Icon</th>
<td>
<input type="text" class="-text busipress_upload_field" id=
"busipress_settings_map[default_map_icon]" name=
"busipress_settings_map[default_map_icon]" value=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/red-dot.png" /><span> <input type="button"
class="busipress_upload_image_button button-secondary" value=
"Upload File" /></span> <label for=
"busipress_settings_map[default_map_icon]">Choose the default map icon (if
individual business type icon is not set</label>
<div class="preview-image" style="padding-top:10px;"><img src=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/red-dot.png" /></div>
</td>
</tr>
<tr valign="top">
<th scope="row">Active Map Icon</th>
<td>
<input type="text" class="-text busipress_upload_field" id=
"busipress_settings_map[active_map_icon]" name=
"busipress_settings_map[active_map_icon]" value=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/blue-dot.png" /><span> <input type="button"
class="busipress_upload_image_button button-secondary" value=
"Upload File" /></span> <label for=
"busipress_settings_map[active_map_icon]">Choose the active map icon (if
individual business type icon is not set</label>
<div class="preview-image" style="padding-top:10px;"><img src=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/blue-dot.png" /></div>
</td>
</tr>
</tbody>
</table>
Assuming you can select the button already (I changed it to "button-selector" for the meantime), use parent to get the parent td then find the child div to be changed. This will get the nearest div to your button.
$("button-selector").parent('td').find("div")

Categories