pass the input value if checkbox is checked, values are in array? - javascript

<?php include("database/connect.php"); ?>
<form action="" method="post">
<?php
$q = mysqli_query($con,"select * from tbl_user");
while($f=mysqli_fetch_array($q))
{
?>
<input type="checkbox" name="ch[]" value="<?php echo $f['id'];?>"/>
<input type="number" name="qty[]"/><br>
<?php
}
?>
<input type="submit" name="yy" value="Submit"/>
</form>
From above code I want the value of the qty if the check box is checked.
I tried like array_combine and foreach if any one know logic then comment.Thanks in advance.

A number input (unless it is disabled or lacks a name) will always be successful and appear in the data.
A checkbox will only be successful if it is checked.
This means that using PHP's simple array syntax will cause your inputs to get out of sync with each other. The first number input will have the same index as the first checked checkbox, and so on.
To deal with this: Give the inputs explicit indexes.
For example:
<input type="checkbox" name="ch[]" value="<?php echo $f['id'];?>"/>
<input type="number" name="qty[<?php echo $f['id'];?>]"/><br>
Then in the PHP you can:
foreach ($_POST[ch] as $ch_value) {
do_something_with($_POST['qty'][$ch_value]);
}

You can associate a onclick handler in that checkbox and make the onclick function to provide you with the value of qty[] only when it is checked. For that send the reference to the element and the index to the onclick function and use the same index to name the elements ch and qty:
function cbClick(e, index) {
if (e.checked) {
var qty = document.querySelector('input[name="qty['+index+']"]').value;
console.log('cb value '+ e.value);
console.log('qty value' + qty);
}
}
<!-- You will loop the PHP code to give the name to each elements with 0, 1, 2..-->
<input type="checkbox" name="ch[0]" onclick="cbClick(this, 0)" value="cb9" />
<input type="number" name="qty[0]" /><br>
<input type="checkbox" name="ch[1]" onclick="cbClick(this, 1)" value="cb10" />
<input type="number" name="qty[1]" /><br>

Related

How to get value of an hidden input from PHP Foreach loop with javascript

I have tried to get the value of hidden input from the PHP loop using javascript when its input is out focus and it returns all array of values and when I change code some, it returns only the first value.
Here is a PHP for each loop.
<?php
$s = 0;
foreach ($examSchedule as $key => $student) { ?>
<input type="hidden" id="student" name="student[]" value="<?php echo
$student['student_id'] ?>">
<?php }
?>
And it returns inputs like this
<input type="hidden" id="student" name="student[]" value="388">
<input type="hidden" id="student" name="student[]" value="389">
<input type="hidden" id="student" name="student[]" value="390">
<input type="hidden" id="student" name="student[]" value="391">
<input type="hidden" id="student" name="student[]" value="392">
<input type="hidden" id="student" name="student[]" value="393">
When I try to get the value I got the array with all the values
$("input").focusout(function(event){
event.preventDefault();
var students= $('[name="student[]"]').map(function () {
return this.value;
});
console.log(students);
}
Results are
n.fn.init(6) ["388", "389", "390", "391", "392", "393", prevObject:
n.fn.init(6), context: document]
And when i try to use
$("input").focusout(function(event){
event.preventDefault();
var students = $('#student').val();
console.log(student);
}
It just display only the first value.
How can I get the value of specific input when the out focus event is applied to a certain input field.
Use "this" keyword in javascript code:
"this" keyword will provide you the input element on which "focusout" event occurs
$("input").focusout(function(event){
event.preventDefault();
var students = $(this).val();
console.log(student);
}

How to send unchecked checkbox value that is not 0/false or 1/true but integers form 1 to 32

I have an array of checkboxes with some additional columns. When one is checked it its value is added on a MySQL table. Values from 1 to 32.
When one of them is unchecked I need to send MySQL the same data and with ON DUPLICATE KEY UPDATE just to update the rest of the columns if changed.
I don't want to send 0 or 1 but the value from 1 to 32 in this case.
<input type="checkbox" name="add_value[]" id="add-value" value="{$values.id_value}"/><p>{$values.name} </p>
The way to do this is like:
<input type="checkbox" name="1bit" />
<input type="checkbox" name="2bit" />
<input type="checkbox" name="4bit" />
<input type="checkbox" name="8bit" />
<input type="checkbox" name="16bit" />
Then in your receiver, something like
<?php
$num = 0;
if ($_REQUEST["2bit"]===1) $num += 1;
if ($_REQUEST["4bit"]===1) $num += 2;
...
?>
Then you can submit $num to your database. You also should add checks to make sure your field names (1bit, 2bit, etc) exist in the $_REQUEST array
Expanding on my comment to what he's asking, you can do something like this:
$checkBoxValue = (ISSET($_POST['name']) ? 1 : 0;
Then just use a standard sql query to do what you need with it.
If you need a specific value for the checkbox you can use hiddens in conjunction to hold the value for you too.
Or even one more option you can do something like this:
<form action="" method="post">
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
<input type="submit" />
</form>
<?php
for($i = 1; $i<=count($_POST); $i++) {
$_POST["status_$i"] = isset($_POST["status_$i"]) ? $_POST["status_$i"] : 0;
}
var_dump($_POST);

jQuery undefined value click event

I have some forms with custom id's.
All of them has some of the hidden fields and one number and submit field. I would like to get the number field's value in a variable with this function
$(".formclass").click(function () {
console.log(this.id);
var id = this.id;
var value = $(id).find("input[type='number']").val();
console.log(value);
});
The return output in the console is
form-103
undefined
tried with .children() or .attr('value'), none of them worked.
here is an example:
<form id="form-<?=$id_val?>" class="formclass"
enctype="multipart/form-data"
method="POST"
action="/etlap/">
<input type="hidden" name="add-to-cart"
value="<?php echo htmlspecialchars($pid); ?>"/>
<input type="number" id="quantity"
name="quantity" min="1"
required="required"
pattern="[0-9]*"
max=<?= $floor_available_stock ?>
inputmode="numeric"
value="1"/>
<input type="hidden" name="variation_id"
value="<?php echo htmlspecialchars($getvar1); ?>"/>
<input type="submit" value="Add to cart"/>
</form>
Have not tried but may be you should use a css selector in the line 4. Try using the selector like :
var value = $("#"+id).find("input[type='number']").val();
If you want to find the number inside the element you clicked you can simply do
$("input[type='number']", this).val();
When using this version of the selector, the second element will be the parent that is used to search children of. Normal selectors are effectively wrappers around $(selector, document)
Ref. http://api.jquery.com/jQuery/#jQuery1

How to create a dynamic jQuery string of checkbox id's

Im at my wits end with this one.
When i click a checkbox, I want add the ID of the checkbox to a comma separated string in an input below. I have this working however, what I can not do is remove the ID and its comma if it already exists in the input field (checking and unchecking).
Simple form.
<form>
<input class="iteminput" type="checkbox" value="1" id="1" name="<?php echo $title; ?>">
<input class="iteminput" type="checkbox" value="2" id="2" name="<?php echo $title; ?>">
<input class="iteminput" type="checkbox" value="3" id="3" name="<?php echo $title; ?>">
<!-- Note that this field may or may not have an existing string of ID's (1,2,3) from previous saves -->
<input type="text" id="excludelist" value="<?php echo $saved-string; ?>">
</form>
jQuery(document).ready(function(){
jQuery('.iteminput').on('click', function(){
var id = jQuery(this).attr('ID');
var string = jQuery('#excludelist').val();
var newstring = string + id + ',';
jQuery('#excludelist').val(newstring);
})
})
You can get the value of the input box, and use the split method to split the string of IDs into an array. At that point you can check if the ID you are looking for is in that array. Example:
const id = 3;
const inputValue = $('input[type=text]').val();
// Split the IDs into an array by comma.
const currentIds = inputValue.split(',');
if (currentIds.indexOf(id) === -1) {
// ID has not yet been added to the input box.
// We can add it to the array here, and
// update it later.
currentIds.push(id);
} else {
// ID is in the current list of IDs. We
// can remove it like this:
currentIds.splice(currentIds.indexOf(id), 1);
}
// Finally, we can reset the input string
// with the new values we set above.
$('input[type=text]').val(currentIds.join(','));
See:
String.prototype.split()
Array.prototype.indexOf()
Array.prototype.push()
Array.prototype.splice()
Array.prototype.join()
Why not just rebuild it?
var $iteminputs = $('.iteminput');
$iteminputs.on('change', function(){
var ids = $.map($iteminputs.filter(':checked'), function(element){ return element.id; });
$('#excludelist').val(ids.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="iteminput" type="checkbox" value="1" id="1" name="title1">
<input class="iteminput" type="checkbox" value="2" id="2" name="title2" checked>
<input class="iteminput" type="checkbox" value="3" id="3" name="title3" checked>
<!-- Note that this field may or may not have an existing string of ID's (1,2,3) from previous saves -->
<input type="text" id="excludelist" value="2,3">

create a select and populating it using a php function, after pressing a button

I have been trying a lot of things, but I dont get the solution.
I have a form which has this structure:
<form>
<input type="text" name="nombre">
<input type="submit" name="first submit">
<input type="text" name="address">
</form>
when I submit on "first submit"... I want to put on that form, a select, which will be populated with the results of a php function (passing the "name" as function variable)
the php function, receives the name written and returns an array, which needs to be looped, to get every element as an option of the select
the form at the end need to look as:
<form mode="post" action="somephp.php" >
<input type="hidden" name="nombre" value=(name inserted before)>
<input type="hidden" name="nombre" value=(address inserted before)>
<select>
<option value="i">$function_return[i]</option>
<option value="i">$function_return[i]</option>
<option value="i">$function_return[i]</option>
</select>
<input type="submit" name="second submit">
<form>
I have waste a lot of time... but im getting crazy.... could anyone save my life?
thanks
pd: adding the code i have tried:
<script>
function datos() {
var min = 0,
max = <?php echo count(obtener("manuel")) ?>,
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = <?php echo obtener("manuel")[i][element] ?>;
select.appendChild(opt);
}
}
</script>
</head>
<body>
<input type="button" value="Submit" onclick="datos()"/>;
</body>
</html>
<?php
function obtener($link) {
$buscar= (too large, simply it receives things, its only a practice exercise, i give to every name things like "color" "clothes" etc)
return $buscar;
}
?>

Categories