jquery - identify items by class and then extract value - javascript

I have the following hidden input field on my form:
<input class="dow" id="hidden_dow0" type="hidden" value="m,t,w,r,f,s,n">
Once the form has loaded I need to find this hidden control, extract the value... and then use each item in the list ('m,t,w ') to set corresponding checkboxes on
So far, I have been able to find all hidden inputs, but I don't know how to extract the value from it.
Here's what I have so far:
$('.dow ').each(function (i, row) {
var $row = $(row);
var $ext = $row.find('input[value*=""]');
console.log($ext.val); //fails.
});
EDIT 1
This is I tried:
//find all items that have class "dow" ... and
$('.dow ').each(function (i, row) {
var $row = $(row);
console.log(i);
console.log(row); //prints the <input> control
//var $ext = $row.find('input[value*=""]');
var $ext = $row.find('input[type="hidden"]');
console.log($ext); //prints an object
$ext.each(function() {
console.log( $(this).val() ); //does not work
});
});

In jQuery val() is a function.
The .dow element is the input, you don't need to find it
$('.dow ').each(function (i, row) {
console.log( $(this).val() ); //works
});

Related

Get Selected Row Value In Kendo Grid

I'm able to get the selected row in kendo grid, But I'm unable to get the specific selected row data in detail grid.
One thing that I expect is just get the Ticket_ID field string "5d484b061bf03".
I've tried to make my code just like this:
function onChange(arg) {
var selected = $.map(this.select(), function(item) {
return $(item).text();
});
myWindow.data("kendoWindow").open();
undo.fadeOut();
console.log(selected.TICKET_ID);
}
But just getting "undefined".
Any well thought to advise will be appreciated.
Thanks
jQuery $.map returns an array constructed of return values, and you are returning strings.
See Telerik example in API reference for kendo.ui.Grid change to see more about getting the data items used to construct the selected grid rows. The data items will have a field corresponding to the ticket_id value. The name of the field is case-sensitive.
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
console.log (dataItem);
selectedDataItems.push(dataItem);
}
// selectedDataItems contains all selected data items
}
you can get and persist selected row on a specific page after edit or paging in change and databound events like this:
Grid_OnRowSelect = function (e) {
this.currentPageNum = grid.dataSource.page();
//Save index of selected row
this.selectedIndex = grid.select().index();
}
.Events(e => e.DataBound(
#<text>
function(e)
{
//جهت نمایش صحیح پیجینگ
var grid = $("#Grid").data("kendoGrid");
grid.pager.resize();
//در صورت تغییر صفحه، سطر را انتخاب نکند
if(this.currentPageNum == grid.dataSource.page())
{
//انتخاب مجدد سطر انتخاب شده قبل از ویرایش
var row = grid.table.find("tr:eq(" + this.selectedIndex + ")");
grid.select(row);
}
}
</text>)
)

Deleting multiple rows of a table with Jquery and ajax

I want to be able to delete checkbox-selected rows but when I click on "Delete Selected", both the table on the web page and MySQL database stay unchanged. How do I get the selected rows from both the web page and the database to be deleted?
Edit: I'm now able to delete the rows but only the first row, despite selecting more than one checkbox, or selecting another checkbox not on the first row. Also, if I want to delete another entry, I will have to first refresh the page before deleting another one.
datatable.php
<div class="row well">
<a type="button" class="delete_all btn btn-primary pull-right">Delete Selected</a>
</div>
<script type="text/javascript">
$(document).ready(function($)
{
function create_html_table (tbl_data) {
tbl +='<table>';
tbl +='<thead>';
tbl +='<tr>';
tbl +='<th rowspan="3"><input type="checkbox" id="master"></th>';
// More table headers
tbl +='</tr>';
tbl +='</thead>';
tbl +='<tbody>';
$.each(tbl_data, function(index, val)
{
var row_id = val['row_id'];
//loop through ajax row data
tbl +='<tr id="row" row_id="'+row_id+'">';
tbl +='<td><input type="checkbox" class="sub_chk"></td>';
tbl +='<td>'+(index + 1)+'</td>';
tbl +='<td><div col_name="filename">'+val['filename']+'</div></td>';
// More data
tbl +='</tr>';
});
tbl +='</tbody>';
tbl +='</table>';
}
var ajax_url = "<?php echo APPURL;?>/ajax.php" ;
// Multi-select
$(document).on("click","#master", function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
var ele_this = $('#row') ;
var row_id = ele_this.attr('row_id');
var allVals = [];
$(".sub_chk:checked").each(function()
{
allVals.push(row_id);
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var data_obj=
{
call_type:'delete_row_entry',
row_id:row_id,
};
ele_this.html('<p class="bg-warning">Please wait....deleting your entry</p>')
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
}
else if(d1.status == "success")
{
ele_this.closest('tr').css('background','red').slideUp('slow');
}
});
}
});
});
</script>
ajax.php
//--->Delete row entry > start
if(isset($_POST['call_type']) && $_POST['call_type'] =="delete_row_entry")
{
$row_id = app_db()->CleanDBData($_POST['row_id']);
$q1 = app_db()->select("select * from data where row_id='$row_id'");
if($q1 > 0)
{
//found a row to be deleted
$strTableName = "data";
$array_where = array('row_id' => $row_id);
//Call it like this:
app_db()->Delete($strTableName,$array_where);
echo json_encode(array(
'status' => 'success',
'msg' => 'deleted entry',
));
die();
}
}
//--->Delete row entry > end
I've seen other similar SO questions like this one but I don't think it is applicable to my code.
My output:
To achieve what you want, you have to select the good elements the right way. For example, an HTML id must be unique, so giving all your elements the same id="row" won't work. Using your class will be enough. Then you have to consider that each will execute the function separately for all your selected elements, so that if you want to do things for each element, all the code must be inside.
I optimized a little your code by getting rid of allVals variable, if its only goal is to test if rows have been selected, you can directly test .length on your selection. I renamed variables so that it's more clear which is what.
Also it's not very clear in the question if the "Please wait....deleting your entry" text should appear in the button or in each row, i assumed it was in the button, and it will help you differentiate all elements from how they are selected.
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
//'click' is called on the button, so 'this' here will be the button
var button = $(this) ;
var checked_checkboxes = $(".sub_chk:checked");
if(checked_checkboxes.length <=0)
{
alert("Please select row.");
}
else {
button.html('<p class="bg-warning">Please wait....deleting your entry</p>');
//next code will be executed for each checkbox selected:
checked_checkboxes.each(function(){
var checkbox = $(this);
var row_id = checkbox.attr('row_id');
var data_obj=
{
call_type: 'delete_row_entry',
row_id: row_id,
};
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
//you still have to do something with your message, keeping in mind that a separate message will be generated for each separate $.post (one is emitted for each checked checkbox)
}
else if(d1.status == "success")
{
checkbox.closest('tr').css('background','red').slideUp('slow');
}
});
});
}
});

Javascript find select element in a table cell

I got a table column with selects and text value cells like this:
<tr>
<td data-key="data1">some text data</td>
</tr>
<tr>
<td data-key="data2">
<select>
<option>1_option</option>
<option>2_option</option>
</select>
</td>
</tr>
I need to grab the data depending on the type of data in the cell. I do it like this:
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var localobj = {};
var cell = $row.find(':nth-child(1)');
dataattr = cell[0].getAttribute('data-key');
var selectObject = cell.find("select");
console.log(selectObject);
if(selectObject){ // always true here, but I need false if there is no select in the cell
localobj[dataattr] = selectObject.val();
}else{
localobj[dataattr] = cell.text();
}
return localobj;
}).get();
It grabs selected values correctly but cannot get the text ones because it always returns true in my if evaluation. Any ideas how to fix it?
Thank you
jQuery wraps everything in it's own object container and therefore selectObject will always evaluate to true as it is an object that is not undefined or null.
You can simply check to make sure the object has at least 1 element via
if (selectObject.length > 0) { ... }
try like this
var tbl = $('#tblHours');
tbl.find('tr').each(function(){
$(this).find('td').each(function(){
alert($(this).find('select :selected').val());
});
});
As
As explained by #Arvind Audacious, jQuery always returns a container. You cannot assume the result of the query is NULL. Instead, you need to check its length in order to verify if it has actually retrieved any elements. See code below for example:
$('#myTable tbody tr td').each(function(){
var selectObject = $(this).find('select');
if(selectObject.length == 0) {
console.log($(this).text())
} else {
console.log(selectObject);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Checking jQuery selector object won't work, as it will be always true. Checking the length of the selector return is the best approach for this. Please check the fiddle - https://jsfiddle.net/nsjithin/r43dqqdy/1/
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var localobj = {};
var td = $row.find('td').first();
var dataattr = td.attr('data-key');
var select = td.find('select');
if(select.length > 0){
console.log(select);
if(select.find('option:selected').length > 0){
localobj[dataattr] = select.val();
}
else{
// If not selected. What to do here??
}
}
else{
localobj[dataattr] = td.text();
}
return localobj;
}).get();
console.log(obj);

JQuery display checkboxed table row data

So I know there are a few posts about this but I haven't found them to helpful so I'm hoping this will shed new light on my problem.
I'm trying to to get data from a check-boxed row in a HTML table. At the moment I only want to display it on a windows.alert or in the Visual Studio console. But eventually I'm going to post the data to a database.
My code:
$(document).ready(function () {
$('#button').click(function () {
var id = [];
$(':checkbox:checked').each(function (i) {
id[i] = $(this).val();
});
if (id.length === 0) {
alert("Please select at least one checkbox");
}
else {
$.post('http://localhost/Dynamic/?Insert');
}
});
});
I've tried alert($(this).text()) but that just appears empty.
Help would be appreciated.
If it helps this is how I populate the table:
var tableName = 'table1'
$.ajax({
url: 'http://localhost/Dynamic?prod=' + tableName,
dataType: 'Json',
success: function (Results) {
$.each(Results, function () {
var row = "";
for (i = 0; i < this.length; i++) {
var input = '<td>' + this[i] + '</td>';
row = row + input;
}
$('#table1 tbody:last-child').append('<tr>' + row + '<td> <input class="checkBox" type="checkbox" id="count"/> </td></tr>');
});
}
});
As you can see the table is populated dynamically so it can be populated by different tables.
your selector is wrong. $(':checkbox:checked') should be $('.checkbox:checked').
maybe try to change to different class name.
$('.mycheckbox:checked').each(function (i) {
id[i] = $(this).val();
});
I've gotten it to work, I created a global array and added all the values to that. I then created a counter and set each checkbox's ID to the counters value. I then increment the counter before looping back around to sort with the next row of data.
Then When I want to choose data. I check the checkbox's of the data. Press the button then I get the Id's of each of the checkbox's. I then put the checkbox id into the array to get the value before adding it to an array which I then post.

Javascript/jquery write each text value from :selected option to separate input

I'm retrieving some data from MySQL and write it in certain select tags, then i retrieve every selected option value and display it in a DIV, here is the javascript:
function main() {
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div#one").text(str);
})
.trigger('change');
}
So, i want each retrieved value to be written in separate input:
First value: <input type="text" id="test" />
Second value: <input type="text" id="test2" />
Third value: <input type="text" id="test3" />
How can i do that? Many thanks!
Simple select always have a selected value, so you can try something like this:
$(function() {
$("select").change(function() {
var str = "";
$("select").each(function() {
str += $(this).val()+"<br/>";
});
$("div#one").html(str);
});
});
You can see in action here: http://jsfiddle.net/vJdUt/
For adding the selected options in a "div" tag:
//empty div at start using .empty()
$("select").change(function () {
//get the selected option's text and store it in map
var map = $("select :selected").map(function () {
var txt = $(this).text();
//do not add the value to map[] if the chosen value begins with "Select"
return txt.indexOf("Select") === -1 ? txt + " , " : "";
}).get();
//add it to div
$("#one").html(map);
});
For adding the selected options in an "input" tag:
//empty textboxes at start using .val("")
$("select").change(function () {
var text = $(":selected", this).text() //this.value;
//get the index of the select box chosen
var index = $(this).index();
//get the correct text box corresponding to chosen select
var $input = $("input[type=text]").eq(index);
//set the value for the input
$input.val(function () {
//do not add the value to text box if the chosen value begins with "Select"
return text.indexOf("Select") === -1 ? text : "";
});
});
Consolidated demo
http://jsfiddle.net/hungerpain/kaXjX/

Categories