Check different radio buttons at the same time with jquery [Extension] - php

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);
});
});

Related

Get drop down list options based on selected checkbox value

I have the following codes that generate checkboxes from database
< table class="table">
< thead>
< /thead>
< th>
<?php
$oaNamesQuery = "SELECT DISTINCT oaName FROM oaDetails";
$oaNamesQueryExecute = mysqli_query($conn, $oaNamesQuery);
while($oaNamesQueryRow = mysqli_fetch_array($oaNamesQueryExecute)){
$oaName = $oaNamesQueryRow['oaName'];
echo '<div class = "checkbox-group" required style="float:left; margin-right: 25px;"> <input class="checkBoxes" type="checkbox" id="checkBoxArray" name="checkBoxArray[]" value="'.$oaName.'"> '.$oaName.'</div>';
}
?>
< /th>
< /table>
There is another input box as below whereby input type is number
<div class="col-sm">
<label for="numberOfShiftPerDay">Number</label>
<input type="number" class="form-control" id="numberOfShiftPerDay" name="numberOfShiftPerDay" placeholder="No: " onchange="disablingRoutine()" min="1" max="4">
</div>
Example UI as below
When I enter some number, there will be a drop down menu appear according to the number I entered. Eg: If keyed in 1, there will be one drop down list will appear as below using jQuery 'OnChange'. The UI will be as below
What I Need
I need the drop down menu options to be based on user selected checkboxes. Eg: If the user selected checkboxes X, Y and XX, then these drop down list should show X, Y and XX. Can someone help me how to do this?
Edit 1
Added Javascript function on the change routine as suggested by stackoverflow member. But now having duplicate issues. Below the code that I changed
if ($("#numberOfShiftPerDay").val() == 1) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift1').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 2) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift2').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 3) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift3').append('<option>' + cval + '</option>')
});
} else {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift4').append('<option>' + cval + '</option>')
});
}
You can get the selected checkbox values and append to your dropdown list in your onchange function.
Try this:
function disablingRoutine()
{
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
$('#dropdownID').append('<option>'+cval+'</option>')
});
}
Edit 2
function disablingRoutine()
{
cdata = '';
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
cdata += '<option>'+cval+'</option>';
});
$('#dropdownID').html(cdata)
}

JQuery ignoring click() and change()

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 });

jQuery autocomplete function not working?

I have a page where a user can click a button which says "Add a Skill" and then it should display an input box where you type in your skill, it should display another input box where your skill level should appear and then a horizontal slider where you select your skill level.
I have table in the database called 'skill_list' which has two columns: id and name. The name field will contain thousands of skills in it which you can select from.
I also need the functionality for it to only post the form if the skill exists in the database.
What I am asking is how to get the autocomplete working with jQuery based on my current code or could someone rewrite it slightly for me?
At the moment I have the following code and it throws up no errors in the firebug console and everything works aas normal but I'm really unsure what I have to do to get this working:
skills.php - auto() function (controller):
public function auto(){
$skill = $_POST['skill-0'];
$query = $this->db->query('SELECT * from skill_list WHERE name LIKE "'.$skill.'%" ORDER by name ASC LIMIT 10');
$data = array();
if ( $query && mysql_num_rows($query) ){
while( $row = mysql_fetch_array($query, MYSQL_ASSOC) ){
$data[] = array(
'label' => $row['name'],
'value' => $row['id']
);
}
}
echo json_encode($data);
flush();
}
skills.php (view)
<form method="post" action="skills/add" id="container">
<script>
$.fn.addSlide = function () {
return this.each(function () {
var $this = $(this),
$num = $('.slide').length++,
$name = $('<input type="text" class="inputField" id="autoskill" name="skill-' + $num + '" placeholder="What\'s your skill?"></div>'),
$slide = $('<br><div class="slide" id="slider-' + $num + '"></div><br>'),
$amt = $('<input name="amount-' + $num + '" id="amount-' + $num + '" class="inputField" readonly placeholder="Slide to select this skill level..."/><br>');
$this.append($name).append($amt).append($slide);
$slide.slider({
value: 0,
min: 0,
max: 5,
step: 1,
slide: function (event, ui) {
$amt.val(ui.value);
}
});
});
}
$('body').on('click', '.addNew', function(event) {
event.preventDefault();
$('#newFields').addSlide();
});
var count = 0;
$(document).ready(function(){
$('#autoskill').autocomplete({
source:'skills/auto', minLength:2
});
$('.addNew').click( function(event){
event.preventDefault();
$('#length').html(count);
count++;
});
$('.submitButton').click( function(event){
$('#container').append('<input type="hidden" name="count" value="' + count + '">');
});
});
</script>
<button class="addNew submitButton"> Add a Skill </button><br>
<div id="newFields"></div>
<input type="submit" class="submitButton" value="Save Skills">
</form>
Hopefully someone can help, Thanks!
make $name into this
$name = $('<input type="text" class="inputField" id="autoskill-'+$num+'" name="skill-' + $num + '" placeholder="What\'s your skill?"></div>'),
then after
$this.append($name).append($amt).append($slide);
add
$('#autoskill'+$num).autocomplete({
source:'skills/auto', minLength:2
});
and remove the autocomplete line completely from ur ready function
then for json make
$data[] = array(
'label' => $row['name'],
'value' => $row['id']
);
into
$data[$row['id']]=$row['name']

checkbox value displaying twice

I am using jquery to get the value of a checkbox. However, what is happening is that the value is getting duplicated and seems to be getting values for all checkboxes in the while loop. I would be grateful if someone could point out my error. Thank you.
UPDATE: Current code. Now only selecting first entry. No output on further checkbox clicks.
PHP Code
while($row = mysql_fetch_array($result))
{
$ticket = $row['ticket_frm'];
$rowdate = date("d/m/Y",strtotime($row['date_frm']));
$id = $row['id_frm'];
$from = $row['from_frm'];
$subject = $row['subject_frm'];
$message = $row['message_frm'];
$myString = <<<EOF
<span><input id="check" type="checkbox" name="delete" value="<?php echo $ticket ?>"></span>
<div class='msgTrue buttonMailTrue' data-message='%s' data-subject='%s' data-rowdate='%s' data-from='%s'>
<img src="images/sml_new_mail_icon.gif" class="mailIcon" alt="" />$subject;
<div class="rowdate">$rowdate</div><br />
<span class="mailFrom">$from</span>
</div>
<p class="checked"></p>
<!-- The following end tag need to be at the start of the line -->
EOF;
printf($myString, $message, $subject, $rowdate, $from);
} echo '<p class="checked">'.'</p>';
jQuery Code
$(function() {
$("#check").click(function() {
var isChecked = $(this).prop("checked"); // or $(this).prop("checked")
if (isChecked) {
$("p.checked").html("Checkbox is checked: <b>True</b>");
} else {
$("p.checked").html("Checkbox is checked: <b>False</b>");
}
});
});
According your code and selectors, there are many input class="check" elements on your page.
You find them by class name, so this is why they are duplicate.
Use id-attribute and $("#id") syntax to get right values, or use this keyword in your code:
//var isChecked = $('.check').is(':checked'); - wrong
var isChecked = $(this).is(':checked'); // right
Update:
You didn't provide unique id for your elements. Of cause this doesn't work. Your error is the same as earlier.
Try this code:
<input id="check$ticket" type="checkbox" name="delete" value="<?php echo $ticket ?>">
Same for javascript - you have to find element by it's unique id
$("#check" + TICKET_NUMBER_HERE).click(function() {
var isChecked = $(this).prop("checked"); // or $(this).prop("checked")
if (isChecked) {
$("p.checked").html("Checkbox is checked: <b>True</b>");
} else {
$("p.checked").html("Checkbox is checked: <b>False</b>");
You should use this to work with current checkbox:
$(".check").click(function() {
var isChecked = this.checked; // or $(this).prop("checked")
if (isChecked) {
$("p.checked").html("Checkbox is checked: <b>True</b>");
} else {
$("p.checked").html("Checkbox is checked: <b>False</b>");
}
});
Change your jquery code to. As $('.check') returns array of object it is by default checking property of 1st object only
$(function() {
$('.check').click(function(){
var isChecked = $(this).is(':checked');
alert(isChecked);
if(isChecked)
$('p.checked').html('Checkbox is checked: <b>True</b>');
else
$('p.checked').html('Checkbox is checked: <b>False</b>');
});
});
Try
$(".check").click( function() {
$("p.checked").html(
"Checkbox is checked: <b>" + $(this).is(":checked") + "</b>" );
}

Increment href value by one (Javascript)

I have got a ordered list
<li id="prev">
<a href="#fragment-1>Next</a>
</li>
I want to increment the href value to
<a href="#fragment-1">...
<a href="#fragment-2">...
<a href="#fragment-3">...
<a href="#fragment-4">...
When the next is clicked it should stop from 4 and return to 1 allso is it possible with javascript at all
Thank you
Give your link an id first to make it easier to select.
Then,
document.getElementById('the_id_here').addEventListener('click', function(e) {
var n = e.target.href.split('-')[1] * 1 + 1;
if (n > 4)
n = 1;
e.target.href = e.target.href.split('-')[0] + '-' + n;
}, false);
Example: http://jsbin.com/ajegaf/4#fragment-1
Not exactly what you want but should be close enough to aim you in the right direction, check http://jsfiddle.net/pj28v/
<ul id="list"></ul>
Next​
$(function() {
var $list = $('#list'),
count = 4,
i = 0,
cur = 0;
for (; i < count; i++) {
$list.append('<li>frag' + i + '</li>');
}
$('a', $list).eq(0).css('color','red');
$('#next').click(function(ev) {
ev.preventDefault();
cur++;
if (cur >= count) cur = 0;
$('a', $list).css('color','blue').eq(cur).css('color','red');
});
});​
A jQuery solution:
$(document).ready(function(){
$('#prev a').click(function(){
var href = $(this).attr('href');
var num = parseInt(href.substr(href.indexOf('-') + 1));
if(num == 4)
{
num = 1;
}
else
{
num++;
}
$(this).attr('href', '#fragment-' + num)
});
});​
http://jsfiddle.net/UYDdB/
A solution similar to Delan's one but with jQuery and without the usage of a test. http://jsfiddle.net/GZ26j/
$('#next').on('click', function(e) {
e.preventDefault();
href = $(this).attr('href');
var n = href.split('-')[1] * 1 + 1;
n = n%5;
e.target.href = href.split('-')[0] + '-' + n;
});​
Edit:
This solution makes the counter start at 0 and not 1
use a hidden field to hold the value, and an onclick function to increase it and submit the form. SEE: How can I increase a number by activating a button to be able to access a function each time the button is increased?
<?
if(!isset($_GET['count'])) {
$count = 0;
} else {
$count = $_GET['count'];
}
?>
<script type='text/javascript'>
function submitForm(x) {
if(x == 'prev') {
document.getElementById('count').value--;
} else {
document.getElementById('count').value++;
}
document.forms["form"].submit();
}
</script>
<form action='hidfield.php' method='get' name='form'>
<input type='hidden' name='count' id='count' value='<?php echo $count; ?>'>
</form>
<input type='submit' name='prev' value='prev' onclick="submitForm('prev')">
<input type='submit' name='next' value='next' onclick="submitForm('next')">

Categories