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

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.

Related

form submit with checkboxes [duplicate]

I've got a load of checkboxes that are checked by default. My users will probably uncheck a few (if any) of the checkboxes and leave the rest checked.
Is there any way to make the form POST the checkboxes that are not checked, rather than the ones that are checked?
The solution I liked the most so far is to put a hidden input with the same name as the checkbox that might not be checked. I think it works so that if the checkbox isn't checked, the hidden input is still successful and sent to the server but if the checkbox is checked it will override the hidden input before it. This way you don't have to keep track of which values in the posted data were expected to come from checkboxes.
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
Add a hidden input for the checkbox with a different ID:
<input id='testName' type='checkbox' value='Yes' name='testName'>
<input id='testNameHidden' type='hidden' value='No' name='testName'>
Before submitting the form, disable the hidden input based on the checked condition:
form.addEventListener('submit', () => {
if(document.getElementById("testName").checked) {
document.getElementById('testNameHidden').disabled = true;
}
}
I solved it by using vanilla JavaScript:
<input type="hidden" name="checkboxName" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">
Be careful not to have any spaces or linebreaks between this two input elements!
You can use this.previousSibling.previousSibling to get "upper" elements.
With PHP you can check the named hidden field for 0 (not set) or 1 (set).
My personal favorite is to add a hidden field with the same name that will be used if the check-box is unchecked. But the solution is not as easy as it may seems.
If you add this code:
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
The browser will not really care about what you do here. The browser will send both parameters to the server, and the server has to decide what to do with them.
PHP for example takes the last value as the one to use (see: Authoritative position of duplicate HTTP GET query keys)
But other systems I worked with (based on Java) do it the way around - they offer you only the first value.
.NET instead will give you an array with both elements instead
I'll try to test this with node.js, Python and Perl at sometime.
you don't need to create a hidden field for all checkboxes just copy my code.
it will change the value of checkbox if not checked the value will assign 0 and if checkbox checked then assign value into 1
$("form").submit(function () {
var this_master = $(this);
this_master.find('input[type="checkbox"]').each( function () {
var checkbox_this = $(this);
if( checkbox_this.is(":checked") == true ) {
checkbox_this.attr('value','1');
} else {
checkbox_this.prop('checked',true);
//DONT' ITS JUST CHECK THE CHECKBOX TO SUBMIT FORM DATA
checkbox_this.attr('value','0');
}
})
})
A common technique around this is to carry a hidden variable along with each checkbox.
<input type="checkbox" name="mycheckbox" />
<input type="hidden" name="mycheckbox.hidden"/>
On the server side, we first detect list of hidden variables and for each of the hidden variable, we try to see if the corresponding checkbox entry is submitted in the form data or not.
The server side algorithm would probably look like:
for input in form data such that input.name endswith .hidden
checkboxName = input.name.rstrip('.hidden')
if chceckbName is not in form, user has unchecked this checkbox
The above doesn't exactly answer the question, but provides an alternate means of achieving similar functionality.
I know this question is 3 years old but I found a solution that I think works pretty well.
You can do a check if the $_POST variable is assigned and save it in a variable.
$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';
the isset() function checks if the $_POST variable is assigned. By logic if it is not assigned then the checkbox is not checked.
$('input[type=checkbox]').on("change",function(){
var target = $(this).parent().find('input[type=hidden]').val();
if(target == 0)
{
target = 1;
}
else
{
target = 0;
}
$(this).parent().find('input[type=hidden]').val(target);
});
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
If you leave out the name of the checkbox it doesn't get passed.
Only the test_checkbox array.
You can do some Javascript in the form's submit event. That's all you can do though, there's no way to get browsers to do this by themselves. It also means your form will break for users without Javascript.
Better is to know on the server which checkboxes there are, so you can deduce that those absent from the posted form values ($_POST in PHP) are unchecked.
I also like the solution that you just post an extra input field, using JavaScript seems a little hacky to me.
Depending on what you use for you backend will depend on which input goes first.
For a server backend where the first occurrence is used (JSP) you should do the following.
<input type="checkbox" value="1" name="checkbox_1"/>
<input type="hidden" value="0" name="checkbox_1"/>
For a server backend where the last occurrence is used (PHP,Rails) you should do the following.
<input type="hidden" value="0" name="checkbox_1"/>
<input type="checkbox" value="1" name="checkbox_1"/>
For a server backend where all occurrences are stored in a list data type ([],array). (Python / Zope)
You can post in which ever order you like, you just need to try to get the value from the input with the checkbox type attribute. So the first index of the list if the checkbox was before the hidden element and the last index if the checkbox was after the hidden element.
For a server backend where all occurrences are concatenated with a comma (ASP.NET / IIS)
You will need to (split/explode) the string by using a comma as a delimiter to create a list data type. ([])
Now you can attempt to grab the first index of the list if the checkbox was before the hidden element and grab the last index if the checkbox was after the hidden element.
image source
I would actually do the following.
Have my hidden input field with the same name with the checkbox input
<input type="hidden" name="checkbox_name[]" value="0" />
<input type="checkbox" name="checkbox_name[]" value="1" />
and then when i post I first of all remove the duplicate values picked up in the $_POST array, atfer that display each of the unique values.
$posted = array_unique($_POST['checkbox_name']);
foreach($posted as $value){
print $value;
}
I got this from a post remove duplicate values from array
"I've gone with the server approach. Seems to work fine - thanks. – reach4thelasers Dec 1 '09 at 15:19" I would like to recommend it from the owner. As quoted: javascript solution depends on how the server handler (I didn't check it)
such as
if(!isset($_POST["checkbox"]) or empty($_POST["checkbox"])) $_POST["checkbox"]="something";
Most of the answers here require the use of JavaScript or duplicate input controls. Sometimes this needs to be handled entirely on the server-side.
I believe the (intended) key to solving this common problem is the form's submission input control.
To interpret and handle unchecked values for checkboxes successfully you need to have knowledge of the following:
The names of the checkboxes
The name of the form's submission input element
By checking whether the form was submitted (a value is assigned to the submission input element), any unchecked checkbox values can be assumed.
For example:
<form name="form" method="post">
<input name="value1" type="checkbox" value="1">Checkbox One<br/>
<input name="value2" type="checkbox" value="1" checked="checked">Checkbox Two<br/>
<input name="value3" type="checkbox" value="1">Checkbox Three<br/>
<input name="submit" type="submit" value="Submit">
</form>
When using PHP, it's fairly trivial to detect which checkboxes were ticked.
<?php
$checkboxNames = array('value1', 'value2', 'value3');
// Persisted (previous) checkbox state may be loaded
// from storage, such as the user's session or a database.
$checkboxesThatAreChecked = array();
// Only process if the form was actually submitted.
// This provides an opportunity to update the user's
// session data, or to persist the new state of the data.
if (!empty($_POST['submit'])) {
foreach ($checkboxNames as $checkboxName) {
if (!empty($_POST[$checkboxName])) {
$checkboxesThatAreChecked[] = $checkboxName;
}
}
// The new state of the checkboxes can be persisted
// in session or database by inspecting the values
// in $checkboxesThatAreChecked.
print_r($checkboxesThatAreChecked);
}
?>
Initial data could be loaded on each page load, but should be only modified if the form was submitted. Since the names of the checkboxes are known beforehand, they can be traversed and inspected individually, so that the the absence of their individual values indicates that they are not checked.
I've tried Sam's version first.
Good idea, but it causes there to be multiple elements in the form with the same name. If you use any javascript that finds elements based on name, it will now return an array of elements.
I've worked out Shailesh's idea in PHP, it works for me.
Here's my code:
/* Delete '.hidden' fields if the original is present, use '.hidden' value if not. */
foreach ($_POST['frmmain'] as $field_name => $value)
{
// Only look at elements ending with '.hidden'
if ( !substr($field_name, -strlen('.hidden')) ) {
break;
}
// get the name without '.hidden'
$real_name = substr($key, strlen($field_name) - strlen('.hidden'));
// Create a 'fake' original field with the value in '.hidden' if an original does not exist
if ( !array_key_exists( $real_name, $POST_copy ) ) {
$_POST[$real_name] = $value;
}
// Delete the '.hidden' element
unset($_POST[$field_name]);
}
You can also intercept the form.submit event and reverse check before submit
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
I use this block of jQuery, which will add a hidden input at submit-time to every unchecked checkbox. It will guarantee you always get a value submitted for every checkbox, every time, without cluttering up your markup and risking forgetting to do it on a checkbox you add later. It's also agnostic to whatever backend stack (PHP, Ruby, etc.) you're using.
// Add an event listener on #form's submit action...
$("#form").submit(
function() {
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "0"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
); // end submit() argument list
$('form').submit(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});
I see this question is old and has so many answers, but I'll give my penny anyway.
My vote is for the javascript solution on the form's 'submit' event, as some has pointed out. No doubling the inputs (especially if you have long names and attributes with php code mixed with html), no server side bother (that would require to know all field names and to check them down one by one), just fetch all the unchecked items, assign them a 0 value (or whatever you need to indicate a 'not checked' status) and then change their attribute 'checked' to true
$('form').submit(function(e){
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).val(0); //Set whatever value you need for 'not checked'
$(this).attr("checked", true);
});
return true;
});
this way you will have a $_POST array like this:
Array
(
[field1] => 1
[field2] => 0
)
What I did was a bit different. First I changed the values of all the unchecked checkboxes. To "0", then selected them all, so the value would be submitted.
function checkboxvalues(){
$("#checkbox-container input:checkbox").each(function({
if($(this).prop("checked")!=true){
$(this).val("0");
$(this).prop("checked", true);
}
});
}
I would prefer collate the $_POST
if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;
it minds, if the POST doesn't have have the 'checkboxname'value, it was unckecked so, asign a value.
you can create an array of your ckeckbox values and create a function that check if values exist, if doesn`t, it minds that are unchecked and you can asign a value
Might look silly, but it works for me. The main drawback is that visually is a radio button, not a checkbox, but it work without any javascript.
HTML
Initialy checked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="a" value="1" checked>
<input type="radio" name="a" value="0">
</span>
<br/>
Initialy unchecked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="b" value="1">
<input type="radio" name="b" value="0" checked>
</span>
and CSS
span input
{position: absolute; opacity: 0.99}
span input:checked
{z-index: -10;}
span input[value="0"]
{opacity: 0;}
fiddle here
I'd like to hear any problems you find with this code, cause I use it in production
The easiest solution is a "dummy" checkbox plus hidden input if you are using jquery:
<input id="id" type="hidden" name="name" value="1/0">
<input onchange="$('#id').val(this.checked?1:0)" type="checkbox" id="dummy-id"
name="dummy-name" value="1/0" checked="checked/blank">
Set the value to the current 1/0 value to start with for BOTH inputs, and checked=checked if 1. The input field (active) will now always be posted as 1 or 0. Also the checkbox can be clicked more than once before submission and still work correctly.
Example on Ajax actions is(':checked') used jQuery instead of .val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
params will get value in TRUE OR FALSE..
Checkboxes usually represent binary data that are stored in database as Yes/No, Y/N or 1/0 values. HTML checkboxes do have bad nature to send value to server only if checkbox is checked! That means that server script on other site must know in advance what are all possible checkboxes on web page in order to be able to store positive (checked) or negative (unchecked) values. Actually only negative values are problem (when user unchecks previously (pre)checked value - how can server know this when nothing is sent if it does not know in advance that this name should be sent). If you have a server side script which dynamically creates UPDATE script there's a problem because you don't know what all checkboxes should be received in order to set Y value for checked and N value for unchecked (not received) ones.
Since I store values 'Y' and 'N' in my database and represent them via checked and unchecked checkboxes on page, I added hidden field for each value (checkbox) with 'Y' and 'N' values then use checkboxes just for visual representation, and use simple JavaScript function check() to set value of if according to selection.
<input type="hidden" id="N1" name="N1" value="Y" />
<input type="checkbox"<?php if($N1==='Y') echo ' checked="checked"'; ?> onclick="check(this);" />
<label for="N1">Checkbox #1</label>
use one JavaScript onclick listener and call function check() for each checkboxe on my web page:
function check(me)
{
if(me.checked)
{
me.previousSibling.previousSibling.value='Y';
}
else
{
me.previousSibling.previousSibling.value='N';
}
}
This way 'Y' or 'N' values are always sent to server side script, it knows what are fields that should be updated and there's no need for conversion of checbox "on" value into 'Y' or not received checkbox into 'N'.
NOTE: white space or new line is also a sibling so here I need .previousSibling.previousSibling.value. If there's no space between then only .previousSibling.value
You don't need to explicitly add onclick listener like before, you can use jQuery library to dynamically add click listener with function to change value to all checkboxes in your page:
$('input[type=checkbox]').click(function()
{
if(this.checked)
{
$(this).prev().val('Y');
}
else
{
$(this).prev().val('N');
}
});
#cpburnz got it right but to much code, here is the same idea using less code:
JS:
// jQuery OnLoad
$(function(){
// Listen to input type checkbox on change event
$("input[type=checkbox]").change(function(){
$(this).parent().find('input[type=hidden]').val((this.checked)?1:0);
});
});
HTML (note the field name using an array name):
<div>
<input type="checkbox" checked="checked">
<input type="hidden" name="field_name[34]" value="1"/>
</div>
<div>
<input type="checkbox">
<input type="hidden" name="field_name[35]" value="0"/>
</div>
<div>
And for PHP:
<div>
<input type="checkbox"<?=($boolean)?' checked="checked"':''?>>
<input type="hidden" name="field_name[<?=$item_id?>]" value="<?=($boolean)?1:0?>"/>
</div>
All answers are great, but if you have multiple checkboxes in a form with the same name and you want to post the status of each checkbox. Then i have solved this problem by placing a hidden field with the checkbox (name related to what i want).
<input type="hidden" class="checkbox_handler" name="is_admin[]" value="0" />
<input type="checkbox" name="is_admin_ck[]" value="1" />
then control the change status of checkbox by below jquery code:
$(documen).on("change", "input[type='checkbox']", function() {
var checkbox_val = ( this.checked ) ? 1 : 0;
$(this).siblings('input.checkbox_handler').val(checkbox_val);
});
now on change of any checkbox, it will change the value of related hidden field. And on server you can look only to hidden fields instead of checkboxes.
Hope this will help someone have this type of problem. cheer :)
You can add hidden elements before submitting form.
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function (i, el) {
if(!el.checked) {
var hidden_el = $(el).clone();
hidden_el[0].checked = true;
hidden_el[0].value = '0';
hidden_el[0].type = 'hidden'
hidden_el.insertAfter($(el));
}
})
});
The problem with checkboxes is that if they are not checked then they are not posted with your form. If you check a checkbox and post a form you will get the value of the checkbox in the $_POST variable which you can use to process a form, if it's unchecked no value will be added to the $_POST variable.
In PHP you would normally get around this problem by doing an isset() check on your checkbox element. If the element you are expecting isn't set in the $_POST variable then we know that the checkbox is not checked and the value can be false.
if(!isset($_POST['checkbox1']))
{
$checkboxValue = false;
} else {
$checkboxValue = $_POST['checkbox1'];
}
But if you have created a dynamic form then you won't always know the name attribute of your checkboxes, if you don't know the name of the checkbox then you can't use the isset function to check if this has been sent with the $_POST variable.
function SubmitCheckBox(obj) {
obj.value = obj.checked ? "on" : "off";
obj.checked = true;
return obj.form.submit();
}
<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">
If you want to submit an array of checkbox values (including un-checked items) then you could try something like this:
<form>
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Dog
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Cat
</form>
$('form').submit(function(){
$('input[type="checkbox"]:checked').prev().val(1);
});

Keep checkbox status for multiple checkboxes with same name

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.

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

Change a form value before submitting via JavaScript

I've been through a lot of questions on similar issues, but can't seem to get this working. What I'm trying to do is when a button is clicked, replace the value of a form field with the word 'now' and then submit the form. Initially, the HTML form looks like this:
<tr id="row43" bgcolor="#FF0000">
<form id="form43" name="loggingUpdate" action="index.php" method="POST">
<td>PersonsName</td><td>SGS 1-26</td>
<td><input type="text" name="takeoff" id="takeoff43"/><a href='#' onclick='startTakeoff(43);return false;'><img alt='Start Now' src='brush_24.png' border='0'></a></td>
<td><input type="text" name="landing" /></td><td>0 Mins</td>
<td><input type="text" name="towHeight" /></td>
<td><input type="hidden" name="flightIndex" value="43"/><input type="submit" value="Update..." /> <a href=deleteEntry.php?flightIndex=43><img src="close_24.png" /></a></td>
</form></tr>
The Javascript that's triggered by the onclick is as shown below:
function startTakeoff(flightIndex) {
var flightForm = document.getElementById("form"+flightIndex);
var flightRow = document.getElementById("row"+flightIndex);
flightRow.cells[2].innerHTML = "<input type=\"text\" name=\"takeoff\" value=\"now\"><img alt=\"Start Now\" src=\"brush_24.png\" border=\"0\">";
flightForm.submit();
}
So when the button is clicked, it should replace the cell's value with 'now' and submit the form. The trouble is while it does submit, the changed value doesn't actually get submitted. If I manually add something to one of the other fields (the towHeight for example) and click the button, it does get submitted successfully. In other words, it is only the 'takeoff' field that doesn't get submitted when the button is clicked. I've never worked with Javascript before, so this seems very odd to me.
In the way of background, there is a PHP script that's generating the HTML and taking the submitted input, hence some of the strange IDs. The entire page can be seen here in case I've left anything out http://ad7zj.net/logging/index.php I'd appreciate the help!
You are looking for the .onsubmit() event.
That said, you might be best off just getting the time from the server. It will save you from a whole world of time zones, day light savings time issues, and the number of computers out there with inaccurate time settings.
EDIT:
Ok, thanks to your comment I think I see what is going on.
You are trying to update the form using .innerHTML. .innerHTML is a rather strange beast and full of all sorts of heartache -- yield not to its temptations. It looks like the browser is waiting till the Javascript event is over before actually applying the innerHTML update. That would be my guess, anyways. Outside of the simplest of updates, I avoid the thing.
Nuke this:
flightRow.cells[2].innerHTML = "<input type=\"text\" name=\"takeoff\" value=\"now\"><img alt=\"Start Now\" src=\"brush_24.png\" border=\"0\">";
Try this instead:
// Assuming only one form with one name 'takeoff'
var el = document.getElementsByName("takeoff")[0];
el.value = 'now';
// The rest of the updates shouldn't matter -- the form is being submitted, nothing should be seen.

How can I create a dynamic form using jQuery

How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.

Categories

Resources