Keep checkbox status for multiple checkboxes with same name - javascript

I have a page of content generated by ajax and organized with a row of checkboxes. Clicking on any of the checkboxes passes a parameter into the URL and that's used to create a SQL query. I want to add the checkboxes to another section of the page but when I do this, I'm unable to keep the checkboxes styled (there's a custom style for a checked and unchecked state). Click on either row of checkboxes will organize the data properly, but only one row of checkboxes will show the checked-on/checked-off state.
I'm using the following code to style the checkboxes:
$(':checkbox').change(function() {
if($(this).is(":checked")) {
$(this).next('label').children('div').removeClass("sort-not-active").addClass("sort-active");
}
else {
$(this).next('label').children('div').removeClass("sort-active").addClass("sort-not-active");
}
});
The HTML for my checkboxes is below. I figured my style issues might be caused because I'm passing the variable as an ID instead of a class, but whenever I remove the ID the checkboxes stop working altogether.
<?php foreach (array_unique($disciplines) as $discipline): ?>
<input class="disciplinechecks" type="checkbox" id="<?php echo $discipline; ?>" name="<?php echo $discipline; ?>" value="<?php echo $discipline; ?>" onChange="checkBoxChange(this.checked,'<?php echo $discipline; ?>');">
<label for="<?php echo $discipline; ?>">
<div class="sort-genre sort-active"><?php echo $discipline; ?></div>
<span></span>
</label>
<?php endforeach ?>
Below is the function I use to pass the values into the URL. Nothing here references an ID so I can't figure out why removing the ID from my checkboxes breaks it:
var typeItemsChecked = Array( ALL OF THE $DISCIPLINE VALUES ARE HERE );
function checkBoxChange(x,y) {
if(x){
var type = y;
typeItemsChecked.push(type);
showUser();
}
else {
var type = y;
typeItemsChecked.remove(type);
showUser();
}
}
function getURLString() {
joinedTypeItemsChecked = typeItemsChecked.join();
var queryString = [
("d="+joinedTypeItemsChecked)
];
var url = queryString.join("&");
return url;
}
This is what the HTML looks like after the PHP
<input class="disciplinechecks" type="checkbox" id="Web Design" name="Web Design" value="Web Design" onChange="checkBoxChange(this.checked,'Web Design');">
<label for="Web Design">
<div class="sort-genre sort-active">Web Design</div>
<span></span>
</label>
<input class="disciplinechecks" type="checkbox" id="Print Design" name="Print Design" value="Print Design" onChange="checkBoxChange(this.checked,'Print Design');">
<label for="Print Design">
<div class="sort-genre sort-active">Print Design</div>
<span></span>
</label>

Okay, so, after reading your comment responses, nothing in your original post jumps out at me immediately as an issue, but there are a couple of problems that your "processed" code has (particularly around the id and name attributes) that could be causing you troubles. Specifically:
id attributes can not contain spaces (see here for more information on valid id values: What are valid values for the id attribute in HTML?)
id values must be unique within the page
Multiple checkboxes (and, on a side note, radio buttons) that have the same name attribute, are considered to be grouped (i.e., sort of like they are one input).
Now, browsers can often be pretty forgiving about these things, but scripting languages can get very confused. So, before you go any further in your debugging, I would suggest updating your PHP to:
strip any spaces out of the $discipline value, when assigning the id attribute. While name attributes can have spaces, I would avoid using them there as well, as a general practice.
use some sort of index value (or something similar) to differentiate the id and name values between the two sets of checkboxes.
On a side note . . .
. . . there are also a couple of places where you can simplify your code . . . doing that will also reduce the number of places where bugs can pop up. Specifically:
In you JS code for the styling, try this:
$(':checkbox').change(function() {
$(this).next().children('div').toggleClass("sort-not-active sort-active");
});
no need to specify 'label' in the next() call, since it is always the next sibling of the checkbox
if the default classes are set up correctly, then all you need to do is toggle the two classes on the change of the checkbox. Since there are only two states that the checkbox can be in, there are only two states that the combination of classes can be in.
For the code for capturing the checked boxes, you can simplify it to this:
function checkBoxChange(x,y) {
if (x) {
typeItemsChecked.push(y);
}
else {
typeItemsChecked.remove(y);
}
showUser();
}
I don't see any reason that this would be causing the problems that you are seeing, but I just thought that I would toss that out to help reduce the complexity a little bit. :)
So, I'm not guaranteeing that any of these are going to fix the issue that you are seeing (actually, using just your original JS for the styles and the HTML samples that you gave, everything worked just fine for me in Firefox), but I do know that some browsers and scripting languages can be very particular about not following the correct rules of HTML. Try addressing some of these issues and see if the problems that you are seeing go away. If not, we can try again with your new code.

Related

Can anyone suggest some ideas for what I want to do here

I am quite well versed in developing in PHP, HTML5 and CSS3 however when it comes to Javascript and Jquery I'm totally lost.
What I'm looking at doing is on my site I want to place a custom page that allows the users to select certain options which will be specified by me.
pretty much along the lines of:-
Question1?
Select one of 2 options.
option 1 moves along to question 2
however where option 2 then moves to a different question.
what I would like to do instead is to use Javascript instead so it could be question 1 select answer, then question 2 automatically populates underneath. and then depending on that answer and so on, until the end is reached.
I will include a little snippet below so it helps visualise the end goal that I am looking for:-
<?php
$q1 = $_POST['q1'] ?? '';
$q2 = $_POST['q2'] ?? '';
?>
<?php
if(isset($_POST['q1] {
echo 'q2';
} else {
echo 'q20';
}
?>
The HTML would then be:-
<form name="script_path.ext" method="POST">
<span>Question 1?</span></br>
<select id="q1" name="q1">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<input type="submit" name="submit"
value="Next">
obviously it would be better to use Jquery to do this as the amount of variables are going to grow as questions get added and could become an infinite loop of if_statements.

Javascript / Php : set textarea value

I have the following script, which returns 2 values from my database.
$(document).ready(function() {
<?
$link=new mysqli($serveur,$login,$pass,$base);
mysqli_set_charset($link, "utf8");
$r=mysqli_query($link, "select sujet,corps from mail where type='Création_rationnaire'");
while($row = mysqli_fetch_array($r)) {
?>
document.getElementById("sujet").value="<? echo $row[sujet];?>";
document.getElementById("te").value="<? echo $row[corps];?>";
<? }mysqli_close($link); ?>
});
Here are my 2 forms, one is a classic Input, the other is a textarea.
<input id='sujet' class="form-field">
<textarea id="te" class="textarea" rows="9" cols="70"></textarea>
The problem is : my SQL request works in MySQL, but when "corps" is echoed as above, nothing appears in the Inputs, like the script was crashing... Only "sujet" can be echoed successfully. So... why, just why ? Thanks in advance for whoever helps me.
EDIT : all I can echo in the "te" textbox is a single string like this : echo 'something';... but nothing else works...
Try this
document.getElementById("sujet").value="<? echo $row['sujet'];?>";
document.getElementById("te").text="<? echo $row['corps'];?>";
or if you use jquery
var message = <?php echo $row['corps']; ?>;
$("#te").val(message);
Textarea does not have a value but it does have text.
in an input box you would have <input type="text" value="example" /> and in a text area the value is inside the element like so
<textarea>example</textarea>
A other way is to use innerHtml (javascript) or html (jquery) .
But note that html tags will be display with one of these options
document.getElementById("te").innerHTML="<? echo $row['corps'];?>";
<textarea> doesn't have value property. Since you are using jQuery to bind document ready, you can use jQuery to set the value.
$("#sujet").val("<? echo $row[sujet];?>");
$("#te").html("<? echo $row[corps];?>");
What is the value of $row[corps]? Is it empty string? Does it contain double quote, or newline characters? If it contains any of them, it will break your javascript source code. What does javascript source code look like when you check source code inside the browser?
It works by inserting the values directly into the plain html forms. I usually use this javascript function because I have tons of forms to fill in my program, and it never failed until now... So my function above was good, but we still don't know why it failed in this particular case...
Problem solved anyways... thanks to everyone.

Input Checkbox Array, if unchecked no value is sent by jQuery

I have a form which is dynamically created so I have an input array!
Solved: <input type="hidden" name="smoker_patient[ID]" value="off" /> hidden field for every checkbox with the same ID!#
The rows look like:
<tr><td>
[stuff]
<input type="checkbox" name="smoker_patient[1]" class="smoker" id="cbx1" checked="checked"/>
[stuff]
</td></tr>
<tr><td>
[stuff]
<input type="checkbox" name="smoker_patient[2]" class="smoker" id="cbx2"/>
[stuff]
</td></tr>
<tr><td>
[stuff]
<input type="checkbox" name="smoker_patient[3]" class="smoker" id="cbx3" checked="checked"/>
[stuff]
</td></tr>
As you can see, cbx1 and cbx3 are checked.(only to show the error) But the array which is sent by jQuery only consists of
smoker_patient[0] = 'on'
smoker_patient[1] = 'on'
but it should be...
smoker_patient[0] = 'on'
smoker_patient[1] = 'off'
smoker_patient[2] = 'on'
So i get the error in PHP:
Notice: Undefined offset: 2 in newcoexposition.php on line XX
I am unsure of your syntax in the naming of your input sections. You seem to know what your doing well enough that I don't think you are unaware that if you name="" them all the same then your $_POST or $_GET of that input will only see the same one over and over. I am sure you have thought of this and the name="smoker_patient[]" must be just a pseudo place holder.
That being said, if that's not the problem with the code then you can approach it like this.
You need to use PHP to make sure that the $_POST value has been set somewhere. When a checkbox is selected or checked and the form is sent via $_POST for example, the information isn't sent like other HTML objects. Instead it is sent as either ON or OFF in your $_POST response handling PHP page.
#mithunsatheesh is correct the only way to do this is to use an isset($_POST['checkbox']) to make sure it has been set, or checked...
If your sections are dynamic then you can use php and a simple counter to make sure that all dynamic checkboxes are given unique names and identifiers like so...
I would first see how many boxes I need and then...
$totalNumOfBoxes = 3;
for($i=0; $i<$totalNumOfBoxes; $i++) {
echo '<tr>
<td>
<input type="checkbox" name="smoker_patient_".$i class="smoker" id="cbx".$i />
</td>
</tr>';
}
Then you would have a series of boxes each with unique identifiers, so that when you submit the form each checkbox can't be confused with its sibling checkbox in the $_POST array.
On the other side, in the $_POST response handling PHP file you would then look for them all by giving yourself a $_GET variable filled with how many boxes there are since testing the boundaries to see how many have been returned isn't possible with isset() and checkboxes ...
I would make a form that has all these boxes have a method: POST and action: myHandlerPHPFile.php?boxCount=3so when you get to this side of the POST request you can make your $totalNumOfBoxes = $_GET['boxCount'].
You can set the action: myHandlerPHPFile.php?boxCount= count to 3 by using the same look that makes the boxes to also add this counted variable to the mix.

Laravel 4 and Bootstrap Switch

I am trying to use the Bootstrap Switch (http://www.bootstrap-switch.org) with the latest version of Laravel (4.2.8) however I am new to learning this framework and PHP.
I have referenced the four required files within the head of my main index.blade.php file as shown below:
{{ HTML::style('public/bootstrap-switch-style/css/bootstrap-switch.css') }}
{{ HTML::style('public/bootstrap-switch-master/css/bootstrap.css') }}
{{ HTML::script('public/bootstrap-switch-master/js/jquery.js') }}
{{ HTML::script('public/bootstrap-switch-master/js/bootstrap-switch.js') }}
Further down the index.blade.php file I create a checkbox with a value of checked, and attempt to call the function to concert the checkbox to a toggle switch.
<input type="checkbox" name="my-checkbox" checked>
{{$toggle=("[name='my-checkbox']").bootstrapSwitch();}}
The following error appears:
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Call to undefined function bootstrapSwitch()
Underneath that error an extract of my index.blade.php file is referenced:
<input type="checkbox" name="my-checkbox" checked>
<?php echo $toggle=("[name='my-checkbox']").bootstrapSwitch();; ?>
Has anyone managed to integrate the Bootstrap Switch with Laravel previously, or is there any other way of doing this? Ultimately this is for a staff availability website which which should toggle red for if someone is unavailable, or green for if they are available. The status (boolean) is stored with a MySQL database. Many thanks in advance.
This isn't really what you're trying to do:
<?php echo $toggle=("[name='my-checkbox']").bootstrapSwitch(); ?>
This is basically saying to do the following:
Take the string "[name='my-checkbox']" and concatenate it with the results of calling the global function bootstrapSwitch and assign those results to the variable $toggle and finally echo the whole thing out, as a string.
The error message is correctly telling you that your PHP script is unaware of any such function.
What I think you're trying to do, in Javascript, is something like this:
$("[name='my-checkbox']").bootstrapSwitch();
Which is valid. Remove the PHP tags, remove the echo and replace your current line with that and see if that works for you. Furthermore, I would suggest going back to the documentation, where its plainly spelled out:
Add your checkbox.
<input type="checkbox" name="my-checkbox" checked>
Initialize Bootstrap Switch.
$("[name='my-checkbox']").bootstrapSwitch();

Jquery appending value of html to input box but not text within a span

I have an ajax query that brings back a searched name and id:
if($result)
{
while($row=mysqli_fetch_array($result))
{
extract($row);
echo "<li>".$row['first_name']." ".$row['last_name']."<span class='uid'>".$row['user_id']."</span></li>";
}
}
What I am trying to do is append the first and last names to a search box and then retrieve the userid and place that in another search box.
$('li').click(function(){
$('.client_name').not('span.uid').val($(this).text());
$('.listbox').hide();
});
The above jquery does not work as I feel I am using the 'not' property wrongly. Is it possible to split these values ?
html is as follows
<div class="form_align">
<label>
Client Name
</label>
<input type="text" class="client_name" />
<label>
Client Account No.
<span class="small">This is important !</span>
</label>
<input type="text" class="client_account_no" />
<div class="listbox">
<div class="nameslist">
</div>
</div>
</div>
I recommend changing the AJAX response to surround the names in their own <span class='ajaxname'>. That will make it a lot simpler to target the name separately from the sibling node <span class='uid'>. Otherwise, to exclude the value of the <span class='uid'> you would need to do something tricky like temporarily remove it from the DOM to get the <li>'s text then place it back in. All way too complicated.
echo "<li><span class='ajaxname'>".$row['first_name']." ".$row['last_name']."</span><span class='uid'>".$row['user_id']."</span></li>";
Since the AJAX response sends a new <li> into your DOM, you will need to use .on() to bind the click event.
$('li').on('click', function(){
// Get the name from its <span> and put it into the input
$('.client_name').val($(this).find('.ajaxname').text());
// Get the uid and put it inot .client_account_no
$('.client_account_name').val($(this).find('.uid').text());
$('.listbox').hide();
});
And what do you know, it works (jsfiddle).
Addendum:
Other answer never materialized, so here is an arguably better solution using a data-uid attribute in the AJAX-returned HTML
// PHP supplies the user_id in an HTML attribute data-uid
echo "<li data-uid='" . $row['user_id'] . "'>".$row['first_name']." ".$row['last_name'] . "</li>";
The JavaScript has a much easier job then:
$('li').on('click', function(){
// Get the name, which is just the <li>'s text content...
$('.client_name').val($(this).text());
// Get the uid from the data-uid attribute
$('.client_account_name').val($(this).attr('data-uid'));
$('.listbox').hide();
});

Categories

Resources