I have this code:
while($row = mysql_fetch_array($res)) {
$name = $row['advertiser'];
$id = $row['id'];
if($row['id'] % 4 == 1 || $row['id'] == 1)
{
echo "<tr>";
}
if($row['availability'] == 0)
{
$td = "<td id='green'>";
}
if($row['availability'] == 1)
{
$td = "<td id='grey'>";
}
if($row['price'] == 0)
{
mysql_query("UPDATE booklet SET availability = 0 WHERE id = '$id'");
}
echo $td . $row['id'] . "<br/><p style='font-size: 6pt;'>" . $name[0] . "<p><img src=" . $row['image'] . "></td>";
if($row['id'] % 4 == 0)
{
echo "</tr>";
}
}
It creates a table. What I want to do is this: if you click on a td, I want to pass the value of that td, for example - the number one (1), if you clicked on the first td - I want to pass this value over to a hidden input so I may later use it elsewhere.
The table looks fine. I know what to do when I have the value in a hidden input. I just need to be able to have the table, when I click on a td, to pass the value over. Or to do anything. onClick doesn't work. Even the absolute simplest isolated JQuery statements don't even come close to parsing. The most complex Javascript that actually has worked on this page is a document.write(). Everything else stumps any known browser.
So, using absolutely any methods, is it a possibility, within the realm of current technology, to have code that does what I want?
Again, I need to have a table cell, when clicked on, pass a variable to a hidden input. I've tried everything.
You'll need to add the click event with JQuery and then use Jquery to set the value... Something like this should work.
$(function() {
$("table#mytable td").mouseover(function() {
//The onmouseover code
}).click(function() {
//The onclick code
$("#hiddenInputID").val(text);
});
});
<td onclick="document.forms[0]['nameofhiddenfield'].value = this.id"> ... </td>
Try to validate your html, you might have mismatched quotes/square brackets somewhere, which breaks Javascript.
Related
I want mutliple radio buttons (number unknown, because they get created dynamcially) to have the same onClick or onChange event, whichever fits the best. I found examples for jQuery but not pure Javascript. Should i just loop trought all radio buttons on the form?
They get created in php like so:
//DB Connection already established
$sql = "SELECT * FROM users";
$results = $dbConnection->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch-assoc()){
echo "<li><input type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
}
}
else
{
echo "<p>No users found</p>";
}
How can i do that loop? Or is there any more common way of doing that?
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Or Should i just add onclick=myfunction(this) into the php file?
I want multiple radio buttons (number unknown, because they get created dynamically) to have the same onClick or onChange event.
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Let's assume that your PHP has rendered the list items and you have a common function called myFunction() which you want to use to log it's parameter to your console:
function myFunction(val){
console.log("The value is " + val);
};
Now if I understand you correctly, you want to run the above function whenever one of the rendered radio buttons are clicked and to pass the value of the value attribute of the radio button that was clicked as a parameter for the above function.
Firstly, you need to assigned all the rendered radio button in your list to a variable:
var x = document.querySelectorAll("li input");
Secondly, since x is a collection of objects (here, all the radio buttons rendered), you will now have to map through each item on x using forEach and assign a click listener on each radio button which runs the ClickItem()function passing it the item's defaultValue as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.defaultValue;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/56/
However, if by value, you mean the content after the input tag but still inside the respective li tag, then you just need to make slight changes to the above code like this:
Firstly, to prevent the selector from querying li elements from other parts of the page, you need to wrapped your list items with a div or a ul having a unique ID like this:
<ul id="someList">
//create your list items here
</ul>
Secondly, you need to assigned all the rendered list items to a variable:
var x = document.querySelectorAll("#someList li");
Thirdly, similarly to what we did above, since x is a collection of objects (here, all the list items rendered), you will now have to map through each item on x using forEach and assign a click listener on each list item which runs the ClickItem()function passing it the item's innerText as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.innerText;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/58/
Actually the JQuery make it easier, but you can do the same with pure JS.
the real concept is to capture the event bubbling, try this:
fatherElement => element that is not dynamic
fatherElement.addEventListener("click", function(event){
if(event.target.type == 'radio'){
//do something
}
});
Use this echo line instead yours:
echo "<li><input onchange='yourOnChange(event)' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
I add onchange='yourOnChange(event)' there. And of course remember to add proper js function e.g function yourOnChange(e) { console.log(e); } to your web page.
Or Should i just add onclick=myfunction(this) into the php file?
Yes, you can do that. In that case code will be;
<li><input onclick='myclick('". $row['E-Mail'] ."')' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>"
Now in JS code myclick(email) function can handle anything with email argument.
Pure JS solution:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'radio') {
if(inputs[i].checked)
{
//if radio button is checked
myClick(inputs[i].id, 'checked') //you can get anything apart from id also
}
else
{
//if radio button is not checked
myClick(inputs[i].id, 'unchecked') //you can get anything apart from id also
}
}
}
myClick(id, stat)
{
//YAY!! I have got the id
}
You can do a for of loop if you have querySelectorAll.
Here is an example:
const radios = document.querySelectorAll('input[type=radio]');
for (const element of radios ) {element.addEventListener('click', function(event) {
console.log(event.currentTarget)
})
}
Using pure JS you can select your radio buttons and add event listeners like so:
const radios = document.querySelectorAll('input[type=radio]');
radios.forEach(radio => radio.addEventListener('change', e => {
// radio is your radio button element
});
Same with jQuery:
$('input[type=radio]').change(() => {
//your code goes here
});
Depending on the user type, my page dynamically creates either a select element (for admins to change) or a div with text (for regular users) using the same id.
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher' >teacher</option>";
echo "</select></td></tr>";
}
else echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
When the page submits, I need either the .val() from the select element or the .text() from the div element.
I can't use .val() on the div element and I can't use .text() on the select element.
Is there a way in jQuery / javascript to get one or the other, depending on which element type was created?
make the else statement as so (use input[type=hidden], to use the .val())
else echo
"<tr>
<td>Type:</td>
<td>
<!-- div to show the value -->
<div>$user_type</div>
<!-- hidden input type to get the value via jQuery .val() -->
<input type='hidden' id='type' value='$user_type'>
</td>
</tr>";
Oh by the way, you can use PHP variables inside strings that are defined with double quotes echo "$someVar";
Since you are printing out from PHP the HTML out put, by the same time you can print a Javascript variable who has what method use to get the value/text. Then, use the variable in your Javascript to perform one query or other.
Something like :
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher'>teacher</option>";
echo "</select></td></tr>";
echo "<script> var method = 'val'</script>";
}
else
{
echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
echo "<script> var method = 'text'</script>";
}
You can check it with the following simple code in javascript:
if(document.getElementById("type").tagName == "SELECT") {
//Your code for admin
}
else
{
//Your code if it is not admin
}
You can have the text or the value with a simple and elegant ternary condition :
var result = $("#type").val() !== undefined ? $("#type").val() : $("#type").text();
Hoping I can get some help with this, I'm building a page that has 5 tables on them.
2 of them are sortable using (http://www.kryogenix.org/code/browser/sorttable/)
A rather large one I want it to be collapsible, and I tried using this:
HTMl drilldown table: Design
However, when I enable it, all the tables become collapsable, this is the jQuery from the above question.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('thead').on('click', function(){
$(this).next('tbody').toggleClass('collapsed');
});
});
I'm not familiar with jQuery, so wasn't sure how to modify it so it only used the one table. I tried using the table ID but it didn't work.
<?php
$qcTable = "<table id ='thcol'>";
foreach($tableArray as $cat=>$catData)
{
$title = ucwords(str_replace("_"," ",$cat));
$score = number_format($catData['sc'],2);
$qcTable .= "<thead><tr><th>$title ($score%)</th></tr></thead><tbody class='collapsed'>";
foreach($catData as $td=>$subCatData)
{if($td != 'a' && $td != 'b' && $td != 'c' && $td != 'sc'){
$getSubCat = explode("__",$subCatData['b']);
if(sizeof($getSubCat) ==1)
$subTitleBuild = $getSubCat[0];
else
{
unset($getSubCat[0]);
$subTitleBuild = implode(" > ",$getSubCat);
}
$subtitle = ucwords(str_replace("_"," ",$subTitleBuild));
$subscore = number_format($subCatData['sc'],2);
$qcTable .= "<tr><td>$subtitle ($subscore%)</td></tr>";
}
} $qcTable .= "</tbody>";
}
$qcTable .= "</table>";
echo $qcTable;
?>
The other two tables theads look like this:
<table class = 'sortable'><thead><th class='sorttable_numeric'>
Ticket ID</th><th>Game</th><th>Agent</th><th>Score</th><th>Star</th></thead><tbody>
Thank you in advance,
C
Your line
$('thead').on('click', ...);
put an handler for the click event on all your <thead></thead> tags, you should put a class on the ones you want to be able to collapse like <thead class="collapsable"></thead> when you write them in PHP, then your line of JavaScript will be :
$('thead.collapsable').on('click', ...);
In that way, only your thead tags with the class collapsable will be able to trigger the collapse.
i want to display a certain number of input tags for a form; this should depend on how many items a user dynamically selects that they want.
for example, if a user says they want 3 items. i want to display 3 input bars.
i am not clear of the best way to proceed with this. for example, i am able to determine how many items they select from the select options:
$(".howmany").change(function(){
var value = $(this).val();
}
but what is the correct way to proceed thereafter; do i dynamically render the exact number of input tags selected using a for each: or pre-display (but hide) all of the input tags and only show the exact number of input tags requested.
i would appreciate an example of how its been done . at the moment i am only able to hide the entire area. eg:
var requests = $("#howmany").val();
if (reqeusts < 1){
$('#reqeusts').hide();
}
else {
$('#reqeusts').show();
}
but i obviously need to be able to show individual form tags accordingly to the number the user selected.
hi again, i want to thank everyone for their answers.
i deeply sorry, but i forgot to mention that the reason for the confusion is that the values for the imput are dynamically fed from an array function.
public function arrayValues()
{
return $selection = array(
'0' => 'none' ,' 1' => '1 item' ,' 2' => '2 item' ,' 3' =>' 3 item' );
}
i then need to render one of the below imput select tags for each number of items selected.
<?php echo '
<select id="howmany" name="items[howmany]" />';
foreach ($arrayValues as $key => $value)
{
echo '<option value="' . $key .'">' . $value . '</option>';
}
echo'</select>';
?>
$(".howmany").change(function(){
var value = $(this).val(); // get the number of inputs
value = parseInt(value); // make sure it's an integer
htmlStr = "";
for (var i = 0; i < value; i++)
{
htmlStr += "Label " + i +" <input type='text'>";
}
$('.container').empty();
$('.container').append(htmlStr);
}
You need something like this:
$('button').click(function () {
$('div').empty().append(new Array(+$('input[type=number]').val()+1)
.join("<input type='text' placeholder='Type Something'/>"));
});
I hope this gives you an idea of how to solve your problem.
DEMO
I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.
My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:
... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
<tr><td><input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>"
value="<?php echo $row['docid'];?>"></td> ...
I have an EDIT Link as a menu in the top in view.php.
<a href="editdoc.php>Document</a>
My question : How do I pass the value of the checked checkbox when I click the edit link.
Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.
Thanks in advance.
Lakshmi
Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.
I found a solution!!!
Though I did it in a different way, I thank Jaak Kütt for all the support and helping me to think of a possible way..
This is what I did.. I named the form as showForm and moved to editdoc.php through the function itself.
My Check Box :
<form name="showForm">
<input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>" value="<? php echo $row['docid'];?>">
My Link:
<a id="a_editdoc" onclick="getchkVal();" title="Edit Document">Document</a>
The corresponding script:
<script>
function getchkVal() {
var contents, vals = [], mydocid = document.forms['showForm']['chk_docid[]'];
for(var i=0,elm;elm = mydocid[i];i++) {
if(elm.checked) {
vals.push(encodeURIComponent(elm.value));
}
}
contents = vals.join(',');
window.location="editdoc.php"+"?v="+contents;
}
</script>
In the editdoc.php :
<?php
$cval=$_GET['v'];
?>
Thanks.
make sure your inputs have different id-s..
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
...<input type="checkbox" name="chk_docid[]" class="chk_input"
id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
using jQuery:
Document
$("#editdoc").click(function(){
var selection=$("input.chk_input:checked");
if(selection.length){
var href=$(this).attr('href')+'?'+selection.serialize();
$(this).attr('href',href);
}
return true;
});
non-jQuery:
<a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
function submitWithChecked(e,className){
// fetch all input elements, styled for older browsers
var elems=document.getElementsByTagName('input');
for (var i = 0; i < elems.length; ++i) {
// for each input look at only the ones with the class you are intrested in
if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
// check if you need to add ? or & infront of a query part
e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
// append elements name and value to the query
e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
}
}
return true;
}
in editdoc.php fetch the values with php using $_GET['name_of_input_element']