PHP associative array null in Javascript function - javascript

I have a PHP webpage containing 6 textboxes as given below:
<html>
<script type="text/javascript">
function add()
{
//PHP associative array not storing properly in JS array
var array = JSON.parse(<?php echo json_encode($elementsindex); ?>);//getting array
//JS array elements not printing
for(var i in array)
{
alert("key = "+i+" and value = "+array[i]);
}
for(var key in array)
{
if(array[key]===null || array[key]===0)//for loop not executing
{
var valtoadd = 5;
array[key] = valtoadd;//add value to index IN ARRAY
var textbox = document.getElementById(key);
textbox.value = valtoadd;//add value to textbox
}
}
}
</script>
<body>
<form method="POST" action="">
<div id="operation">
<input type="text" id = "5E" name="5E" value="">
<input type="text" id = "4E" name="4E" value="" >
<input type="text" id = "3E" name="3E" value="">
<input type="text" id = "2E" name="2E" value="">
<input type="text" id = "1E" name="1E" value="">
<input type="text" id = "0E" name="0E" value="">
</div>
....rest of the code
</form>
..php code
I have a PHP code in the same page that invokes the Javascript function add() on a particular buttonclick() which is working perfectly:
<?php
include 'footer.php';
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['PUSH']))
{
//I am creating an associative array
$elementsindex = array("0E"=>0 ,"1E"=>0,"2E"=>0, "3E"=>0, "4E"=>0, "5E"=>0);
echo '<script type="text/javascript">';
echo 'add();'; //invoking JS function
echo '</script>';
}
?>
However in the Javascript function add(), the PHP array is not getting stored in var array. Also, the array elements are not printing in the alert box and the code never executes the for(var key in array) loop.
I am sure that the associative array is being passed correctly (the Javascript function is invoked successfully), but maybe not being received at the JS function because initially all the values in the key-value pair are zero (required for the project).

This code stores the $a into an object variable. I simply change the way to obtain the value.
var obj = <?php echo json_encode($a); ?>;
for (var i in obj)
{
alert("key = " + i + " and value = " + obj[i]);
}

Related

how to set value to specific object of array object in javasript

I have to write inputbox inner a looping statement.
let say I have 3 times loop
<?php
for($i = 0; i<3;i++){
?>
<input type="number" id="numb" onkeyup="getvalue(this.value)"/>
<span id="result"></result>
<?php
}
?>
<script>
function getvalue(val){
var res= parseInt(val)*10;
if(isNaN(res) == true){
res = 0;
}
document.getElementById('result').value = res;
}
</script>
the question is, how to set every value I type in inputbox only settbthe result
inner span from its row index only
You can access the input that the user is typing in it bye getting the event object and the target property of that. That event.target (input element) has a property called nextElementSibling.
Use the nextElementSibling to access the next element after the input which here it is the span.
No need to use id or other methods
Change the input element to:
<input type="number" class="numb" onkeyup="getvalue(event)"/>
Change the script tag content to:
function getvalue(event) {
var input = event.target;
var val = input.value;
var res = parseInt(val) * 10;
if (isNaN(res) == true) {
res = 0;
}
input.nextElementSibling.textContent = res;
}
You might have more luck trying an approach like this. Remove the ID attributes from the elements - you can replace with class names if you like or remove entirely from the span element as it should not necessarily be required to allow you to target it programmatically. If you use sibling selectors you can use the target attribtute of the event ( in this case keyup within the number element ) and then traverse the DOM to find the span...
<?php
for($i = 0; $i<3; $i++){
?>
<input type="number" class="numb" onkeyup="getvalue(event)"/>
<span class="result"></span>
<?php
}
?>
<script>
function getvalue(e){
var node=e.target.nextElementSibling;
var res=parseInt(e.target.value) * 10;
if( isNaN(res) )res=0;
node.textContent=res;
}
</script>
function getvalue(e){
var node=e.target.nextElementSibling;
var res=parseInt(e.target.value) * 10;
if( isNaN(res) )res=0;
node.textContent=res;
}
<input type="number" onkeyup="getvalue(event)" />
<span></span>
<input type="number" onkeyup="getvalue(event)" />
<span></span>
<input type="number" onkeyup="getvalue(event)" />
<span></span>
You can set an id for each input and it related result span. The id will just be the $i of the for loop. This will help to easily access the specified result span in the getvalue function:
<?php
for ($i = 0; $i < 3; $i++) {
?>
<div>
<input type="number" data-input-id="<?php echo $i; ?>" onkeyup="getvalue(this)" >
<span class="result-<?php echo $i; ?>"></span>
</div>
<?php
}
?>
<script>
function getvalue (element) {
const inputId = element.dataset.inputId;
const val = element.value;
let res = parseInt(val) * 10;
res = isNaN(res) ? 0 : res;
document.querySelector(`.result-${inputId}`).innerText = res;
}
</script>

Dynamically set global JS variables

I am wondering on how to dynamically set JS values. To better understand what I am trying to accomplish, here's a php example:
$first;
$second;
$third;
$my_array = ('first' => 'val_1','second' => 'val_2','third' => 'val_3');
foreach ($my_array as $key => $value){
$$key = $value;
}
let's say you have a ton of input boxes with a unique ID in html form and you want to use the id as a global variable using jquery or js, that's when I am a bit confused how I can dynamically assign already defined global variables from an Each statement.
The type of html I want to identify through js.
<input id='first' value='val_1'>
<input id='second' value='val_2'>
<input id='third' value='val_3'>
The JS/jquery code
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
/* now what... */
});
in the php example the extra dollar sign make the dollar to say I want to populate a variable named like the variable stored in $key. I am wondering if the same can be accomplished with JS or jquery.
The purpose is to manage the amount of values only by adding inputs to the HTML form without the need for altering the JS code considerably.
This isn't good programming style in PHP or JavaScript. Just use an array instead:
var values = [];
$('input').each(function() {
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
values[item_id] = item_value;
});
console.log('first = ' + values['first'] + ', second = ' + values['second']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="first">First: </label>
<input id="first" type="text" value="hello" />
<label for="second">Second: </label>
<input id="second" type="text" value="world!" />
<label for="third">Third: </label>
<input id="third" type="text" />
You can use eval function
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
eval(item_id+'='+item_value);
});
For example
var v1 = 'first';
var v2 = 'second';
var val1 = 10;
var val2 = 20;
var first;
var second;
eval(v1+'='+val1);
eval(v2+'='+val2);
console.log('first='+first,'second='+second);

Count values from <input type="text"

Hello i want to count the ids inside a input type="text"
the values return as this 1,4,6 etc
<input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
here the only javascript version :
var testme = function() {
var myInput = document.getElementById('selected_ids');
var myValue = myInput.value;
var myCount = myValue.split(',').length;
document.body.innerHTML += '<br>myValue = ' + myValue + ' | myCount = ' + myCount;
}
<input type="text" class="selected_ids" value="1,4,6" name="selected_ids[]" multiple="yes" id="selected_ids" />
<button onclick='testme()'>test me</button>
You can use split function. for example :
var curval = document.getElementById('selected_ids').value;
var curval_arr = curval.split(',');
var cnt = curval_arr.length;
First, your input type needs to be text and not hidden. It's not possible to enter values in a hidden text box.
So your text box should be :-
<input type="text" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
Now suppose the user enters 1,4,6 into the text box(make sure the numbers are separated by a comma). Then on the PHP side you can access as follows.
<?php
$array = explode(',', $_POST['selected_ids']); //this array consists all the elements.
//To get length, do :-
count($array);
?>

Unable to check if a javascript checkbox array element is checked or not?

What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}

how to fetch values from array input in javascript

How do I properly fetch values from array in javascript:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz.value;
var qtybuy = document.yoh.qbuys.value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal;
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid" value=""><br/>
Cost: <input type="text" name="coz" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal" value=""></br>
</form>
</body>
<?php } ?>
</html>
As you can see this program will just multiply the 2 values. One of the values would be fetched from the database, and the other comes from the user.
If I do it this way, I don't get any results:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz[].value;
var qtybuy = document.yoh.qbuys[].value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal[];
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid[]" value=""><br/>
Cost: <input type="text" name="coz[]" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys[]" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal[]" value=""></br>
</form>
</body>
<?php } ?>
</html>
Do I need to include the index manually? What do I need to do to achieve the same results when using arrays.
You can use a name value:
cost=document.yoh.elements['coz[]'].value;
You need to iterate through the arrays. To iterate through an array (or object) in JavaScript:
for (key in arr){
// The key will be set to each key in the array (arr)
// The value at that key will be arr[key] (like always)
}
I'm not entirely sure what your goal is, but in general, know that the "[]" syntax is PHP only, JavaScript treats it as any other name (and possibly as a syntax error).

Categories

Resources