I have a dynamic input in my php code like this one:
<开发者_C百科input type="checkbox" id="advantage[]" name="advantage[]" value="Special Option" />
And I need to know if it's checked... I can have multiple checks in the same format in the code, my brain hurts because i can't find a solution!
Thanks 4 the help!
var isSpecialOptionSet = $("input[value='Special Option']:checked").length ? true : false;
// isSpecialOptionSet will now be true/false according to the state of the checkbox.
var isChecked = $('input:checkbox[value="Special Option"]').is(":checked");
Client-side:
$('input[type=checkbox][name="advantage[]"][value="Special Option"]').is(':checked')
Server-side:
in_array('Special Option', $_POST['advantage'])
Note that you shouldn't use the same id multiple times.
You can do like:
$(function(){
$('input[type="checkbox"]').each(function(){
if ($(this).is(':checked'))
{
alert('Checked');
}
else
{
alert('Not Checked');
}
});
});
Or even based on value if is is same across all checkboxes:
$(function(){
$('input[value="Special Option"]').each(function(){
if ($(this).is(':checked'))
{
alert('Checked');
}
else
{
alert('Not Checked');
}
});
});
If you're trying to determine if it's checked after postback, checkbox value data is only passed to the server in $_POST when it is checked. Otherwise the value is empty or null.
If you're trying to determine if it's checked before postback, you will need to write some Javascript in PHP that will be processed client-side.
You can use :checked
http://api.jquery.com/category/forms/
You can't/shouldn't have multiple checkboxes in this format because the id has to be unique.
var isChecked = $('#advantage\\[\\]').is(':checked');
You set in HTML form "advantage[]" witch becomes in php an array. You need to tell what is the value of that specific part.
eg: "advantage['checkbox1']" then in php you will get
$_POST['advantage']['checkbox1'] will be equal to 'Special Option';
if that checkbox is checked.
on the other hand if you can't modify:
<?php
if(in_array('Special Option', $_POST['advantage'])){
// checkbox is checked
// it can only be identified by an id witch you will receive by
// foreach($_POST['advantage'] as $id => $val);
}
?>
If you want to do it with jQuery follow this link and you will be able to see how it is done:
JQuery HowTo: How to check if checkbox is checked using jQuery
Checked selector - jQuery
精彩评论