Uncheck value for checkbox in jquery (with ajax and php) - php

I have an editable ajax table , and have a "unlock" field with a checkbox for every row.
When I check the chekbox I need to get the value 1 ( I'm ok for this part ! :)
My code to get the value of the cheked box:
( $("#unlock_input_" + ID).val(); ) )
But when I uncheck one of any checkbox , I need to get the value 0 ( I need help for this part)
So.... How can I do that in jquery ? Thx

You could throw on a :checked selector. Then you'll get back undefined when the box is unchecked, which is falsey, so:
var result = $("#unlock_input_" + ID + ":checked").val() || 0;
result will end up with the value of the checkbox if it's checked, or 0 if not, because of the way JavaScript's curiously-powerful || operator works.
Live example
Another way to write it:
var result = $("#unlock_input_" + ID).filter(":checked").val() || 0;
Or of course, the rather more direct:
var cb = $("#unlock_input_" + ID)[0],
result = cb.checked ? cb.value : 0;

change your code to this (using prop to ask for the checked-property):
var result = $("#unlock_input_" + ID).prop('checked')?1:0;
EDIT:
if you explicitly need the value instead of 1, just do:
var element = $("#unlock_input_" + ID);
var result = element.prop('checked')?element.val():0;

You can use the checked property of the checkbox to decide whether 1 or 0. Try this
if($("#unlock_input_" + ID)[0].checked){
alert("1");
}
else{
alert("0");
}
Alertnatively you can use jQuery is method to check whether the checkbox is checked or not.
if($("#unlock_input_" + ID).is(":checked")){
alert("1");
}
else{
alert("0");
}

You could check if it's chekced
if($("#unlock_input_" + ID).is(':checked')){
myVal = "1";
}
else{
myVal = "0";
}

Related

Why all the inputs are checked after post in JQUERY?

I have radio inputs, if I click on an input, then after post, all the other inputs go to "checked", I don't understand why, here is my code:
foreach ($tab_stickers_stored as $key => $value) {
<input class="form-check-input switch_sticker" type="checkbox" id="switch_sticker_<?=$key?>" name="switch_sticker" value="<?= $key ?>"
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>>
}
$(".switch_sticker").on('change', function() {
var index = $(this).val();
$("input[name='switch_sticker']:checked").each(function(){
if ($("#switch_sticker_" + index).is(':checked')) {
var temp = document.getElementById('largeur_sticker_' + index).value;
document.getElementById('largeur_sticker_' + index).value = document.getElementById('longueur_sticker_' + index).value;
document.getElementById('longueur_sticker_' + index).value = temp;
} else {
var temp = document.getElementById('longueur_sticker_' + index).value;
document.getElementById('longueur_sticker_' + index).value = document.getElementById('largeur_sticker_' + index).value;;
document.getElementById('largeur_sticker_' + index).value = temp;
}
index = "";
});
});
Thank you
Your inputs have different id attributes, but they all have the same name. It is the name that determines what gets submitted, as you have already discovered without realising it when you wrote this line:
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>
That if statement has nothing in it which varies around the loop; it looks at the same value $_POST['switch_sticker'] every time.
The JavaScript code, meanwhile, is essentially irrelevant to the question, because it only changes the value of various elements. Those will show up as the value of the $_POST['switch_sticker'] variable, but because there's only one variable and lots of values, it will just end up with the last one in the list.
The solution is to give each of your checkboxes their own name, like you give them their own value: name="switch_sticker_<?=$key?>". Then look for that name in the PHP: <?php if (isset($_POST['switch_sticker_' . $key])){echo 'checked="checked"';}?>.
You can also use names in the form something[something_else], e.g. name="switch_sticker[<?=$key?>]" and <?php if (isset($_POST['switch_sticker'][$key])){echo 'checked="checked"';}?>. That will cause PHP to create an array when they're submitted, which is a bit nicer to work with - you can write things like foreach ( $_POST['switch_sticker'] as $submittedKey => $submittedValue ) { ... }.

JQuery set default is value is passed using url

This is a question is continuation of on my previous question on
JQuery next class
Thanks to all the guys who helped me with that issue.
Now I have problem in setting default values. There are 2 parts.
1st Part:
Say there is a link which loads default item1, item2 and also maybe item2
What I have done is the link pass values through URL like this
index.php?item1=3
Now how do i check this and enable respectively?
I have used PHP to check and set disabled in if nothing is passed, when passed it dosnt set disabled. but now the problem is 2nd item for which value has not been passed is disabled (item1 is enabled and set to default for the ids passed & item2, item3 are disabled) and to enable item2 I have reselect the item1.
Because, according to jquery item2 is unlocked only when item1 changes. How to override this?
2nd part: is similar to first but for certain pages item1 is set to default in code () and nothing is passed via url. Issue is same again.
I know both are of similar issues, just wondering if there is an easy solution rather than changing all part2 to part1 i.e passing item1 via url (I have to manually go into each page and change :( ).
Hey you need to check the value of Parameter by its name through This link. And Check whether value is null or not.and Do perform your operation on not null value.
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
This way you can call function to get value:
var Value = getParameterByName("Item1");
You can use a function to parse the querystring from jQuery.
QueryString (Taken from this SO answer)
(function($) {
$.qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Javascript
var item1 = $.qs('item1');
if (item1) {
// do something...
} else {
// set a default value...
}

Unchecked checkbox returns value as "undefined" via Jquery

Jquery
var g = $("#chav_wc:checked").val();
alert(g);
and.. HTML
<input type="checkbox" id="chav_wc" value="1" /></div>
Works fine, but if checkobx is not checked, returns value as "undefined". How can I set it to return "0" instead when not checked? Thx.
EDIT (solution)
Solution if someone encounters same challenge (thx 2 Dave & insertusernamehere)..
var g = ($('#chav_wc').is(':checked') ? 1 : 0 );
have you tried:
$('#chav_wc').is(':checked');
You could do it like this:
var g = ( 'undefined' == typeof $("#chav_wc:checked").val() ? 0 : 1 );
I use a function like this in my applications to simplify things.
function is_checked(id){
var $check = $('#'+id);
if($check.prop('checked')){
return 1;
}
else{
return 0;
}
}
Use $("#chav_wc").val(); else your selector don't match the checkbox and returns undefined.

Php variable to JavaScript

How to add the value of php variabele to jquery variable and adds them,i have a form that will take a value and post to second page where second page contains a div panel where the form checkboxes values are adding and subtracting,basically i want to add the submitted value from page1 to page2.Here is the code.I have 3 form values which will be redirected one by one.Whenever user submits the respective button
if($_POST['submit'])
{
$beg=$_POST['basic'];
}
function refreshPrices() {
var currentTotalValue = 0;
var beg=?????
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}
var beg=<?php echo $beg; ?>
Try this:
var beg = '<?php echo $beg ;?>';
if you want to add to the total value you can do this:
currentTotalValue = currentTotalValue + parseInt(beg);
its better to do it this way :
var js_var = '<?=json_encode($php_var);?>';
This way you will be able to transfer any type of data to js (arrays, objects, strings, etc.) and access it easily like this:
js_var['element']
var beg = '<?php echo $beg ;?>';
But this can be only one once during the load of the page. After that we cant assign a server side script to js.
Retrieve value by input class or id like dat
var beg = $("#basic").val();

Get checkboxes on the page with jQuery and put the values into string to send ajax call

What I'm trying to do is use jQuery to grab any checkboxes that are checked on the page. The boxes are dynamically created using a specific ID number of each one for the ID and Value.
What is the easiest way about getting it to grab the values of each checked item? Then check if less than or greater than 3 is checked. If only 3 are checked then send the values of each checkbox to my php script. I'm using a regular button on the page so I will proably have to use the .click method since its not actually part of a form to submit.
I've seen several examples around here but not quite what I'm trying to do.
$('#mybtn').live('click',function(){
$("input[type=checkbox]").each(function() {
// I guess do something here.
)};
)};
the code i believe you are wanting is this
$('#mybtn').live('click',function(){
var num_checked = $("input[type=checkbox]:checked").length;
var checkbox_values = new Array();
if( num_checked > 3 ) {
//its greater than 3
//do what you need to do
} else if( num_checked < 3 ) {
//its less than 3
//do what you need to do
}else {
//it equals 3
//do what you need to do
//go thru and add values to array
$("input[type=checkbox]:checked").each(function() {
checkbox_values.push($(this).val());
});
}
});
if you want to send email of variables you can output array checkbox_values to php
If all your checkboxes are in a form, you can do $('#form_id').serialize();
You can get how many are checked using
$("input[type=checkbox]:checked").length
http://jsfiddle.net/XKRRL/7/
Not really sure what you want to do with the ones that are checked, but the js fiddle loops through the checked ones. From there you could grab id's etc.
full code
$(function() {
$('#mybtn').live('click', function() {
var checkedBoxes = $("input[type=checkbox]:checked"),
checkedNum = checkedBoxes.length;
if(checkedNum === 3){
for(var i=0; i< checkedNum; i++){
alert($(checkedBoxes).eq(i).val());
}
}
});
});
It's simple to grab all checked checkboxes:
var checked = $('input[type=checkbox]:checked'),
count = checked.length;
if (count == 3) {
values = $.map(checked, function(i){
return $(this).val();
});
}
Then do whatever you want on the values array.

Categories