How to get name of the dropdown selected item in jquery? - javascript

If i have the bookd_ids and book_titles as follows in the database:
id | title
---------------
1 | abc
2 | xyz
3 | pqr
I have the books dropdownlist as show below:
<%= select("books", "book_id", Book.all.collect {|b|
[ b.title, b.id ] }, {:include_blank => 'Select Book'})%>
i can get the id of the books thru query this way:
var id = $("#books_book_id").val();
How to get the abc, xyz pqr titles using jquery?

var text = $("#books_book_id option:selected").text();

Have put some space between :selected
var value = jQuery("#edit-system-name :selected").text();

Related

How can I read the checked state of a checkbox within the cell of a dynamically created HTML table

I am using JS to determine the checked state of checkboxes which are contained within cells of a table which has been loaded dynamically into a web page.
The page comprises 2 fieldsets:-
+-SelectFieldset-----------------------------+
| <param1> <param2> { Load button } |
| {Update button} |
+--------------------------------------------+
+-ResultFieldset id=resultFS-----------------+
| Ref_ID Description Ready |
| +-resultTable id=outTable----------------+ |
| | 123 chair [ ] | |
| | 167 dresser [ ] | |
| | 231 sofa [ ] | |
| | ... etc... | |
| +----------------------------------------+ |
+--------------------------------------------+
Notes "[ ]" above depicts a table cell containing an input with type = checkbox;
param1, param2 are dropdown selectors
Initially the ResultFieldset is empty; and is loaded when the "Load" button is clicked (using a JQuery post statement) after the select parameters have been specified.
$.post("../listProducts.php", {
AccName: account,
From: startDate}, function(data){
$("#resultFS").after(data);
});
Once the resultTable is displayed, the user checks the checkboxes as relevant in the table rows.
Subsequently, when the "Update" button is clicked I need to loop through each table row, read that row's Ref_ID value and then, depending on the checked status of the associated checkbox, post an Update to the specified row of a MySQL table.
The code to loop through the table is:-
$("#btnUpdate").on('click', function() {
for (var i=0, row; row = outTable.rows[i]; i++) {
var rowRef = row.cells[1].textContent;
console.log( "Ref_ID = " + rowRef);
var isChecked = 0;
if (row.cells[2].firstChild.checked = true){
isChecked = 1;
// update MySQL table using rowRef;
};
console.log( "Ref_ID = " + rowRef + " Ready = " + isChecked);
};
};
This code logs the Ref_ID values as expected but I'm unable to determine the checkbox state in any row. (The checkboxes are behaving as expected on the webpage - clicking sets & unsets them.)
Please advise on how I should code for this (using either JS or JQuery). Thanks..

Sort Columns on Angularjs DataTable

I want to sort my table columns by angular-dataTables. However, it sort the productCurrency because of 'ng-if' first then only to sort the productType. Any suitable function of dataTable can sort the table correctly? Check my output:
My Output:
|Product |
|CHN Product1|
|USD Product1|
|ABC |
|BBC |
|BBC |
|ZBC |
Expected Output:
|Product |
|ABC |
|BBC |
|BBC |
|CHN Product1|
|USD Product1|
|ZBC |
You can see it was supposed to sort product by alphabet, but it sort by currency 1st then the product type.
(Edited) PS: USD & CHN is productCurrency; Product1, ABC, BBC, ZBC is productType.
Here are my code:
ViewUserType.html
<td>
<span ng-if="ctrl.productType='ABC'" translate="ctrl.productCurrency.translateKey"> {{ctrl.productCurrency}}</span>
<span translate="ctrl.product.type.translateKey">{{ctrl.productType}}</span>
</td>
Controller.js
ctrl.dtOptions = DTOptionsBuilder.newOptions().withOption('aaSorting', [[2, 'desc'], [1, 'desc']]).withOption('pageLength', 25);

Select the opposite of the union data

I had product, vendor, vendor's available day and booking tables. Currently, my search function only can search through vendor available day, but not search through booking table. I used left joins between vendor and vendor available day and compare with the selected day, time and hour. The search result works. How do I search through booking table?
Product Table
id | vendor_id | title | description
Vendor Table
id | name
Vendor Available Table
id | vendor_id | d_day | d_start_hour | d_start_minute | d_end_hour | d_end_minute
Booking Table
id | vendor_id | d_date | d_day | d_start_hour | _start_minute
Below is how I select product based on the selected day, start_hour and start_minute:
SELECT * FROM product
LEFT JOIN ( SELECT * FROM vendor GROUP BY id ) vendor
ON vendor.id = product.vendor_id
LEFT JOIN ( SELECT * FROM vendor_available GROUP BY id) vendor_available
ON vendor_available.vendor_id = product.vendor_id
WHERE ( d_day = '4'
AND (CONCAT(d_start_hour, '.' , d_start_minute) + 0.0) <= '12.15'
AND (CONCAT(d_end_hour, '.', d_end_minute) + 0.0) >= '12.15')
4 is the selected day and 12.15 is the selected hour and selected minute on the client side.
When the user selects 12.15 which is 12.15pm, the query will check which product is available between the vendor available time.
How do I use opposite union with booking table, so that the product which already booked doesn't display to users?
When using LEFT JOIN tbl, it is normal to add this to the WHERE clause (not the ON clause)
AND tbl.id IS NULL
This says that you want to return results only when the is no row in tbl.

AngularJS filter multiple words from a string in a single field

Here the idea of my problem :
Imagine, I have an user looking for a book.
As input, he can try to find the book using book title.
Let's take :
$scope.books = ["Heir Of Earth",
"Woman Of The Solstice",
"Hunters Of Next Year",
"Pilots Without Honor",
"Slaves And A Woman",
"Kings And Heroes",
"Decay Of The End",
"Fortune Of The Land",
"Rejecting My Dreams",
"Painting The Angels"];
Now I take the user query in a string :
example :
$scope.userQueryTitle = "Woman Of";
I want to get all books which where their title contains "Woman" or "Of" but NOT "Woman" AND "Of".
From there, the corresponding result should be this :
$scope.booksResult = ["Heir Of Earth",
"Woman Of The Solstice",
"Hunters Of Next Year",
"Slaves And A Woman",
"Decay Of The End",
"Fortune Of The Land"
];
I found some partial solutions to my problem such as use something like :
View:
<ul ng-repeat="book in booksResult | filter: getBooksFromTitle">
<li>{{book}}</li>
</ul>
Controller:
$scope.getBooksFromTitle = function(book){
return book.match(($scope.userQueryTitle).split(" ")[0]) ||
book.match(($scope.userQueryTitle).split(" ")[1]);
};
It works only if $scope.userQueryTitle contains only 2 words but my problem is what's about if I have 1 or 4 or n word(s) ?
getBooksFromTitle() should be flexible about this but I don't see how to deal with...
Any suggestion ?
Thanks !
This will do it for you:
$scope.getBooksFromTitle = function(book){
var queryWords = $scope.userQueryTitle.split(" ");
for(var i=0;i<queryWords.length;i++){
return book.match(queryWords[i]);
}
};
Change the getBooksFromTitle function as follows,
$scope.getBooksFromTitle = function(book){
return $scope.books.filter(function(e){ return e.match(new RegExp($scope.query.split(" ").join('|'),'i')) });
};
Try to put as many keywords you want, this should solve your problem. Cheers

1 out of 3 dropdown list creating conflict using mysql

Ok so here are the tables I have:
departments associates
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| dep_id | dep_name | date_added | | asso_id | asso_name | dep_id | date_added |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| 1 | Pick a Department| Date | | 1 | A Associate | 2 | Date |
| 2 | Department A | Date | | 2 | B Associate | 3 | Date |
| 3 | Department B | Date | | 3 | C Associate | 4 | Date |
| 4 | Department C | Date | | 4 | D Associate | 5 | Date |
| 5 | Department D | Date | | 5 | A Associate 2 | 2 | Date |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
key_list key_log
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| key_id | key_name | date_added | | id | key_assigned | key_status | assigned_to | assigned_by |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| 1 | Key 1 | Date | | 1 | Key 1 | 0 | A Associate | logged in name |
| 2 | Key 2 | Date | | 2 | Key 4 | 0 | B Associate | logged in name |
| 3 | Key 3 | Date | | | | | | |
| 4 | Key 4 | Date | | | | | | |
| 5 | Key 5 | Date | | | | | | |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
So I'm trying to create a key log where I can store key names and associate names, and if the key was logged out or in. My first issue came when trying to link dropdown menus for departments and associates. I learned that you don't put comas for joins and someone suggested to just go ahead and use multiple querys.
So after some research I went about it this way:
<?php
$dbhost_name = "localhost";
$database = "db_name";
$username = "user_name";
$password = "password";
try {
$dbo = new PDO('mysql:host='.$dbhost_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='dd.php?cat=' + val ;
}
</script>
</head>
<body>
<?Php
#$cat=$_GET['cat']; // Use this line or below line if register_global is off
if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not.
echo "Data Error";
exit;
}
$quer3="SELECT DISTINCT key_name, key_id FROM key_iv order by key_name";
$quer2="SELECT DISTINCT category,cat_id FROM category order by category";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory";
}else{$quer="SELECT DISTINCT subcategory FROM subcategory order by subcategory"; }
echo "<form method=post name=f1 action='dd-check.php'>";
// Starting of first drop down
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['cat_id']==#$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";
// This will end the first drop down list
// Starting of second drop downlist
echo "<select name='subcat'><option value=''>Select one</option>";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
// This will end the second drop down list
echo "<input type=submit value=Submit>";
echo "</form>";
?>
</body>
</html>
My problem with this is that when you select a key, and after select a department, the key originally selected gets reset and you have to go back and select the key again. You might say o well just place the keys drop down at the end. Well my intention is later to be able to select a key and with ajax or php check if the key status of that key is 0 (logged out) or 1 (logged back in), if it's on status 0, automatically select the radio button for status 1, and vise versa.
After this I did more research and found this Populate another select dropdown from database based on dropdown selection and so decided to go with this approach:
<?php
$db = new mysqli('localhost', 'carlos', 'Security5', 'testing');
$query = "SELECT dep_id, dep_name FROM department";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("id" => $row['dep_id'], "val" => $row['dep_name']);
}
$query = "SELECT ass_id, dep_id, ass_name FROM associates";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['dep_id']][] = array("id" => $row['ass_id'], "val" => $row['ass_name']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
The problem with this is again when I place the first drop down before the other two, the other two don't work, and in this case completely disappear. When I place it after the two drop downs, everything works. I know, why am I not placing it after to fix it. Well like I said before, I need this to work for specifically adding other functionality later. Than and I refuse to accept that this can't be done. Can anyone tell me why this is not working for either method, and for that matter which is the better method.
I think the problem with your second attempt is you get key_name and key_id from your query, but where you write out the values in the options you refer to key_name and id (not key_id):
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
So, fixing that up (and the lack of quotes around names, and lack of escaping of data onto HTML):
<?php
$querykeys = "SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
printf("<select name='key_names'>\n");
printf("<option value=''>Select Key</option>\n");
foreach ($dbo->query($querykeys) as $row) {
printf("<option value='%s'>%s</option>",
htmlentities($row['key_id'], ENT_QUOTES),
htmlentities($row['key_name'], ENT_QUOTES)
);
}
echo "</select>\n";
?>

Categories