Advance note: I have already looked at and looked at and tried the solutions in the SO question: Jquery checkbox change and click event. Others on SO deal more with reading the values rather than the issue that the event is not firing.
I will admit that I am a relative newbie to JQuery.
I am trying to make two changes. One when a text field changes and one when a checkbox is toggled. Both are within a form. The idea is that if the text field changes a computation is done and the return value is written into the text after the checkbox. The checkbox toggles that text on and off.
Once finished the form can be submitted.
the code (as seen below) also uses php.
I've pulled the relevant code. I read several examples on line so there is are attempts using
<span id="foo"><input></span>
<input class='romanCheck' id='romanCheck' type='checkbox'>
Neither alert is being called. JSFiddle kinda barfed on the PHP. For the checkbox I've tried both .change() and .click()
The browsers I've tested on are all Mac (my dev environ)
Safari: 7.0.3 (9537.75.14)
Chrome: 33.0.1750.152
Firefox: 28.0
I've attached the relevant code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Not Working.php</title>
<link rel="stylesheet" href="jquery-ui-1.10.4.custom/css/ui-lightness/jquery-ui-1.10.4.custom.css">
<script src="jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
</head>
<body>
<script>
function romanize (num) {
return "(" + "roman for " + ")";
}
$(document).ready(function(){
$(".romanCheck").live("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$("span.iterationField input").live("change",function() {
alert("#iteration.change has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
</script>
<form action='EventValidateProcess.php' method='post'>
<?php
$doesShow = 1;
$isRoman = 1;
$iteration - 13;
print "<table>\n";
print "<tr>\n\t<td>Iteration</td>\n\t";
print "<td><span id='iterationField'><input type='text' name='iteration' value='" . $iteration . "'></span></td>\n\t";
print "<td><input type='checkbox' name='doesShow' value='1'";
if ($doesShow == 1) {
print " checked";
}
print "> visible | ";
print "\n<input class='romanCheck' id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print "> uses Roman numerals\n";
print "<span id='romanDisplay'>(XX)</span></td>\n</tr>\n";
?>
</table>
<button type='submit' name='process' value='update'>Update</button><br/>
</form>
</body>
.live() deprecated: 1.7, removed: 1.9
Use .on() as you are using jquery-1.10.2
Syntax
$( elements ).on( events, selector, data, handler );
$(document).on("change", "span.iterationField input" ,function() { //code here });
$(document).on("change", ".romanCheck" ,function() { //code here });
span.iterationField is not exist, instead span#iterationField,
and just use:
$(document).ready(function(){
$("input.romanCheck").on("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
Note: make sure jquery library in imported
After a lot of finessing it seemed the answer that worked best was the following:
$(document).change("input.romanCheck", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$(document).change("input.iterationField", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
Using:
print
"<input id='iterationField' type='text' name='iteration' value='";
print $iteration . "'/>";
print
"<input id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print ">";
print "<span id='romanDisplay'>";
if ($isRoman == 1) {
print "(" . $romanIteration . ")";
}
print "</span>";
Im not sure what is your problem but try this.
function romanclick(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//your code romanclick
$('span.iterationField input').click(function(){
textchange();// call it again
});
}
function textchange(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//change text code
$('.romancheck').click(function(){
romanclick();// call it again
});
} ;
1.$(document).on("change", "span.iterationField input" ,function() { //call your function here });
2.$(document).on("change", ".romanCheck" ,function() { //call your function here });
Related
I have a problem similar to this resolved question here link!
There are many great answers in this link even extending the OP's problem to multiple radio groups.
(My formatting is the same as in the link but) my problem is that I don't have more than two radio groups, but rather multiple elements in my radio groups using a FOREACH loop.
My PHP is below followed by the script.
<?php
$query = mysqli_query($con, "SELECT example
FROM example_DB ");
while ($row = mysqli_fetch_assoc($query)){
foreach($row as &$value) {
if ($value == NULL) {
echo "";
}
else {
?>
<form method="post">
<input data-group="A" class="A" type="radio" value="<?php echo"$value<br />\n";?>">
<?phpecho"$value<br />\n";}}}?>
</input>
</div>
<div>
<?php
$query = mysqli_query($con, "SELECT example
FROM example_DB");
while ($row = mysqli_fetch_assoc($query)){
foreach($row as &$value) {
if ($value == 0.00) {
echo "";
}
else {
?>
<input data-group="A" class="A" ID="A" type="radio" value="<?php echo"$value<br />\n";?>">
<?php
echo"$value<br />\n";
}}}
?>
</input>
</div>
</form>
Im using the script that came with one of the answers in the link:
<script>
$( document ).ready(function() {
$(function() {
var radios = $('[type=radio]');
$('input:radio').change(function(){
var index = $( this ).index( $('[name=' + this.name + ']') );
var groups = [];
radios.not( $('[name=' + this.name + ']') )
.each(function(v,i) {
$.inArray(this.name, groups) > -1 || groups.push( this.name );
});
$.each(groups, function(i,v) {
$('[name=' + v + ']').eq( index ).prop( 'checked', true );
});
});
});
});
</script>
Try this : You can read the name of selected radio button and find all radio button with same name to select them.
NOTE - $(document).ready(.. and $(function(){.. both are same, so you can use any one of them and not both at same time.
$(function() {
$('input:radio').change(function(){
var name = $(this).prop('name');
$('input:radio[name="'+name+'"]').prop('checked',this.checked);
});
});
EDIT- As OP want to select all radio button with same class name or value, use following code -
For Same Class -
$(function() {
$('input:radio').change(function(){
var className = $(this).prop('class');
$('input:radio[class="'+className +'"]').prop('checked',this.checked);
});
});
For Same Value -
$(function() {
$('input:radio').change(function(){
var radioVal = $(this).val();
$('input:radio[value="'+ radioVal +'"]').prop('checked',this.checked);
});
});
Hi I am trying to add some function which only allows the user to select up to 4 checkboxes at a time, but failing miserably... php and javascript don't seem to be working together very well!
my PHP code is:
<?php
echo "<form method='post' name='time' action='timeinsert.php'>";
echo "<td><input type='checkbox' `name='$displayTime2'onclick='KeepCount()'></td>";
echo "</form>";
?>
my Javascript code is:
<script language="JavaScript">
<!--`
function KeepCount() {
var NewCount = 0
if (document.time.<?php"$displayTime2"?>.checked)
{NewCount = NewCount + 1}
f (NewCount == 4)
{
alert("Pick maximum of 4 time slot's Please")
document.time; return false;`
}
//-->
</script>
Using jQuery:
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'>
</script>
<script type='text/javascript'>
$(function() {
$('input[type=checkbox]').click(function () {
var count = $('input[type=checkbox]:checked').length;
if (count > 4) alert('Pick maximum of 4 time slots please!');
});
});
</script>
<?php
echo "<form method='post' name='time' action='timeinsert.php'>";
echo "<td><input type='checkbox' name='$displayTime2'></td>";
echo "</form>";
?>
UPDATE: To prevent further checks from happening after 4 clicks, you can do this:
<script type='text/javascript'>
$(function() {
$('input[type=checkbox]').click(function () {
var count = $('input[type=checkbox]:checked').length;
if (count > 4) {
$(this).removeAttr('checked');
alert('Pick maximum of 4 time slots please!');
}
});
});
</script>
<script language="JavaScript">
var NewCount = 0;
function KeepCount()
{
if(NewCount <= 4)
{
if (document.time.<?php echo $displayTime2; ?>.checked)
{
NewCount = parseInt(NewCount)+1;
}
}
else
{
alert("Pick maximum of 4 time slot's Please");
return false;
}
}
</script>
Okay I have now edited Stefan's code and come up with:
<script type='text/javascript' src='includes/jquery-1.9.1.min.js'>
</script>
<script type='text/javascript'>
$(function() {
$('input[type=checkbox]').click(function () {
var count = $('input[type=checkbox]:checked').length;
if (count > 4) alert('Pick maximum of 4 time slots please!');
if (count > 4) $(this).removeAttr("checked");
});
});
</script>
this alerts the user and removes and ticks after 4 checkboxes have already been selected. Is it possible to add
$(this).removeAttr("checked");
to the first if statement rather than adding another line of code?
I've a php for loop which finds data from an Json object, and creates based on these information different divs and different links:
echo $remoteTownFB . " - " .
"<a href=\"#\" id=" . $remoteTownFB . "_trigger>" .$eventName . "</a></br>";
After that, I wrote a Java Script to create different divs (with different names) wich should pop up on mouseover (with a Jquery Script)
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
document.getElementById('pop-up').appendChild(samplediv);
document.getElementById('pop-up').appendChild(txt);
</script>
My problem is now the Jquery Script. I tried around with $.each on an Array where every Town name is in, but I couldn't figure it out.
This is my base:
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('a#trigger').hover(function(e) {
$('div#pop-up').show().;
}, function() {
$('div#pop-up').hide();
}
);
$('a#trigger').mousemove(function(e) {
$("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
Any help or ideas?
First of you forgot to close the id-property:
echo $remoteTownFB . " - " .
"" .$eventName . "</br>";
Then, for the pop-up to work you could try:
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
samplediv.style.display = 'none';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
samplediv.appendChild(txt);
document.getElementById('pop-up').appendChild(samplediv);
</script>
The jquery part would be:
<script type="text/javascript">
$(function() {
$('a[id$="_trigger"]').hover(
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).show();
},
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).hide();
}
);
});
</script>
I'm not really sure what you are trying to do with the mousemove call so I left that alone.
I actually converted the html checkboxes into images(below is the code), now the checkboxes have 3 states one for checked, one for unchecked and one for null,
now i want to add a DRAG feature to it like if we select unchecked and drag on other checkboxes, the other checkboxes should get this value, i meam the image must be changed.
Here is an example on this link http://cross-browser.com/x/examples/clickndrag_checkboxes.php , this example is without images but i want the same thing to happen with images.
Any help will really make my day, Thanks!
here is the code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var inputs;
var checked = 'checked.jpg';
var unchecked = 'unchecked.jpg';
var na = 'na.jpg';
function replaceChecks()
{
//get all the input fields on the funky_set inside of the funky_form
inputs = document.funky_form.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i < inputs.length; i++)
{
//check if the input is a funky_box
if(inputs[i].className == 'funky_box')
{
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].value == 0 )
{
img.src = unchecked;
inputs[i].checked = false;
}
else if(inputs[i].value = 1 )
{
img.src = checked;
inputs[i].checked = true;
}
else if(inputs[i].value = 2 )
{
img.src = na;
inputs[i].checked = true;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set name
img.name = 'checkImage'+i;
//set image
img.onclick = new Function('checkChange('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
}
}
}
//change the checkbox status and the replacement image
function checkChange(i)
{
if(inputs[i].value==0)
{
inputs[i].checked = true;
inputs[i].value = 2;
document.getElementById('checkImage'+i).src=na;
}
else if(inputs[i].value==1)
{
inputs[i].checked = false;
inputs[i].value = 0;
document.getElementById('checkImage'+i).src=unchecked;
}
else if(inputs[i].value==2)
{
inputs[i].checked = true;
inputs[i].value = 1;
document.getElementById('checkImage'+i).src=checked;
}
}
setTimeout(function(){replaceChecks();}, 0);
</script>
</head>
<form name="funky_form" action='checkkkkkkkkkkkkkkkkkkkkkkkkk.php' method='POST'>
<table id="table1" border=1px cellpadding=1px cellspacing=1px>
<tr>
<th>D/T</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
<th>20</th>
<th>21</th>
<th>22</th>
<th>23</th>
<th>24</th>
</tr>
<?php
$days = array('SUN');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"sun${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
$days = array('MON');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"mon${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
?>
</table>
</form>
It really is quite simple, bind an event to mousedown and not click, set a variable to indicate that the button is held down and at the same time check/uncheck the current checkbox etc.
Set another event to the mouseenter event of any checkbox, then check it the mousebutton is held down, and set the state to the same as the first checkbox where the mousebutton was first pressed down.
var state = false, mouse=false;
$('checkbox').on({
click: function(e) {
e.preventDefault();
},
mousedown: function(e) {
this.checked = !this.checked;
state = this.checked;
if(e.which === 1) mouse = true;
},
mouseup: function(e) {
if(e.which === 1) mouse = false;
},
mouseenter: function(e) {
if (mouse) this.checked = state;
}
});
Here's a fiddle to show how : FIDDLE
This will still have some bugs in it, and will need some additional checks etc. but it's basically how it's done.
I'm not going to go through all your code with bits of PHP and javascript sprinkled in it, you should probably have set up a fiddle with the HTML and some images if that is what you wanted, so you'll have to figure out how and where to switch the images yourself, but that should be pretty straight forward
There are several ways to add event listeners. The following concept can also be used using jQuery (and personally what I prefer).
object = document.getElementById("objectName");
$(object).bind('dragstart', eventStartDrag);
$(object).bind('dragover', eventStartDrag);
$(object).bind('drag', eventDragging);
$(object).bind('dragend', eventStopDrag);
And there are jQuery shortcuts such as:
$(object).mousedown(eventMouseDown);
$(object) is the object you want to listen for the event. Not all browsers support event capturing (Internet Explorer doesn't) but all do support event bubbling, so I believe the most compatible code is adding the event listener without jQuery.
object.addEventListener('mousedown', eventStartDrag, false);
According to this post, the preferred way of binding an event listener to a document in jQuery is using .on() rather than .bind(), but I have not tested this yet.
Hope this helps.
I guess that jQuery Draggable and Droppable could help you.
SAMPLE CODE
One more SAMPLE without drag and drop that is more similar to your example with regular checkboxes.
I have some code that involves clicking on a button and either you are logged in and you go to the next page or you are logged out and you get an alert. I have never liked onClick inside HTML and so I would like to turn this around into clicking on the id and having the jQuery do its magic.
I understand the click function of jQuery, but I don't know how to put do_bid(".$val["id"]."); down with the rest of the Javascript. If I haven't given enough information or if there is an official resource for this then let me know.
<li class='btn bid' onclick='do_bid(".$val["id"].");'> Bid </li>
<script>
//Some other Javascript above this
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
</script>
UPDATE: This is the entirety of the Javascript code. I think none of the answers have worked so far because the answers don't fit the rest of my Javascript. I hope this helps
<script language="JavaScript">
$(document).ready(function(){
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "" + s + "";
}
function CountBack() {
<?
for($i=0; $i<$total_elements; $i++){
echo "myTimeArray[".$i."] = myTimeArray[".$i."] + CountStepper;";
}
for($i=0; $i<$total_elements; $i++){
echo "secs = myTimeArray[".$i."];";
echo "DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,1000000));";
echo "DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));";
echo "DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));";
echo "DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));";
echo "if(secs < 0){
if(document.getElementById('el_type_".$i."').value == '1'){
document.getElementById('el_".$i."').innerHTML = FinishMessage1;
}else{
document.getElementById('el_".$i."').innerHTML = FinishMessage2;";
echo " }";
echo "}else{";
echo " document.getElementById('el_".$i."').innerHTML = DisplayStr;";
echo "}";
}
?>
if (CountActive) setTimeout("CountBack()", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor, id) {
document.write("<span id='"+ id +"' style='background-color:" + backcolor + "; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined") BackColor = "white";
if (typeof(ForeColor)=="undefined") ForeColor= "black";
if (typeof(TargetDate)=="undefined") TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined") DisplayFormat = "%%D%%d, %%H%%h, %%M%%m, %%S%%s.";
if (typeof(CountActive)=="undefined") CountActive = true;
if (typeof(FinishMessage)=="undefined") FinishMessage = "";
if (typeof(CountStepper)!="number") CountStepper = -1;
if (typeof(LeadingZero)=="undefined") LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0) CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
var myTimeArray = new Array();
<? for($i=0; $i<$total_elements; $i++){?>
ddiff=document.getElementById('el_sec_'+<?=$i;?>).value;
myTimeArray[<?=$i;?>]=Number(ddiff);
<? } ?>
CountBack();
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
}</script>
If you want to attach click event handler using jQuery. You need to first include jQuery library into your page and then try the below code.
You should not have 2 class attributes in an element. Move both btn and bid class into one class attribute.
Markup change. Here I am rendering the session variable into a data attribute to be used later inside the click event handler using jQuery data method.
PHP/HTML:
echo "<li class='btn bid' data-bid='".$val["id"]."'>Bid</li>";
JS:
$('.btn.bid').click(function(){
do_bid($(this).data('bid'));
});
If you don't want to use data attribute and render the id into a JS variable then you can use the below code.
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
$('.btn.bid').click(function(){
if(!loged_in){
alert('You must log in to bid!');
}
else{
do_bid(loged_in);
}
});
First, you need to make the <li> have the data you need to send, which I would recommend using the data attributes. For example:
echo "<li class=\"btn bid\" data-bid=\"{$val['id']}\">Bid</li>";
Next, you need to bind the click and have it call the javascript method do_bid which can be done using:
function do_bid(bid){
//bid code
}
$(function(){
// when you click on the LI
$('li.btn.bid').click(function(){
// grab the ID we're bidding on
var bid = $(this).data('bid');
// then call the function with the parameter
window.do_bid(bid);
});
});
Assuming that you have multiple of these buttons, you could use the data attribute to store the ID:
<li class='btn' class='bid' data-id='<?php echo $val["id"]; ?>'>
jQuery:
var clicked_id = $(this).data('id'); // assuming this is the element that is clicked on
I would add the id value your trying to append as a data attribute:
Something like:
<li class='btn' class='bid' data-id='.$val["id"].'>
Then bind the event like this:
$('.bid').click(function(){
var dataId = $(this).attr('data-id');
doBid(dataId);
});
You can store the Id in a data- attribute, then use jQuery's .click method.
<li class='btn' class='bid' data-id='".$val["id"]."'>
Bid
</li>
<script>
$(document).ready(function(){
$("li.bid").click(function(){
if ("" === "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>") {
alert('You must log in to bid!');
}
else {
document.location.href="item.php?id=" + $(this).data("id");
}
});
});
</script>
If you are still searching for an answer to this, I put a workaround.
If data is not working for you, try the html id.
A working example is here: http://jsfiddle.net/aVLk9/