Yii2: Jquery selecting id of a table cell not working - javascript

I am using Yii2 and using this jquery code to access the value of a cell(td) column. I have set the id of the column say 'room_name'
I am using this code which works fine on a form, but in grid-view(table) I am getting a blank alert.
<?php
$script = <<<EOD
alert ($('#room_name').val());
EOD;
$this->registerJs($script);
?>
Do I need to do it differently for tables, as the id is getting repeated over multiple rows.
Thanks for a suggestion.

I got it from #anpsmn. Adding for record for help to others.
$('td.room_name').each(function(){
alert($(this).text());
})

Related

jQuery responds with html table containing a (form in each row plus jquery code to edit each row) newly created forms ignore submit()

Three days and I cannot find an answer to this or a solution. I am far from being a jQuery guy.
User arrives at a php page that shows a form to choose the language code and submit. Form gets submitted and the jQuery response builds a table in a div container in the original page. So far so good. The resulting table contains hundreds of rows where the language variables can be edited. On clicking the edit button, I get nothing, no errors in console, nothing. If I use on click, I can fire an alert. On submit, bind, and many others do not work.
I am attempting to load the table, perform basic editing, submit the edits to the db, and refresh the div.table.row with the edited results. I have not gotten to the part where I refresh the rows with the edited data, still stuck trying to submit the dynamic form in each row.
One interesting thing that happens when I use on click, it works with just the first button I click on, it somehow disables all the other rows. I need to be able to submit a row for changes, have that row refresh and move on to the next row all without redirecting. Is this too much to ask? Or should I just move them from page to page?
The ajax php page returns the table using the following code:
if(!empty($_POST['edit_language']) && $_POST['edit_language'] == 1){
edit_language($_POST['lang']); //call function to edit language
} else {
echo "You got here but no variables<br>"; //testing
print_r($_POST); //testing
}
function edit_language($lang){
//query table to get language vars list
$sql = "SELECT lang_site.lid, lang_codes.iso_code, lang_codes.`language`, lang_varnames.varid, lang_varnames.varname, lang_site.varval FROM lang_codes LEFT JOIN lang_site ON lang_site.langid = lang_codes.langid LEFT JOIN lang_varnames ON lang_site.varid = lang_varnames.varid where lang_codes.iso_code = '" . $lang . "'";
$result = db_query($sql);
//generate report table
echo "<table cellspacing='0' border='1'><tr><th>Count</th><th>Language</th><th>Variable Id</th><th>Variable Name</th><th>Variable Value</th><th>Edit</th></tr>";
$a=1; //count the rows to number the rows for easy viewing
while($data = db_fetch_assoc($result)){
//create form in each tr
echo "<form name='edit_" . $data['lid'] . "' id='edit_" . $data['lid'] . "' action=''><tr><td>" . $a++ . "</td><td>" . $data['language'] . "</td><td>" . $data['varid'] . "</td><td>" . $data['varname'] . "</td><td><textarea class='form-control' name='varval' id='varval' cols='100' wrap='virtual'>" . $data['varval'] . "</textarea></td><td id='editresponse'><button type='submit' class='button' type='submit' id='but_" . $data['lid'] . "'>Edit</button></td></tr></form>";
?>
//jquery to post edits
<script language="javascript">
$(document).ready(function()
{ //using $.ajax() function
//alert("document ready"); //this alerts each row
//this function will not work, no errors, simply nothing
$(document).on("submit", "#edit_<?php echo $data["lid"]; ?>", function(e)
{
//alert("button clicked"); //this does not work
var data = $("#edit_<?php echo $data["lid"]; ?>").serialize();
$.ajax({
type : "POST",
url : "/lang/ajax_langs.php",
data : data,
success : function(response)
{
{
$("#editresponse").html(response);
};
}
});
e.preventDefault();
});
});
</script>
<?php
}
echo "</table>";
}
?>
How do I get the jQuery to submit the individual form in each row to effect an edit and then refresh each row individually as languages are edited? I need to add another form to each row to delete an entry then remove the row dynamically, but I am stuck here without being able to submit any of these forms.
I should add that this generated form shows well in the website, but is not shown in view source. Using chrome browser. I'm open to any suggestions. Thanks in advance for reading. I seriously hope I can find a solution here. Otherwise, I'm back to the 90's on this software.
It's not working because you are only submitting one id. You need to make each of your forms be of the same class. Therefore, any form clicked will be processed. Like
<form class="myForm" .....
Then, the Jquery would look like this
$(".myForm").submit(function(e){
var inputToChange = this.varval; // saw input varVal, but use whatev
var dataToChange = inputToChange.value;
// then send the data to php for processing using ajax or post
Then, use inputToChange.value = whatever new value you want to put into the form input or other div/td etc. you want to change. If you want to change data that isn't in an input, just make that td a text input and disable it from being edited by the client
<input type="text" name="lname" disabled>
then on callback send new data to this.lname.value = (many other ways to do this as well)
Don't forget, if you send through ajax you want to stop the form itself from submitting so use e.preventDefault()

Populating drop downs with MySQL entries

I have a MySQL database that contains, amongst other things, 2 tables. One is the events table, containing event names and other details. The other is the instance table. This table links the events table to a venue table and adds a date, so each row is an instance of the linked event.
I am making an event booking form for internal use for these events. I want to allow selection of the event to be booked via a dropdown list. So, I have populated one dropdown with the event names:
$qEvent = "SELECT event_name, event_id FROM events";
$rEvent = mysqli_query($dbc,$qEvent);
echo '<select>';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
What I now want to do is, for the selected event, grab all the instances associated with that event, and populate another dropdown with the dates.
Can I do this with PHP, or do I need to dip into Javascript? I think I just need some way to grab the event_id value of the dropdown selection and then query based on that, but I don't know how without Javascript.
You should be looking at Javascript or jQuery for achieving your goal. I've used jQuery based on my question to you earlier. It's also simpler and less code.
Your PHP:
Add an ID attribute event_menu to your select menu
echo '<select id="event_menu">';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
<div id="container_for_new_menu"></div>
Using jQuery:
$('#event_menu').on('change', function() {
// get selected value and build data string for AJAX
var event_selected = "event_selected="+$(this).val();
// send the selected data to a PHP page to build the populated menu
$.ajax({
url : 'populate-menu.php',
type: 'POST',
data : event_selected,
dataType : 'html',
success : function(data) {
$('#container_for_new_menu').html(data);
}, error : function() {
alert("Something went wrong!");
}
});
});
On populate-menu.php, have something like:
$event_selected = isset($_POST['event_selected']) ? $_POST['event_selected'] : null;
// do SQL query here based on user's selection
// making sure you validate the data in the POST request for malicious BS
// or use parameterized queries
// then build a new menu to send back
echo '<select>';
// loop through results and build options
echo '</select>';
This new menu will then be posted back to your original page into the container_for_new_menu element.
By the looks of it, you want to populate the "instances" dropdown based on the selection the user makes on the "event" dropdown. You cannot do this without Javascript.
My suggested way of doing this is to use AJAX to pull the instance data and populate the "instances" dropdown on change of the "event" dropdown. Useful resources below for simple AJAX get with jQuery:
http://api.jquery.com/jQuery.get/
http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/
You need some kind of Javascript to accomplish this. Either:
Basic- submit the form on select and let php populate the instance drop-down.
More elegant- use Javascript to make an Ajax call on select which will dynamically replace the instance drop-down's div.
You will need JavaScript to populate the second drop down box. I suggest you load all the values into JSON on the page and then you can just use a jQuery on change event to populate the second select box.

PHP multiple records insert

I am attempting to reword my issue.
I have a datatable that can return thousands of records, each with multiple columns. There is a checkbox in the first column that, once the user checks it, they then click a button, and the CONTAINER_NUMBER that is associated with the row is sent to a modal window to be used in a form.
Here is the code for the checkbox:
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\" name=\"checkMr[]\" /></td>";
This is the javascript that retrieves the CONTAINER_NUMBER and sends it to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
});
$(".modal-body .containerNumber").val( selectedID );
});
});
</script>
This is the section of the modal window that displays the CONTAINER_NUMBER:
<div class="modal-body">
<form action="" method="POST" id="serviceModalForm" name="serviceModalForm">
<input type="text" name="containerNumber" id="containerNumber" class="containerNumber">
Here is the section of PHP that takes the id="containerNumber" and converts it to a PHP variable. After that, there is an INSERT statement that inserts the containerNumber into a database table:
<?php
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$container = mysql_real_escapse_string(stripslashes($container));
$sql = "INSERT INTO myTable (container_num) VALUES ('$container')";
if(mysql_query($sql)){
echo "Insert complete";
}
else {
echo "Insert was not completed";
}
?>
This code is fine. It works good. It does what it's supposed to do...for when the user checks ONE checkbox. It DOES NOT work when the user checks multiple checkboxes.
Basically, from what I've been researching is that I need to separate the records from the variable $container, as there can be multiple containers in that variable, which is why the query does not work when there are more than one container numbers selected.
I need to be able to separate the container numbers and store them in an array or something. The query will read each record separately and generate multiple INSERT statements for each record.
I've tried several times to create an array and get the sql statement to recognize it, but have been unsuccessful. I'm not sure if I'm placing the array in the right place. I'm not sure if this has to be done in the javascript before the container gets sent to the modal window.
I know I need to utilize a FOREACH loop to go through the array, but like I said, I'm not sure where the array needs to go in my code.
Please help. I know I need to learn PDO or MYSQLI. I will be sure to utilize PDO or MYSQLI on my next application. Until then, please help me with this issue.
Thank you, and sorry for so much wording.
Your containerNumber will be posted as a converted string from a js array. Something like id1, id2, id3[...]
In your php code, convert the $container back to an array ($containerArray = explode(",", $container)) and construct the sql dynamically to add all the rows in a single query so that the statment becomes something like
INSERT INTO myTable (container_num) VALUES ('$containerArray[0]'), ('$containerArray[1]')[...]

How to create a textbox that display message when mouseover?

I have a sql query that obtain a string called description from the database
Also , i have a table that contain a mail list
I would like for each mail list name, when the mouse over it, it display a text block that contain the description
Are there any plugin , or how to do that? Thank you.
I use a jQuery plug-in called TipTip, which is very simple to implement.
The PHP(for the query). You can use whatever, this is an example.
<?php
$q = 'your sql query'
$query = mysql_query($query)
while($row = mysql_fetch_array($query)){
?>
<div class="email-list-name-<?=$row['id']?>"> <?=$row['email-list-name']?> </div>
<div class='description-for-email' style='display:none;'><?=$row['description']?></div>
<?php } ?>
The jQuery:
$(function(){
$('div[id^="email-list-name"]').click(function(){
$('.description-for-email').hide(); //hide all message displays
$(this).next('.description-for-email').show(); //show the next description for our email we clicked
});
});
You didn't really provide any other information, so I just threw together a general example.
You can use the title attribute of html for that or make use of tooltip . You can easily find an example of tooltip. But if you trying to fetch the data from your db on the run time..i would say thats a bad idea

How does onchange carry selected text and hidden value?

I have a dynamically populated PHP dropdown menu that gathers the following information from the database:
echo '<option value="'.$image['id'].'">'.$image['description'].'</option>';
I then have a JavaScript function that shows the selected text - description in an input box for editing and then on submit update back into the database.
Question: Is there away using JavaScript that I could pass the id and description together but only have the description show in the input box for editing?
$('#captionSelect').change(function(){
$('#captionInput').val($("#captionSelect option:selected").text()).show();
});
you can try this.
$('#captionSelect').change(function(){
$('#captionInput').val($("#captionSelect option:selected").html()).show();
});
Thanks.
hello jess Try this out....
$('#captionSelect').change(function(){
$('#captionInput').val($("#captionSelect").val());
});
You would need to add a hidden form field to your form.
Then you can use:
$('#captionSelect').change(function(){
var $selected = $("#captionSelect option:selected");
$('#hiddenField').val($selected.val());
$('#captionInput').val($selected.text()).show();
});
I added the $selected to avoid multiple look-ups.

Categories

Resources