JQuery find and closest Can't find closest input fields - javascript

I loop through some data dynamically via Ajax and than display them in table. As you see I have multiple row or <tr> , HeaderLine and Customerinfo. which I'm interesting in is CustomerInfo and the thing I'm trying do is when button is clicked, check which input fields is Empty or has no value than give an alert and for finding input fields or elements I used jQuery find() and closest() Method, but for some reason it can't find any elements.
Can anyone please help me to solve the issue?
JavaScript for checking Empty input fields before sending to server:
<script>
function AnmodomRMA(e) {
var tr = $(e).closest("table").find(".CustomerInfo");
var email = tr.find('input.Email').val();
var telefon = tr.find('input.Telefonnummer').val();
if (email === "") {
alert("Input is Empty:" + email);
return false;
}
if (telefon === "") {
alert("Input is Empty:" + telefon);
return false;
}
var formdata = $("select, textarea,input").serializeArray();
$.ajax({
"url": '#Url.Action("AutoRMAAnmoding", "User")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
console.log(data);
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
JavaScript for Load Data (dynamically into table):
<div class="card-body">
<table class="table">
<tbody id="ResultProduct"></tbody>
</table>
<div id="AppendBtnRMA">
</div>
</div>
<script>
$.ajax({
type: "GET",
url: "/User/serializeItemLineByID" + 1,
dataType: 'json',
success: function (result) {
$.each(result.findclosedorders, function (ii, e) {
var guid = uuidv4();
rows += '<tr class="HeaderLine">';
rows += '<td>some data</td>';
rows += '</tr>';
rows += '<tr class="CustomerInfo">'
rows += '<input type="hidden" name="model.InsertRMALists.Index" value="' + guid + '" />';
rows += '<td><label>Telefonnummer</label><input name="model.InsertRMALists[' + guid + '].Telefonnummer" id="Telefonnummer" type="tel"></td>';
rows += '<td><label>E-mail</label><input name="model.InsertRMALists[' + guid + '].Email" id="Email" type="text"></td>';
rows += '</tr>';
});
var btnAppend = "";
btnAppend += '<button onclick="AnmodomRMA(this);">Create RMA</button>';
$("#AppendBtnRMA").append(btnAppend);
$("#ResultProduct").append(rows);
},
})
</script>

Thanks for all help :)
Here is how did i solve the problems:
- Add a class to input fields.
- beacuse button it was out side the table, i have to select closest element around table and than find <tr> like:
var tr = $(e).closest(".card-body").find("tr.section");
and than loop through that element i want to check if it is Empty:
$(tr).each(function (i, el) {
var t = $(el).find('input.Telefonnummer').val();
if (t ==="") {
alert("empty");
}
});

In the function AnmodomRMA(e) e refers to the event itself and not the clicked button, try to use e.target:
var tr = $(e.target).closest("tr");

Related

I have dynamically generated 2 <tr> and I want to get the data of the <tr> I click

The Question might be confusing but this is the exact situation..
I have dynamically generated few ( as per data fetched from database) and now I want to allow the user to select one of the radio buttons and I want to capture the details of the row clicked so please check my code and assist
My ajax code
$.ajax({
data: data,
url: url,
type: 'POST',
datatype: 'JSON',
success: function (response) {
console.log(response);
var result = $.parseJSON(response);
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><input type='hidden' id='"+ result[i].objId + "' value='"+ result[i].objId+"'><td><input type='radio' name='dbRadio' id='dbRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponder > tbody:last').append($row);
}
console.log($row);
}
});
my radio button detection code
$('input[name=dbRadio]').change(function(){
console.log('clicked');
});
Use an instance of this and get the closest tr:
$('input[name=dbRadio]').change(function(){
console.log($(this).closest("tr"));
});
Of course, if this handler isn't being hit, it's probably because your rows are being added dynamically - so delegate the handler:
$('table.queriedResponder').on('change', 'input[name=dbRadio]', function() {
console.log($(this).closest("tr"));
});

submitting arrays to php via ajax

I am having issues figuring out how to submit a form via ajax that has items with the same name(this form is dynamically created and has to use the same names for some fields).
This is the JS code that I have
<script>
var toggle123 = function() {
var chair = document.getElementsByName('chair[]');
var item1 = document.getElementsByName('item[]');
var price = document.getElementsByName('price[]');
var table = document.getElementById('table');
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'table='+table+'';
for(i=0;i<item1.length;i++)
{
dataString += + '& item1[]' + '=' + item1[i];
}
for(i=0;i<chair.length;i++)
{
dataString += + '& chair[]' + '=' + chair[i];
}
for(i=0;i<price.length;i++)
{
dataString += + '& price[]' + '=' + price[i];
}
if (chair == '' || item1 == '') {
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
var mydiv = document.getElementById('table1');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
I want it to submit to submit.php and also to hide the div that is open (table1).
I can get it to go to submit.php but I am not sure if the data is actually getting sent there or if it is just blank. It tells me there was an invalid argument for the foreach loop in submit.php.
Here is submit.php
<?php
include('dbconfig.php');
// Fetching Values From the post method
$table = $_POST['table_id'];
foreach($_POST["item1"] AS $key => $val) {
$chair = $val;
$price = $_POST['price'][$key];
$chair = $_POST['chair'][$key];
$query = mysqli_query($dbconfig,"insert into orders(table_id, price, item, chair) values ('$table', '$price', '$item', '$chair')"); //Insert Query
echo "Form Submitted succesfully";
}
?>
This is the javascript for the dynamic form....each time a button is clicked, this adds onto the form:
listholder.innerHTML += "Chair "+row.chair+"-<input type='hidden' id='chair' name='chair[]' value='"+row.chair+"' /><input type='hidden' id='table' name='table' value='"+row.table_id+"' /><input type='hidden' id='item' name='item[]' value='"+row.item1+"' /><input type='hidden' id='price' name='price[]' value='"+row.item1+"' />" + row.item1 + " - " + row.chair + " (<a href='javascript:void(0);' onclick='deleteCar(" + row.id + ");'>Delete Car</a>)<br>";
I think my main issue is probably forming the datastring that gets passed to submit.php. If anyone could help me figure this out, that would be great!
(P.S. toggle123 is activated via a button click (that works fine)

Checkbox can not checked when added dynamically in html table

I am creating html table dynamically. Having label and checkbox in each row.
Table is being created successfully, but the checkbox are not getting checked or unchecked.
I want the whole html code as a string to use it in another function to display table in modal popup
Here is the code...
$("#btnActivate").click(function () {
$.ajax({
type: "POST",
url: "/configuration/getConfiguredSmartCrind",
dataType: "text",
success: function (response) {
var result = JSON.parse(response);
var str = "<div class='table-responsive' style='width:100%;'><table id='activateConfigurationTable' class='table fc-style'><thead><tr><th style='width:50%;'>SmartCRIND Id</th><th style='width:50%;'>Status</th></tr></thead><tbody>";
for (var i = 0; i < result.length; i++) {
str += "<tr id='" + result[i] + "'><td>" + result[i] + "</td><td><input type='checkbox' id='chk" + result[i] + "' name='check' value='check" + result[i] + "'/></td></tr>";
}
str += "</tbody></table></div>";
confirmOkModal(str, "activateConfiguration();", "", 'Continue', 'Abort');
},
error: function (textstatus, errorThrown) {
alert('error occurred');
}
});
});
confirmOkModal in my code is a bootstrap modal. That's why checkbox is not working.
In this case Two events seems to obsolete each other. I have to overcome bootstrap modals e.preventDefault() in click events.
used => e.stopImmediatePropagation(); in checkbox click event.
Checkbox is working fine.
If you want to getting checked a checkbox just add checked before end tag like <input type="checkbox" checked/>

How to get the values from dynamically generated html textboxes in asp.net

I want to fetch the values from dynamically created html textboxes in my aspx page. Now first I want to check if the textbox exists or not. If exists then I want to fetch values from these texboxes. Here is the code which I am using for creating textboxes dynamically
<script type="text/javascript">
var counter = 2;
$(document).ready(function () {
$("#addButton").click(function () {
if (counter > 3) {
alert("Limit Exceeds");
return false;
}
var $wrap = $('#TextBoxesGroup');
var dynamichtml = '<div id="div' + counter + '"><div class="mcity"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="mcity"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div><div class="mcity"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 11 + '" class="auto"/> </div>';
$wrap.append(dynamichtml);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxesGroup").find("#div"+ counter).remove();
// $("#TextBoxesGroup").find("#textbox" + counter+1).remove();
});
$(".auto").live("focus", function () {
$(this).autocomplete({
source: function (request, response) {
var textval = request.term; // $(this).val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + textval + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});
});
</script>
This code is generating textboxes generating and I am fetching data from my database using json autocomplete process.After this I am trying to send the information to another page using javascript the code that I write for this is below
<script type="text/javascript">
$(function () {
$("#btnPost").bind("click", function () {
//Create a Form
var $form = $("<form/>").attr("id", "data_form")
.attr("action", "Complete.aspx")
.attr("method", "post");
$("body").append($form);
//Append the values to be send
AddParameter($form, "txtleft", $("#txtSearchleft").val());
AddParameter($form, "txtright", $("#txtSearchright").val());
//Send the Form
$form[0].submit();
});
});
function AddParameter(form, name, value) {
var $input = $("<input />").attr("type", "hidden")
.attr("name", name)
.attr("value", value);
form.append($input);
}
</script>
This work fine for textboxes which placed default in my page. But for the textboxes that generate dynamically after these textboxes I dnt know how to send values of those textboxes to my next page
Javascript and asp.net experts please help me to resolve this
Thanks
You can get the controls values using FormCollection. Note that it works on name rather than Id.
You need to keep the count and follow some naming convention for name of your controls.
Create a asp.net hidden field and keep the control count in that. And get according the values of the hidden field.
Msdn link
well if you were to assign your form an id
you could just serialize your form and post it using ajax if you wanted
$.post("complete.aspx",$("#data_form").serialize(),function(response){
//react to the post here
});

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources