Error while passing checkbox values to a Javascript function - javascript

I have a checkbox which stores values from database table. So it contains an array of values when I display them on my page.
<input type="checkbox" id="chkdelt[<?php echo $id; ?>]" name="chkdelt[]" value="<?php echo $id; ?>">
Above given is the checkbox code.
I have a popup block which shows the count of checked checkboxes.
<div class="popup">
Show count here <span id="numb"></span>
<button type="button" onclick="paz(<?php echo json_encode(chkdelt); ?>);">Click</button>
</div>
And I am able to show the count successfully using this javascript function given below.
// used to show number of checked checkboxes in popup
function dumpInArray(){
var arr = [];
$('.table-responsive input[type="checkbox"]:checked').each(function(){
arr.push($(this).val());
});
return arr.length; //returns no of checked check boxes
}
$('.select_chk').click(function () {
$('#numb').html(dumpInArray()); // output of dumpInArray() written into numb span
});
And I try to pass this array to a Javascript function while clicking the button inside of popup.
My Javascript is given below:
function paz(a)
{
var temp = new Array();
temp = JSON.parse(a);
for(i=0;i<temp.length;i++)
{
alert(temp[i]);
}
}
The values are not passed to paz() in Javascript. Rest works fine. I want to pass the values of all checked checkboxes to the paz() when I click the button in the popup div.
Thanks. Help???

You need to pass argument to JavaScript function as a string.
You're passing them as a variable which in turn will be becoming as undefined.
To pass argument as a string use function_name('arg') or function_name("arg").
So in your code change:
<button type="button" onclick="paz(<?php echo json_encode(chkdelt); ?>);">Click</button>
to
<button type="button" onclick="paz('<?php echo json_encode(chkdelt); ?>');">Click</button>
Also I'll suggest you to use <input type="button" /> Instead of <button> & I think if chkdelt is variable name in php you'll need to use $ sign before it and use json_encode($chkdelt).
Hope it'll help you.. Cheers :)!

Related

Change a button's class using js when php is displaying the buttons in a while loop

`<?php
$i = 0;
$testcount = 0;
while($testcount < 8) {
if($i == 0) {
?>
<input id="info" type="hidden" value="hi">
<?php
} else if ($ == 1) {
?>
<input id="info" type="hidden" value="test">
<?php
}
?>
<button onclick="test()" class="btnT">Hello</button>
<?php
$testcount++;
}
?>
<style>
.test1 {
background-color: cyan;
color: black;
}
</style>
<script type="text/javascript">
function test () {
$(".btnT").addClass("test1");
}
</script>`
Ignore the if statement, I have not yet implemented it to the js
I am displaying buttons using php while loop without any text nor class. A class is determined using an if statement using php where they will hold a hidden input value which will then be pushed to javascript which will then add a class depending on the value of the hidden input, I am then trying to remove and add another class to only one individual button displayed in the while loop. I either get the first button to get the change, or it changes all of the buttons, and not the individual button that I clicked. Please help, Thank you!
My biggest question is how to make each button inside the while loop to have the event occur individually, instead of all of them. I know that it is because I have the code to add a class to the button class, I tried replacing the button class with an id, but that way, only the first button will get the new class added and not the rest of the buttons. Hopefully there is a solution for each button to act separately
When you create your while loop you can append the $testcount to the end of an ID for the button, this way each button will have its own unique ID, but still have a 'template' name that you can use in javascript.
<?php
$i = 0;
$testcount = 0;
while($testcount < 8) {
echo '<button id="btn'.$testcount.'" onclick="test('.$testcount.')" class="btnT">Hello</button>';
$testcount++;
}
?>
Afterwards you should get 7 buttons with ID's btn1, btn2, btn3, btn4... etc
Then in Javascript you can run a function based off each button like this:
function test(x) {
var myButton = document.getElementById('btn' + x);
myButton.classList.add("test1");
// Any more JS logic you have
}
When you click, for example, button #2, the ID of that button should be 'btn2'. The onclick of the button will send the number '2' as an argument to the JS function. The variable myButton will get the element by the ID of the btn + the number you gave it to create a string like 'btn2', then based off that you now know which button was pressed, and you are able to run actions based off that. Using your example you added the class 'test1' to that button.

Jquery changevalue or arraypush when checkbox are checked

I have input like this(Looping input form) :
<input id="check_<?php echo $value->id; ?>" value="<?php echo $value->id; ?>" type="checkbox" checked class="check_table get-report-filter">
and hidden input like this :
<input class="hiddenakun" type="hidden" name="hiddenakun" />
this my jquery :
var akun = [];
$('.get-report-filter').each(function() {
$('.get-report-filter').on('click', function() {
akun.push($(this).val());
}
});
my point is, I want to push each array data checked to .hiddenakun, but my code not working, I know it cause every time I write wrong code, datepicker wont work.
You can use .map() along with .get() to create an array of :checked checkboxes values
var akun = $('.get-report-filter:checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
If you want to set the value of checked event, then bind an event handler
var elems = $('.get-report-filter');
elems.on('change', function() {
var akun = elems.filter(':checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
});
Note, datepicker wont work. it's due to syntax error.
Try this:
$('.get-report-filter').each(function(){
if($(this).is(':checked'))
{
akun.push($(this).val());
}
});
// It will push the checked checkbox values to akun
You need more strict checker finder. Not all checkbox, but checked checboxes. For this purpose you can use pseudo class finder
$('.get-report-filter:checked').each
Find info here
https://api.jquery.com/checked-selector/

Serialize form data of a certain form out ot many, if a certain field has value jQuery

I have a page with a couple of forms (number is different, as they are loaded dynamically). I am able to cycle through every form on the page and serialize its data to send to my server. I was wondering if it's possible to only serialize/add data to the array only if a checkbox in any given form is ticked (and that gives it a value I need to use)?
Here is my code:
Javascript
$('body').on('click', '.saveStates', function () {
$('.states_list').each(function (key, value) {
forms.push($(this).serialize());
});
HTML
<form class="states_list">
<input type="checkbox" class="selected_state" name="active_state" value="<?php echo $state['id']; ?>"
<input type="text" class="col-md-10" name="pdf_price" id="pdf_price" value="<?php echo $state['pdf_price']; ?>">
</form>
<button type="button" class="saveStates btn btn-success">Save</button>
I need to check if the checkbox with class selected-state has a value (is ticked), and then add that form to the forms array. I was thinking of doing something like this:
$('.states_list').each(function (key, value) {
if($('.selected_state').val()){
forms.push($(this).serialize());
}
});
But that does not work.
Any help is welcome.
You could filter it using .has():
$('body').on('click', '.saveStates', function() {
$('.states_list').has('.selected_state:checked').each(function(key, value) {
forms.push($(this).serialize());
});
});
But you code could just be:
$('body').on('click', '.saveStates', function() {
var forms = $('.states_list').has('.selected_state:checked').serializeArray();
console.log(forms)
});
I'm not sure I get the issue.
If you only need to check whether the checkbox has been checked in order to send the form you could
if ($(this).is(":checked")) forms.push($(this).serialize());

window.open doesn't do anything

I'm trying to show some info in a pop-up window usig a window.open.. but when I click nothing happens.
This is the function that opens a new window.
function goNewWin(sell_code){
// Set height and width
var NewWinHeight=1000;
var NewWinWidth=1000;
// Place the window
var NewWinPutX=10;
var NewWinPutY=10;
//Get what is below onto one line
TheNewWin =window.open("renovations_history.php?sell_code=" + sell_code,
'Renovaciones','fullscreen=yes,toolbar=no,location=no,status=no,menubar=no,scrollbars=no');
//Get what is above onto one line
TheNewWin.resizeTo(NewWinHeight,NewWinWidth);
TheNewWin.moveTo(NewWinPutX,NewWinPutY);
}
</script>
Here's the HTML, with some PHP.
<form>
<input type="button" value="Renovaciones" onClick="goNewWin(<?php echo $row['sell_code']; ?>)">
</form>
Nor it works with:
Renovaciones
It's 2:22 am and I can think straight, please help.
You need to add single quotes to the JavaScript function call:
<?php
$sell_code = $row['sell_code'];
?>
<input type="button" value="Renovaciones" onClick="goNewWin('<?php echo $sell_code]; ?>')">
Without it, Javascript will consider your $row['sell_code'] as a javascript keyword.
You need to pass it as a string (function parameter).
Reference
if $row['sell_code'] is a string the you can use
$sellCode = $row['sell_code'];
onClick="goNewWin('<?php echo $sellCode; ?>')">

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Categories

Resources